Description
A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9, for left part and right part, respectively. It’s your job
to calculate the number of balanced numbers in a given range [x, y].
Input
The input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 10^18).
Output
For each case, print the number of balanced numbers in the range [x, y] in a line.
Sample Input
2
0 9
7604 24324
Sample Output
10
897
Solution
如果我们能够求出
0...l−1
的BN个数和
0...r
的BN个数,做差即可得到答案,现在问题就转化为求
0...x
的BN个数,这个问题可以用数位dp解决。
f[pivot][pos][sum][free]
记录一种方案,其中
pivot
表示当前平衡点位置,
pos
表示当前讨论的位置(
最高位...pos+1
已经确定,
pos...最低位
还未确定),
sum
表示杠杆权值和(以
pivot
更高位为正,
pivot
更低位为负),
free
记录是否严格小于x(为
0
时表示构造出的数在
Code & Note
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 20;
const int maxs = 1500;
int n, a[maxn];
ll f[maxn][maxn][maxs][2];
ll dp(int pivot, int pos, int sum, bool free){
if(sum < 0) return 0; // 如果当前 sum < 0,那么当前状态肯定不是一个合法的状态,并且之后也不会变为合法状态
if(pos < 0) return sum == 0; // 确定完 最高位...最低位 后,如果当前状态合法(sum == 0),则对应一种合法方案
if(f[pivot][pos][sum][free] != -1) return f[pivot][pos][sum][free]; // 类似于记忆化搜索
ll rtn = 0;
// 在当前位置枚举填数
if(free){
for(int k = 0; k <= 9; ++k){
int kk = k * (pos - pivot);
rtn += dp(pivot, pos - 1, sum + kk, true);
}
} else{
for(int k = 0; k <= a[pos]; ++k){
int kk = k * (pos - pivot);
rtn += dp(pivot, pos - 1, sum + kk, k < a[pos]);
}
}
f[pivot][pos][sum][free] = rtn;
return rtn;
}
ll calc(){
ll rtn = 0;
memset(f, -1, sizeof f);
for(int p = 0; p < n; ++p) rtn += dp(p, n - 1, 0, false); // 枚举每一个 pivot 所在位置
return rtn - n; // 相当于 rtn - len + 1, 0会被计算len次
}
int main(){
int t; ll x;
scanf("%d", &t);
while(t--){
ll l, r, lsum = 0, rsum = 0;
scanf("%lld%lld", &l, &r); --l;
// n为 位数 - 1
x = l; for(n = 0; x; ++n, x /= 10) a[n] = x % 10;
if(l < 10) lsum = l; else lsum = calc();
x = r; for(n = 0; x; ++n, x /= 10) a[n] = x % 10;
if(r < 10) rsum = r; else rsum = calc();
printf("%lld\n", rsum - lsum);
}
return 0;
}