• HDU3709 Balanced Number (数位dp)


     Balanced Number
    Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

    Description

    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 [ xy].

     

    Input

    The 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 ≤ 1018).

    Output

    For each case, print the number of balanced numbers in the range [xy] in a line.

    Sample Input

    2
    0 9
    7604 24324
    

    Sample Output

    10
    897

    数位dp

    表示暂时还不明白为什么这样搜索不会超时。。

    #include<cstdio>
    #include<cstring>
    long long f[20][20][2000];
    int a[20];
    long long dfs(int pos,int z,int l,bool pd){
        if(pos<=0) return l==0;
        if(l<0) return 0;
        if(!pd&&f[pos][z][l]!=-1) return f[pos][z][l];
        int i,j,k,en;
        en=pd?a[pos]:9;
        long long ans=0;
        for(i=0;i<=en;i++)
            ans+=dfs(pos-1,z,l+(pos-z)*i,pd&&i==en);
        if(!pd) f[pos][z][l]=ans;
        return ans;
    }
    long long sum(long long x){
        int i,n=0;
        while(x){
            a[++n]=x%10;
            x=x/10;
        }
        long long ans=0;
        for(i=n;i>0;i--)
            ans+=dfs(n,i,0,1);
        return ans-n+1;
    }
    int main()
    {
        int tt;
        long long x,y;
        scanf("%d",&tt);
        while(tt--){
            scanf("%lld%lld",&x,&y);
            memset(f,-1,sizeof(f));
            printf("%lld
    ",sum(y)-sum(x-1));
        }
        return 0;
    }
  • 相关阅读:
    C# 语言基础(++和--运算)
    Android RSA加密解密
    laravel redis
    larave5.1l队列
    shell更改目录编码
    Linux的权限说明
    MySQL主从架构之Master-Master互为主备
    php curl流方式远程下载大文件
    php session 跨页失效问题
    mysql中文字段转拼音首字母,以及中文拼音模糊查询
  • 原文地址:https://www.cnblogs.com/Mathics/p/3868422.html
Copyright © 2020-2023  润新知