题意:在给定范围内有多少个数是“平衡数”。平衡数:存在一个“平衡点”,满足每一位到该位的距离(有正负)乘以每位的数字之和等于零。
给以看出一个“平衡数”的“平衡点”,一定是唯一的(00000除外)。我们可以枚举每一个平衡点做数位dp。每一位的pre状态即前面所有位的“距离和”,转移的时候新的pre状态为pre + (pos - o) * i,o为平衡点。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define lng long long
using namespace std;
const int maxn = 10000 + 10;
int num[30];
lng dp[20][3000], a, b;
lng dfs(int pos, int pre, int ok, int o)
{
if(pos == -1) return pre == 0;
if(!ok && dp[pos][pre] != -1) return dp[pos][pre];
lng ans = 0;
int end = ok ? num[pos] : 9;
for(int i = 0; i <= end; ++i)
{
int tpre = pre + (pos - o) * i;
if(tpre >= 0) ans += dfs(pos - 1, tpre, (ok && i == end), o);
}
if(!ok) dp[pos][pre] = ans;
return ans;
}
void prework()
{
cin >> a >> b;
}
lng calc(lng n)
{
int tot = 0;
while(n)
{
num[tot++] = n % 10;
n /= 10;
}
lng ans = 0;
for(int i = 0; i < tot; ++i)
{
memset(dp, 0xff, sizeof(dp));
ans += dfs(tot - 1, 0, 1, i);
}
ans -= (tot - 1);
return ans;
}
void solve()
{
cout << calc(b) - calc(a - 1) << "\n";
}
int main()
{
int t; cin >> t;
while(t--)
{
prework();
solve();
}
return 0;
}