题意:一个数字是Balanced number当且仅当存在一个位置loc,使得一个数字的pos位置上的数字dig_pos*(pos-loc)的和是0。
询问区间内有多少这样的数字。
采用数位DP的方法,对于每一个位置,保存状态dp[pos][loc][sum]表示当前位pos位,中心位置为loc,前面的累加和为sum的状态的答案。
执行call()函数的时候,对于一个区间,loc从1到len遍历一次,由于除0以外,所有的数字最多有1个位置loc使得sum==0,0的话存在len个位置。所以要在结果中减去len-1。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL dp[20][20][1800];
int dig[20];
LL dfs(int pos, int loc, int sum, int limit)
{
if(!pos)
return sum == 0 ? 1 : 0;
if(sum < 0)
return 0;
if(!limit && dp[pos][loc][sum] != -1)
return dp[pos][loc][sum];
int n = limit?dig[pos]:9;
LL res = 0;
for(int i = 0; i <= n; ++i)
{
res += dfs(pos-1, loc, sum+i*(pos-loc), limit && i==n);
}
if(!limit) dp[pos][loc][sum] = res;
return res;
}
LL call(LL x)
{
if(x == -1) return 0;
int len = 0;
while(x)
{
dig[++len] = x%10;
x /= 10;
}
LL res = 0;
for(int i = len; i >= 1; --i)
res += dfs(len, i, 0, 1);
return res - len + 1;//important!
}
int main()
{
ios::sync_with_stdio(false);
memset(dp, -1, sizeof(dp));
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif // ONLION_JUDGE
int T;
cin >> T;
while(T--)
{
LL a, b;
cin >> a >> b;
cout << call(b) - call(a-1) << endl;
}
return 0;
}