• 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


  • 相关阅读:
    Nero8刻录引导系统光盘镜像图文教程
    C#多线程与并行编程方面的电子书,中英文版本
    [转]C#通过委托更新UI(异步加载)
    [PHP] 6种负载均衡算法
    [GIt] 团队工作效率分析工具gitstats
    [Git] git代码统计
    [Git] 写文章 史上最全文献检索、阅读及管理攻略
    [Git] 谷歌的代码管理
    [JQuery] jQuery选择器ID、CLASS、标签获取对象值、属性、设置css样式
    [Mongo] 解决mongoose不支持条件操作符 $gt$gte:$lte$ne $in $all $not
  • 原文地址:https://www.cnblogs.com/kongbb/p/10825639.html
Copyright © 2020-2023  润新知