题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3709
数位DP专题:http://blog.csdn.net/chy20142109/article/details/50930004
题意:求区间范围内的平衡数。所谓平衡数就是找一个数位作为中心,其他位产生的值为到中心的距离*该位的数值,如果中心左边的值等于右边的值,就叫
做平衡数。比如4139,3作为中心,左边 = 4 * 2 + 1 * 1 = 右边 = 9 * 1.
思路: 枚举固定每一位作为中心位进行统计。如果第k位作为中心位,那么可以通过判断∑digit[i]*( i - k )(i = m to 1)这个值最后是否为0从而确定
是否为平衡数。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
int T;
LL a,b;
LL dp[20][20][3600];
int digit[20];
LL dfs(int pos,int num,int k,bool flag)
{
if( k==0 ) return num == 0;
if ( num < 0 ) return 0;
if ( !flag && dp[k][pos][num]!=-1 ) return dp[k][pos][num];
int ed = flag?digit[k]:9;
LL ans = 0;
rep(i,0,ed)
{
ans+=dfs(pos,num+i*(k - pos),k-1,flag && (i == ed));
}
if(!flag) dp[k][pos][num] = ans;
return ans;
}
LL cal(LL x)
{
int len = 0;
while(x)
{
digit[++len] = x % 10;
x/=10;
}
LL ans = 0;
rep(i,1,len) ans+=dfs(i,0,len,1);
ans-=len-1;
return ans;
}
int main()
{
Clean(dp,-1);
cin>>T;
while(T--)
{
scanf("%I64d %I64d",&a,&b);
printf("%I64d\n",cal(b) - cal(a-1));
}
return 0;
}