首页 > 代码库 > HDU 3709 Balanced Number
HDU 3709 Balanced Number
Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 2161 Accepted Submission(s): 960
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].
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 | We have carefully selected several similar problems for you: 3711 3715 3718 3713 3712
数位DP,可以参考本博客另外两篇博文:
HDU 2089 不要62
HDU 3652 B-number
#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> #include<math.h> #include<stack> #include<queue> #include<set> #include<map> #include<vector> using namespace std; typedef long long LL; //dp[i][j][k],i表示位数,j表示去掉的点的位置,k表示两遍数的计算结果的差 LL dp[20][20][2500]; int num[50]; LL dfs(int pos,int center,int cha,bool limit) { if(pos==0) return cha==0;//结果差为0则返回1 if(cha<0) return 0; if(!limit && dp[pos][center][cha]!=-1) return dp[pos][center][cha]; int end = limit?num[pos]:9; LL ans = 0; for(int i = 0;i <= end;i++) { ans+=dfs(pos-1,center,cha+i*(pos-center),limit&&(i==end)); } if(!limit) dp[pos][center][cha] = ans; return ans; } LL work(LL n) { int len = 0; while(n) { num[++len] = n%10; n/=10; } LL ans = 0; for(int i = 1;i <= len;i++) { ans+=dfs(len,i,0,true); } return ans-len+1; } int main() { int T; scanf("%d",&T); LL a,b; while(T--) { memset(dp,-1,sizeof(dp)); scanf("%I64d %I64d",&a,&b); printf("%I64d\n",work(b)-work(a-1)); } return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。