Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 2945 Accepted Submission(s): 1348
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
Recommend
枚举中心点,然后按位枚举,长度由len到0,算出当前权值之和pre,然后结束时判断pre值是否为0,为0,返回1,否则返回1。
用dp[len][cen][pre]保存长度为i,中心点为k,之前的权值之和为pre的数字有多少种的状态。
最后需要去除全是0的情况,因为全是0的话,中心点可随意枚举没,所以需要减去(len-1)。
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> using namespace std; #define LL long long #define maxn 30 LL dp[maxn][maxn][2500]; // dp[i][k][j]代表长度为i,中心点为k,最高位到与最高位距离为i的位置经过的数字的权值之和j的数字有多少种 LL digit[maxn]; __int64 dfs(int len,int cen,int pre,bool fp) //dfs版本的纯属暴力枚举每一个数字,而递推版本的是考虑了前缀的影响 { if(len==0) return pre==0; if(pre<0) return 0; if(!fp && dp[len][cen][pre] != -1) // { return dp[len][cen][pre]; } LL ret =0; int fpmax = fp ? digit[len] : 9; for(int i=0;i<=fpmax;i++) //分别算出以i开头的数的方案数, { LL temp=dfs(len-1,cen,pre+i*(len-cen),fp && i == fpmax); ret+=temp; } if(!fp) dp[len][cen][pre]= ret; return ret; } LL f(LL n) { if(n==-1) return 0; int len=0; while(n) { digit[++len] = n % 10; n /= 10; } LL ans=0; for(int cen=1;cen<=len;cen++) { ans+=dfs(len,cen,0,true); } return ans-len+1; } void init() { memset(dp,-1,sizeof(dp)); } int main() { // freopen("test.txt","r",stdin); int t; scanf("%d",&t); while(t--) { init(); LL n,m; scanf("%I64d%I64d",&n,&m); LL ans1=f(m); // init(); LL ans2=f(n-1); printf("%I64d ",ans1-ans2); } return 0; }