HDU - 3709

Balanced Number


Time Limit:                                                        5000MS                       

 

Memory Limit: 65535KB

 

64bit IO Format:                            %I64d & %I64u                       


SubmitStatus


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



               


Hint



Source


2010 Asia Chengdu Regional Contest


//题意:平衡数定义:给你一个数如果以它的某一位为分割线,将这个数分为两部分,如果左右两部分的力矩(力矩:w*l,某位置上的数*这个数到轴的距离)相等,那么这个数即为平衡数。


输入两个数n,m,表示一个区间[n,m],让求在这个区间内有多少个平衡数?


//思路:


数位DP,对于给定的数,计算所有比它小的且为平衡数的个数;


具体看代码:


#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define ll long long
#define N 19
#define M 1378
using namespace std;
ll dp[N][N][M];
int digit[N];
ll dfs(int pos,int o,int sum,int f)
{
	if(sum<0) return 0;
	if(pos==-1)	return sum==0;
	if(!f&&dp[pos][o][sum]!=-1) return dp[pos][o][sum];
	ll ans=0;
	int max=f?digit[pos]:9;
	for(int i=0;i<=max;i++)
	{
		ans+=dfs(pos-1,o,sum+(pos-o)*i,f&&i==max);
	}
	if(!f) dp[pos][o][sum]=ans;
	return ans;
}
ll solve(ll x)
{
	int len=0;
	while(x)
	{
		digit[len++]=x%10;
		x/=10;
	}
	ll ans=0;
	for(int o=0;o<len;o++)
		ans+=dfs(len-1,o,0,1);
	return ans-len+1;
}
int main()
{
	int t;
	memset(dp,-1,sizeof(dp));
	scanf("%d",&t);
	while(t--)
	{
		ll n,m;
		scanf("%lld%lld",&n,&m);
		printf("%lld\n",solve(m)-solve(n-1));
	}
	return 0;
}