HDU 3709 Balanced Number(数位DP)

来源:互联网 发布:现货指标公式源码下载 编辑:程序博客网 时间:2024/05/19 20:38

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,yx,y.
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 ≤ 10 18).
Output
For each case, print the number of balanced numbers in the range x,yx,y in a line.
Sample Input
20 97604 24324
Sample Output
10897

Hint


给定区间[a,b],求区间内平衡数的个数。所谓平衡数即有一位做平衡点,左右两边数字的力矩想等。


遍历每一位做为平衡点,进行搜索,sum保存数字乘以距离的和,若sum为0,则说明平衡。 
要注意因为遍历了len次,所以0多加了len-1次。 
还有个小技巧是当sum<0时就可以直接return了,可以加速。因为,len由大到小的过程中,sum是由大到小的变化,但绝不会小于0,否则就是不能平衡。


#include <bits/stdc++>using namespace std;long long dp[20][20][1540]; /// dp[i][j][k] i表示处理到的数位pos,j是支点,k是力矩和int bit[20];long long dfs(int pos,int pivot,int pre,bool flag){    if(pos==-1)return pre==0;  ///出口,也就是正好左右平衡时    if(pre<0)return 0;         ///当前力矩为负,剪枝    if(!flag&&dp[pos][pivot][pre]!=-1)        return dp[pos][pivot][pre];                    int end=flag?bit[pos]:9;    long long ans=0;    for(int i=0;i<=end;i++)        ans+=dfs(pos-1,pivot,pre+i*(pos-pivot),flag&&i==end);  ///i*(pos-pivot)写的很巧妙,支点左边加,右边减,支点不算                    if(!flag)  dp[pos][pivot][pre]=ans;    return ans;}long long calc(long long n){    int len=0;    while(n)    {        bit[len++]=n%10;        n/=10;    }    long long ans=0;    for(int i=0;i<len;i++)  ///遍历每一个中心点        ans+=dfs(len-1,i,0,1);    return ans-(len-1);///去掉全0的情况}int main(){//    freopen("in.txt","r",stdin);//    freopen("out.txt","w",stdout);    int T;    long long x,y;    memset(dp,-1,sizeof(dp));//这个初始化一定别忘记    scanf("%d",&T);    while(T--)    {        scanf("%I64d%I64d",&x,&y);        printf("%I64d\n",calc(y)-calc(x-1));    }    return 0;}




0 0
原创粉丝点击