poj2116

数论
需要细心,模拟过程就可以了,注意给出的字符串有前导0,需要去前导0

#include 
#include 
#include 
#include 
using namespace std;
typedef long long LL;
const int maxn = 50;
char s1[maxn],s2[maxn],s3[maxn];
LL f[maxn];

void init()
{
    f[0] = 1; f[1] = 2;
    for(int i = 2; i < maxn; i++) f[i] = f[i-1] + f[i-2];
}
LL calu(char s[])
{
    int len = strlen(s),cur = 0;
    LL res = 0;
    for(int i = len - 1; i >= 0; i--) res += (s[i] - '0')*f[cur++];
    return res;
}
bool isOK(char s[])
{
    bool OK = true;
    int len = strlen(s);
    for(int i = 1; i < len; i++) if( (s[i]-'0')&(s[i-1]-'0') == 1 ) OK = false;
    return OK;
}
void change(char s[])
{
    while(!isOK(s)) //s中一定存在连续的1
    {
        int index = strstr(s,"11") - s;
        s[index] = s[index + 1] = '0';
        if(index == 0)
        {
            int len = strlen(s);
            for(int i = len-1; i >= 0; i--) s[i+1] = s[i];
            s[len+1] = '\0';
            s[0] = '1';
        }
        else s[index-1] = '1';
    }
}
void trans(LL x,char s[])
{
    if(x == 0)
    {
        s[0] = '0'; s[1] = '\0'; return;
    }
    int cnt = 0,index = 0;
    while(x >= f[cnt]) cnt++;
    for(int i = cnt-1; i >= 0; i--)
    {
        if(x >= f[i])
        {
            x -= f[i]; s[index++] = '1';
        }
        else s[index++] = '0';
    }
}
void myremove(char s[])
{
    if(calu(s) == 0)
    {
        s[0] = '0'; s[1] = '\0'; return;
    }
    int len = 0;
    while(s[len] == '0') len++;
    int index = 0;
    for(int i = len; i < strlen(s); i++) s[index++] = s[i];
    s[index] = '\0';
}
int main()
{
    init();
    while(scanf("%s%s" ,s1,s2) != EOF)
    {
        myremove(s1);
        myremove(s2);
        LL x = calu(s1);
        LL y = calu(s2);
        LL z = x + y;
        change(s1);
        change(s2);
        trans(z,s3);
        change(s3);
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        int len3 = strlen(s3);
        for(int i = 1; i <= len3+2-len1; i++) printf(" ");
        printf("%s\n",s1);
        printf("+");
        for(int i = 1; i <= len3+2-len2-1; i++) printf(" ");
        printf("%s\n",s2);
        printf("  ");
        for(int i = 1; i <= len3; i++) printf("-");
        printf("\n");
        printf("  ");
        printf("%s\n",s3);
        printf("\n");
        memset(s1,0,sizeof(s1));
        memset(s2,0,sizeof(s2));
        memset(s3,0,sizeof(s3));
    }
    return 0;
}

你可能感兴趣的:(数论)