UVA 10157 Expressions

题意:老是RE,看了题解:点击打开链接
#include <cstdio>
#include <cstring>
using namespace std;
const int LEN=100;
const int NMAX=300;
const int DMAX=150;

int f[NMAX+1][DMAX+1][LEN];
bool vis[NMAX+1][DMAX+1];

void add(int a[],int b[]){
    int c = 0;
    for(int i = 0; i < LEN; ++i){
        int n = (c+a[i]+b[i]) % 10;
        c = (c+a[i]+b[i]) / 10;
        a[i] = n;
    }
}

void sub(int a[],int b[]){
    int c = 0;
    for (int i = 0; i < LEN; i++){
        a[i] = a[i] - b[i] + c;
        if (a[i] < 0){
            a[i] += 10;
            c = -1;
        }
        else c = 0;
    }
}

void mul(int a[],int b[]){
    int c[LEN];
    memset(c,0,sizeof(c));
    int I = LEN;
    while(--I >= 0 && a[I] == 0);   //去除前导0
    ++I;
    int K = LEN;
    while(--K >= 0 && b[K] == 0);
    ++K;
    for(int i = 0; i < I; ++i)
        for(int k = 0; k < K && i+k < LEN; ++k)
            c[i+k] += a[i]*b[k];
    int d = 0;
    for(int i = 0; i < LEN; ++i)
    {
        int n = (d + c[i]) % 10;
        d = (d + c[i]) / 10;
        c[i] = n;
    }
    memcpy(a,c,sizeof(c));
}

void print(int a[]){
    int i = LEN;
    while(--i > 0 && a[i]==0);
    for (int j = i; j >= 0; j--)
        printf("%d",a[j]);
    printf("\n");
}


void cal(int n,int d){
    if(vis[n][d])
        return;
    vis[n][d] = 1;
    if(n % 2 == 1)
        return;
    if(n == 0){
        f[n][d][0]=1;
        return;
    }
    if(d == 0)
        return;
    int t[LEN];
    for(int i = 0; i < n; i+=2){
        cal(i,d);
        cal(n-2-i,d-1);
        memcpy(t,f[i][d],sizeof(t));
        mul(t,f[n-2-i][d-1]);
        add(f[n][d],t);
    }
}

int main(){
    int n,d;
    while(scanf("%d%d",&n,&d)==2){
        if(d==0 && n==0){
            printf("1\n");
            continue;
        }
        else if(d == 0){
            printf("0\n");
            continue;
        }
        else if(n == d*2){
            printf("1\n");
            continue;
        }
        memset(f,0,sizeof(f));
        memset(vis,0,sizeof(vis));
        cal(n,d);    //计算深度不超过d的可能
        cal(n,d-1);
        int ans[LEN];
        memcpy(ans,f[n][d],sizeof(ans));
        sub(ans,f[n][d-1]);
        print(ans);
    }
    return 0;
}



你可能感兴趣的:(UVA 10157 Expressions)