Recover the String
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number ofsubsequences of length 2 of the string s equal to the sequence {x, y}.
In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000.
The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.
If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000.
1 2 3 4
Impossible
1 2 2 1
0110
分析:可以先求出0和1的个数,注意边界情况;
注意到10和01的总个数就是0的个数*1的个数,所以只需构造出10即可;
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <climits> #include <cstring> #include <string> #include <set> #include <map> #include <queue> #include <stack> #include <vector> #include <list> #define rep(i,m,n) for(i=m;i<=n;i++) #define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++) #define mod 1000000007 #define inf 0x3f3f3f3f #define vi vector<int> #define pb push_back #define mp make_pair #define fi first #define se second #define ll long long #define pi acos(-1.0) #define pii pair<int,int> #define Lson L, mid, rt<<1 #define Rson mid+1, R, rt<<1|1 const int maxn=1e5+10; const int dis[4][2]={{0,1},{-1,0},{0,-1},{1,0}}; using namespace std; ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);} ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;} int n,m,k,t; ll a,b,c,d,num1,num2; string ans; int main() { int i,j; scanf("%lld%lld%lld%lld",&a,&b,&c,&d); if(a+b+c+d==0)puts("0"); //特判四个0的情况; else { int c1=1,c2=1; //求出1和0的个数; while(num1<a)num1+=c1,c1++; while(num2<d)num2+=c2,c2++; if(!a&&!b&&!c)c1=0; //特判0的个数为0时; if(!b&&!c&&!d)c2=0; //特判1的个数为0时; if(num1!=a||num2!=d||(ll)c1*c2!=(ll)b+c)puts("Impossible"); //判断是否可行; else { int j=0,now=0; while(j+c1<c)j+=c1,now++,c2--; //在0里面不断插入1; rep(i,0,now-1)ans+='1'; rep(i,now,now+c1-1)ans+='0'; if(c>j)ans.insert(now+c1-c+j,"1"),c2--; //补10; rep(i,1,c2)ans+='1'; //末尾补1; cout<<ans<<endl; } } //system("Pause"); return 0; }