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


  • 相关阅读:
    让SVN自动更新代码注释中的版本号
    eclipse 查看jdk的源代码
    Java Abstract class and Interface
    Eclipse在保存的时间格式化
    Java中使用Runtime和Process类运行外部程序
    免费的东西:火箭的社会图标
    最土团购程序一些常见的数据库操作
    PostgreSQL在何处处理 sql查询之四十五
    遇到 dereferencing pointer to incomplete type 该怎么办
    PostgreSQL在何处处理 sql查询之四十四
  • 原文地址:https://www.cnblogs.com/kongbb/p/10825639.html
Copyright © 2011-2022 走看看