Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 7816 Accepted Submission(s): 3722
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 | We have carefully selected several similar problems for you: 3711 3715 3718 3713 3712
大意:平衡数有平衡点,使平衡点两边的权值(数值)×权重(到平衡点的距离)和相等
对于任意一个平衡数,它的平衡点唯一!!!!!!
枚举平衡点统计平衡数的个数
注意0的情况,0有一个平衡点,但是00有两个平衡点,000有三个平衡点(我们算的时候把00000000这种情况也算进去了,所以最后加剪掉len,再加上0这一个)
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL f[20][20][4000];
LL dig[20];
LL dfs(int pos,int o,int pre,int limit){
LL res=0;
if (pos==0)
return pre==0;
if (!limit&&f[pos][o][pre]!=-1)
return f[pos][o][pre];
int last=limit?dig[pos]:9;
for (int i=0;i<=last;i++){
res+=dfs(pos-1,o,pre+i*(pos-o),limit&&(i==last));
}
if (!limit) f[pos][o][pre]=res;
return res;
}
LL solve(LL n){
if (n<0)
return 0;
if (n==0)
return 1;
int len=0;
while (n){
dig[++len]=n%10;
n/=10;
}
LL ans=0;
for (int i=1;i<=len;i++){
ans+=dfs(len,i,0,1);
}
ans=ans-len+1;
return ans;
}
int main()
{
LL t,x,y;
scanf("%lld",&t);
memset(f,-1,sizeof(f));
while(t--){
scanf("%lld%lld",&x,&y);
LL xpp;
xpp=solve(y)-solve(x-1);
cout<<xpp<<endl;
}
}