uva10759 手算多项式分解 或者dp

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef unsigned long long ULL;

ULL a[555];
ULL b[555];

ULL gcd(ULL x, ULL y){
    return y?gcd(y,x%y):x;
}
/**
手算多项式分解
把原题变为(x^1+x^2+x^3+x^4+x^5+x^6)^n 求指数大于等于x的项数的系数之和
**/

int main()
{
//    freopen("data.in", "r", stdin);
    int n, x;
    ULL ans1, ans2;
    while(scanf("%d%d", &n, &x) != EOF && n+x){
        memset(a, 0 ,sizeof a);
        for(int i = 1; i <= 6; i++)
            a[i] = 1;
        for(int k = 1; k < n; k++){
            memset(b, 0, sizeof b);
            for(int i = k; i <= 6*k; i++){
                for(int j = 1; j <= 6; j++){
                    b[i+j] += a[i];
                }
            }
            memcpy(a, b, sizeof b);
        }
        ans1 = ans2 = 0;
        for(int i = 0; i <= n*6; i++){
            if(i >= x) ans1 += a[i];
            ans2 += a[i];
        }
        if(ans1 == 0)puts("0");
        else if(ans1 == ans2)puts("1");
//        else printf("%llu/%llu\n", ans1, ans2);
        else printf("%llu/%llu\n", ans1/gcd(ans1, ans2), ans2/gcd(ans1, ans2));
    }
    return 0;
}
 
 

dp的做法是用f[i][j]存投掷i次得分为j的概率 转移方程很简单  重点是用分数表示 记得用LCM GCD处理同分和约分  保证分数加减的正确性

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef unsigned long long ULL;

ULL f[25][155], e[25][155];
ULL sum1[25][155], sum2[25][155];

ULL gcd(ULL x, ULL y){
    return y?gcd(y,x%y):x;
}

ULL lcm(ULL x, ULL y){
    return x/gcd(x,y)*y;
}

int main()
{
//    freopen("data.in", "r", stdin);
    f[0][0] = e[0][0] = sum1[0][0] = sum2[0][0] = 1;
    for(int i = 1; i <= 24; i++){
        for(int j = i; j <= 6*i; j++){
            ULL FZ = 0, FM = 1, TMP;
            for(int k = max(0, j-6); k < j; k++){
                if(f[i-1][k] == 0) continue;
                TMP = lcm(FM, e[i-1][k]*6);
                FZ = FZ*(TMP/FM) + f[i-1][k]*(TMP/(e[i-1][k]*6));
                FM = TMP;
                TMP = gcd(FZ, FM);
                FZ /= TMP, FM /= TMP;
            }
            f[i][j] = FZ, e[i][j] = FM;
            if(i == j){
                sum1[i][j] = f[i][j];
                sum2[i][j] = e[i][j];
                continue;
            }
            TMP = lcm(sum2[i][j-1], e[i][j]);
            FZ = sum1[i][j-1]*(TMP/sum2[i][j-1])+f[i][j]*(TMP/e[i][j]);
            FM = TMP;
            TMP = gcd(FZ, FM);
            sum1[i][j] = FZ/TMP, sum2[i][j] = FM/TMP;
        }
    }
    int n, x;
    ULL ans1, ans2;
    while(scanf("%d%d", &n, &x) != EOF && n+x){
        if(x > 6*n) puts("0");
        else if(x <= n) puts("1");
        else{
            ans1 = sum2[n][x-1] - sum1[n][x-1];
            ans2 = sum2[n][x-1];
            printf("%llu/%llu\n", ans1, ans2);
        }
    }
    return 0;
}


你可能感兴趣的:(dp,uva,多项式定义)