zoukankan      html  css  js  c++  java
  • HDU 3709 Balanced Number(数位DP)题解

    思路:

    之前想直接开左右两边的数结果爆内存...

    枚举每次pivot的位置,然后数位DP,如果sum<0返回0,因为已经小于零说明已经到了pivot右边,继续dfs只会越来越小,且dp数组会炸

    注意一下一些细节:dp开long long,注意前导零只能算一次

    代码:

    #include<iostream>
    #include<algorithm>
    #define ll long long
    const int N = 50000+5;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    int dig[20];
    ll dp[20][20][2000];
    ll dfs(int pos,int piv,int sum,bool limit){
        if(pos == -1) return sum == 0? 1 : 0;
        if(sum < 0) return 0;
        if(!limit && dp[pos][piv][sum] != -1) return dp[pos][piv][sum];
        int top = limit? dig[pos] : 9;
        ll ret = 0;
        for(int i = 0;i <= top;i++){
            int tot;
            if(pos > piv){
                tot = sum + (pos - piv)*i;
            }
            else if(pos < piv){
                tot = sum - (piv - pos)*i;
            }
            else{
                tot = sum;
            }
            ret += dfs(pos - 1,piv,tot,limit && i == top);
        }
        if(!limit) dp[pos][piv][sum] = ret;
        return ret;
    }
    ll solve(ll x){
        int pos = 0;
        if(x == -1) return 0;
        while(x){
            dig[pos++] = x % 10;
            x /= 10;
        }
        ll ret = 0;
        for(int i = 0;i < pos;i++){
            ret += dfs(pos - 1,i,0,true);
        }
        return ret - pos + 1; //前导零只能算一次
    }
    int main(){
        int T;
        ll l,r;
        scanf("%d",&T);
        while(T--){
            memset(dp,-1,sizeof(dp));
            scanf("%lld%lld",&l,&r);
            printf("%lld
    ",solve(r) - solve(l - 1));
        }
        return 0;
    }
    


  • 相关阅读:
    何时使用Hibernate (Gavin King的回答)
    Transaction in ADO.net 2.0
    CollectionClosureMethod in .Net
    如何实现真正的随机数
    如何测试私有方法?(TDD)
    try catch 块的使用原则
    多态小quiz
    A simple way to roll back DB pollution in Test
    一个画图程序的演变
    当前软件开发的反思
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9408772.html
Copyright © 2011-2022 走看看