题意:以数字中某一位为对称中心,两边的每位分别乘以中心距,两边的和相等就称为Balanced Number。
分析:想了好久,看一下题解恍然大悟,水题。。。
枚举中心,对于一个中心位进行dp,用模板dfs出口时判断val = 0就行了。
注意前导0,我多开了一维记录前导状态,开三维(中心位:pos位:val位)当然也是可行的,最后要减掉,因为枚举的每一个中心位状态0都满足。
#pragma GCC optimize ("O3")
#pragma GCC optimize ("O2")
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
#define met(s) memset(s, 0, sizeof(s))
#define rep(i, a, b) for(int i = a; i <= b; ++i)
template <class T> inline void scan_d(T &ret) {
char c; ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9') {
ret = ret * 10 + (c - '0'), c = getchar();}}
typedef long long LL;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int MAXN = 1e4 + 10;
int a[20]; LL dp[20][20][4000][2];
inline LL dfs(int pos, int val, int x, int lead, int limit) {
if(pos < 0 || val < 0) return val == 0 && !lead;
if(!limit && dp[x][pos][val][lead] >= 0) return dp[x][pos][val][lead];
int up = limit ? a[pos] : 9;
LL ans = 0;
for(int i = 0; i <= up; ++i) {
int res = val + i * (pos - x);
ans += dfs(pos - 1, res, x, lead && !i, limit && i == up) * 1LL;
}
if(!limit) dp[x][pos][val][lead] = ans;
return ans;
}
inline LL so(LL x) {
if(x < 0) return 0;
int p = 0;
while(x) {
a[p++] = x % 10;
x /= 10;
}
LL ans = 0;
for(int i = 0; i < p; ++i) ans += dfs(p - 1, 0, i, 1, 1);
return ans + 1;
}
int main() {
int T; memset(dp, -1, sizeof(dp));
scanf("%d", &T);
while(T--) {
LL a, b;
scanf("%lld %lld", &a, &b);
printf("%lld\n", so(b) - so(a - 1));
}
return 0;
}