hdu 3709 Balanced Number
Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 1351 Accepted Submission(s): 589
Problem 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 [x, 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 ≤ 1018).
Output
For 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
Author
GAO, Yuan
Source
2010 Asia Chengdu Regional Contest
Recommend
zhengfeng
//和hdu 3652解法相似
1 //31MS 6536K 1008 B C++ 2 /* 3 4 记忆化搜索解决数位DP,和 hdu 3652 相似: 5 dp[i][j][k] i表示第i位 6 j表示第j位为支点 7 k表示高位到低位的力矩和(以j为支点) 8 9 */ 10 #include<stdio.h> 11 #include<string.h> 12 __int64 dp[20][20][2000]; 13 int digit[20]; 14 __int64 dfs(int pos,int central,int pre,bool judge) 15 { 16 if(pos<=0) return pre==0; 17 if(pre<0) return 0; //为负时跳出 18 if(!judge && dp[pos][central][pre]!=-1) 19 return dp[pos][central][pre]; 20 __int64 ans=0; 21 int end=judge?digit[pos]:9; 22 for(int i=0;i<=end;i++){ 23 int tpre=pre+i*(pos-central); 24 ans+=dfs(pos-1,central,tpre,judge&&i==end); 25 } 26 if(!judge) dp[pos][central][pre]=ans; 27 return ans; 28 } 29 __int64 deal(__int64 n) 30 { 31 memset(digit,0,sizeof(digit)); 32 int len=0; 33 while(n){ 34 digit[++len]=n%10; 35 n/=10; 36 } 37 __int64 ans=0; 38 for(int i=1;i<=len;i++) 39 ans+=dfs(len,i,0,true); 40 return ans-len+1; //排除全为0的重复情况 41 } 42 int main(void) 43 { 44 int t; 45 __int64 a,b; 46 scanf("%d",&t); 47 memset(dp,-1,sizeof(dp)); 48 while(t--){ 49 scanf("%I64d%I64d",&a,&b); 50 printf("%I64d\n",deal(b)-deal(a-1)); 51 } 52 return 0; 53 } 54