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

题目分析

之前也研究了一段时间的数位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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值