• 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


  • 相关阅读:
    dd if=/dev/zero of=/dev/null 使用
    Linux 下的dd命令使用详解以及dd if=/dev/zero of=的含义
    windows 以及 linux 查看时间
    Linux下vi命令大全(文件修改)
    python test online
    python ssh登录下载上传脚本
    python telnet 中的数据判断(或者执行cmd后返回的数据 OperatingSystem.Run)
    python 转化串口中的数据 ,并分组判断
    python cmd下关闭exe程序(关闭浏览器驱动)
    robot 网卡连接情况
  • 原文地址:https://www.cnblogs.com/kongbb/p/10825639.html
Copyright © 2020-2023  润新知