HDU 5456 Matches Puzzle Game(2015 ACM/ICPC Asia Regional Shenyang Online)

来源:互联网 发布:mac系统pdf编辑软件 编辑:程序博客网 时间:2024/05/21 15:17

题目分析

之前也研究了一段时间的数位dp,但是一直没有见到这种形式的,状态看了好半天都不知道怎么找状态,看了别人的博客,也给看懂了,感觉其实也不是特别难,但是这种dp太不好查错了!!首先将式子化为A = B+C,那么我们需要定义状态,dp有4维,第一维很明显是火柴棍数量,第二维是有没有进位,第三位是B还能不能继续放数字,第四位是C还能不能继续放数字。状态转移方程见代码。

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;int n,m;int bit[] = {6,2,5,5,4,5,6,3,7,6}; //每个数需要的火柴棍LL dp[505][2][2][2];void add(LL& x, LL y){ //相加并取模    x =(x+y)%m;}LL dfs(int total,bool digit,bool B,bool C){    LL & ret = dp[total][digit][B][C];    if(ret != -1) return ret;  //记忆化    if(total == 0){        if(!digit && !B && !C) return ret = 1;        return ret = 0;    }    ret = 0;    if(B && C){  //B和C前面均可以放数字        for(int i = 0; i < 10; i++){            for(int j = 0; j < 10; j++){                int sum = bit[i] + bit[j] + bit[(i+j+digit)%10];                if(sum > total) continue;                bool another = (i+j+digit)>=10;  //判断是否有进位                add(ret, dfs(total-sum, another, B, C));                if(i) add(ret, dfs(total - sum, another, !B, C)); //注意如果想当前位不能继续放数字,显然首位不能为0                if(j) add(ret, dfs(total - sum, another, B, !C));                if(i&&j) add(ret, dfs(total-sum, another, !B, !C));            }        }    }    else if(B){        for(int i = 0; i < 10; i++){            int sum = bit[i] + bit[(i+digit)%10];            if(sum > total) continue;            bool another = (i+digit)>=10;            add(ret, dfs(total-sum, another, B, C));            if(i) add(ret, dfs(total - sum, another, !B, C));        }    }    else if(C){        for(int j = 0; j < 10; j++){            int sum = bit[j] + bit[(j+digit)%10];            if(sum > total) continue;            bool another = (j+digit)>=10;            add(ret, dfs(total-sum, another, B, C));            if(j) add(ret, dfs(total - sum, another, B, !C));        }    }    else{        if(digit && total == bit[1]) ret = 1;    }    return ret;}int main(){    int T;    scanf("%d", &T);    for(int kase = 1; kase <= T; kase++){        scanf("%d%d", &n, &m);        memset(dp, -1, sizeof(dp));        printf("Case #%d: %I64d\n", kase, dfs(n-3, 0, 1, 1));    }    return 0;}
0 0
原创粉丝点击