求[l,r]中的平衡数,平衡数就是找一个位,左右两边的各个位上的数字乘到平衡位的距离和相等。
需要枚举哪一位是平衡位。
最大的数可以达到10^18,1e18-1如选最高位作为平衡点的话一段是0,一端是9+9 * 2+9 * 3+…+9 * 16 = 8* 9*17 = 1224,求得了一端最大的和是1224,所以选取2000为起始点,就不用考虑负数时数组越界的问题了。
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
LL x,y,t,bits[40],d[40][40][4000];
LL dp(int pos,int mid,int t,int dif){
if(pos == 0) return t == 2000;
if(dif && d[pos][mid][t] != -1) return d[pos][mid][t];
LL x = dif ? 9 : bits[pos],ans = 0;
for(int i = 0 ;i<= x;i++)
ans += dp(pos-1,mid,t-i*(pos-mid),dif||i<x);
if(dif) d[pos][mid][t] = ans;
return ans;
}
LL cal(LL x){
if(x<0) return 0;
LL cnt = 0,res = 0;
while(x){
bits[++cnt] = x % 10;
x /= 10;
}
for(int i = 1;i<=cnt;i++)
res += dp(cnt,i,2000,0);
return res - cnt +1;
}
int main(){
scanf("%lld",&t);
while(t--){
scanf("%lld%lld",&x,&y);
memset(d,-1,sizeof(d));
printf("%lld\n",cal(y) - cal(x-1));
}
return 0;
}