zoukankan      html  css  js  c++  java
  • HDU 3709 数位dp

    A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9, for left part and right part, respectively. It's your job 
    to calculate the number of balanced numbers in a given range [x, y].

    InputThe input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 10 18).OutputFor each case, print the number of balanced numbers in the range [x, y] in a line.Sample Input

    2
    0 9
    7604 24324

    Sample Output

    10
    897

    可以在solve函数中枚举支点,进行dfs。
    返回 cnt - (k-1) 是因为枚举的k个支点都会认定 0 是平衡数,所以减去(k-1)个重复的 0
    不要认为solve(r)-solve(l-1)会将多判定的0正确的消掉,因为 r 与 l-1 的位数不同所以重复判定出来的0的数量不等



    #include<cstdio>
    #include<cstring>
    #define ll long long
    
    int digit[35];
    ll dp[20][20][1600];
    
    ll dfs(int d, int sum, int x, bool shangxian){
        if(d==0)return sum == 0;
        if(sum < 0)return 0;
        if(!shangxian && dp[d][x][sum]!=-1)
            return dp[d][x][sum];
        int maxn = shangxian?digit[d]:9;
        ll cnt = 0;
        for(int i=0;i<=maxn;i++){
            cnt += dfs(d-1,sum+(d-x)*i,x,shangxian && i==maxn);
        }
        return shangxian?cnt:dp[d][x][sum] = cnt;
    }
    ll solve(ll x){
        int k = 0;
        memset(digit,0,sizeof(digit));
        while(x){
            digit[++k] = x%10;
            x /= 10;
        }
        ll cnt = 0;
        for(int i=1;i<=k;i++)
            cnt +=dfs(k,0,i,1);
        return cnt-(k-1);
        // 枚举的不同支点都判定 0 为平衡数,所以减去(k-1)个重复的 0
    }
    int main(){
        int t;
        ll l, r;
        scanf("%d",&t);
        memset(dp,-1,sizeof(dp));
        while(t--){
            scanf("%lld%lld",&l,&r);
            printf("%lld
    ",solve(r)-solve(l-1));
        }
        return 0;
    }
    View Code


  • 相关阅读:
    Unable to load the specified metadata resource
    Web开发人员速查卡
    vs 中大括号之间垂直虚线显示
    第4届华为编程大赛决赛试题解答(棋盘覆盖)
    assert()函数用法总结
    Win7安装VC++6.0已知的兼容性问题的解决方法
    VC6打开一个文件或工程的时候,会导致VC6崩溃而关闭
    浮点数取整.
    1.4 VC6.0在win7下安装的兼容性问题以及解决办法
    华为编程大赛_将字符数组内的数字排序
  • 原文地址:https://www.cnblogs.com/kongbb/p/10825639.html
Copyright © 2011-2022 走看看