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


  • 相关阅读:
    Lodash JS实用类库 数组操作 延时执行 功能强大
    7.【nuxt起步】-Nuxt与后端数据交互
    vue图片懒加载
    猎鹰与龙飞船基于 Linux,采用 C++、Chromium 与 JS 开发
    | 和 ||,& 和 && 的区别
    Linux安装.net core
    Linux下程序后台运行:nohup和&
    vuejs如何调试代码
    全局安装 Vue cli3 和 继续使用 Vue-cli2.x
    导入sass文件
  • 原文地址:https://www.cnblogs.com/kongbb/p/10825639.html
Copyright © 2011-2022 走看看