Jumbled String【Gym - 10193J】【2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018) 】

题目链接


  题目让你求一个字符串是否符合这样条件——有a个“00”串,与b个“01”,c个“10”串以及d个“11”串这样的组成串是否存在。

  我利用了数学的知识来求这道题,假设这样的式子成立,那么我们假设成立字符串中有n个‘0’与m个‘1’,那么我们可以知道对于“00”串的个数为n*(n-1)/2,对于“11”串的个数为m*(m-1)/2,“01”串与“10”串的个数总和为n*m;所以我们可以利用这个等式来确定是否可以有解。那么n、m的值如何确定?n=sqrt(2*a)+1;m=sqrt(2*d)+1。然后以此判断是否成立就行,但是还有另外的条件,需要特判的是a、b、c均等于0且d!=0或者b、c、d均等于0而a!=0的情况,其余就没有坑点了。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
int A, B, C, D;
int n, m;       //n个‘0’、m个‘1’
bool check()
{
    n=m=0;
    if(B | C)
    {
        n=(int)sqrt(2*A)+1;
        if(2*A!=n*(n-1)) return false;
        
        m=(int)sqrt(2*D)+1;
        if(2*D!=m*(m-1)) return false;
    }
    if( (B+C)!=n*m ) return false;
    if(!n && !m) return false;
    return true;
}
int main()
{
    while(scanf("%d%d%d%d",  &A, &B, &C, &D)!=EOF)
    {
        if(!A && !B && !C)
        {
            m=(int)sqrt(2*D)+1;
            if(m*(m-1)==2*D)
            {
                for(int i=1; i<=m; i++) printf("1");
                printf("\n");
            }
            else
            {
                printf("impossible\n");
            }
            continue;
        }
        if(!D && !B && !C)
        {
            n=(int)sqrt(2*A)+1;
            if(2*A==n*(n-1))
            {
                for(int i=1; i<=n; i++) printf("0");
                printf("\n");
            }
            else
            {
                printf("impossible\n");
            }
            continue;
        }
        if(!check()) { printf("impossible\n"); continue; }
        if(!m)
        {
            for(int i=1; i<=n; i++) printf("0");
            printf("\n");
        }
        else if(!n)
        {
            for(int i=1; i<=n; i++) printf("1");
            printf("\n");
        }
        else
        {
            int num = C/n;
            if(C%n==0)
            {
                for(int i=1; i<=num; i++) printf("1");
                for(int i=1; i<=n; i++) printf("0");
                int rest = m - num;
                for(int i=1; i<=rest; i++) printf("1");
                printf("\n");
                continue;
            }
            int tmp = n - ( C - num*n );
            for(int i=1; i<=num; i++) printf("1");
            for(int i=1; i<=tmp; i++) printf("0");
            printf("1");
            for(int i=1; i<=n - tmp; i++) printf("0");
            int rest = m - num - 1;
            for(int i=1; i<=rest; i++) printf("1");
            printf("\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/83446199