Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 1270 Accepted Submission(s): 553
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 ≤ 10
18).
Output
For each case, print the number of balanced numbers in the range [x, y] in a line.
Sample Input
Sample Output
Author
GAO, Yuan
Source
2010 Asia Chengdu Regional Contest
Recommend
zhengfeng
思路:数位DP的模式,只是要注意全是0 的情况得减去。
#include<cstdio>
#include<cstring>
#include<iostream>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
#define clr(f,z) memset(f,z,sizeof(f))
#define LL __int64
#define ll(x) (1<<x)
using namespace std;
LL dp[40][33][2000];//位数,1,0
int bit[40],pos;
LL L,R;int K;
LL DP(int pp,int ba,int dis,bool big)//位置,平衡点,距离量,
{
if(pp==0)return dis==0;
if(big&&dp[pp][ba][dis]!=-1)return dp[pp][ba][dis];
if(dis<0)return 0;
LL ret=0;
int kn=big?9:bit[pp];
FOR(i,0,kn)
{
ret+=DP(pp-1,ba,dis+i*(pp-ba),big||kn!=i);
}
if(big)dp[pp][ba][dis]=ret;
return ret;
}
LL get(LL x)
{ pos=0;
while(x)
{
bit[++pos]=x%10;
x/=10;
}
LL ret=0;
FOR(i,1,pos)
ret+=DP(pos,i,0,0);
return ret-pos+1;//全0 5-999 有0 00 000 只能算一种
}
int main()
{ int cas;
while(~scanf("%d",&cas))
{
FOR(ca,1,cas)
{clr(dp,-1);
// cin>>L>>R>>K;
scanf("%I64d%I64d",&L,&R);
printf("%I64d\n",get(R)-get(L-1));
//cout<<get(R)-get(L-1)<<endl;
}
}
}