天天看點

hdu3709: Balanced Number

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

2
0 9
7604 24324
        

Sample Output

10

   
897

   



   
數位DP。枚舉力臂f[i][j][k]表示i位,力距*力臂的值,力臂為k時候的ans

   
注意f初始值為-1.因為有的狀态f為0,若初值設為0則會TLE

   


          
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
long long f[21][10001][21];
int a[21];
inline long long dfs(int len,int d,int x,bool lim)
{
	if(len==0&&d==0)
		return 1;
	else if(len==0)
		return 0;
	if(!lim&&f[len][d][x]!=-1)
		return f[len][d][x];
	int i;
	int limit;
	if(lim)
		limit=a[len];
	else
		limit=9;
	long long ans=0;
	for(i=0;i<=limit;i++)
	{
		int dx=d+(len-x)*(long long)i;
		ans+=dfs(len-1,dx,x,lim&&i==a[len]);
	}
	if(!lim)
		f[len][d][x]=ans;
	return ans;
}
inline long long cale(long long x)
{
	int len=0;
	while(x!=0)
	{
		len++;
		a[len]=x%(long long)10;
		x=x/(long long)10;
	}
	int i;
	long long ans=0;
	for(i=1;i<=len;i++)
		ans+=dfs(len,0,i,true);
	return ans-(long long)len;
}
int main()
{
	int T;
	scanf("%d",&T);
	memset(f,-1,sizeof(f));
	while(T>0)
	{
		T--;
		long long l,r;
		scanf("%lld%lld",&l,&r);
		printf("%lld\n",cale(r)-cale(l-1));
	}
	return 0;
}