Problem 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 ≤ 1018).
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
Author
GAO, Yuan
Source
2010 Asia Chengdu Regional Contest
Recommend
zhengfeng | We have carefully selected several similar problems for you: 3711 3715 3718 3713 3712
dp[i][j][k]表示i位数,轴在j上,和为k的数的个数,然后枚举j,数位dp,注意0每一次都会被算到,最后要减去(len - 1)
/************************************************************************* > File Name: hdu3709.cpp > Author: ALex > Mail: [email protected] > Created Time: 2015年03月01日 星期日 18时42分38秒 ************************************************************************/
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const double eps = 1e-15;
typedef long long LL;
typedef pair <int, int> PLL;
LL dp[40][40][4000];
int bit[40];
LL dfs (int cur, int pro, int sum, bool flag, bool zero)
{
if (cur == -1)
{
if (zero)
{
return 1;
}
return sum == 0;
}
if (!flag && ~dp[cur][pro][2000 - sum])
{
return dp[cur][pro][2000 - sum];
}
LL ans = 0;
int end = flag ? bit[cur] : 9;
for (int i = 0; i <= end; ++i)
{
if (zero && !i)
{
ans += dfs (cur - 1, pro, 0, flag && (i == end), 1);
}
else if (zero && i)
{
ans += dfs (cur - 1, pro, i * (cur - pro), flag && (i == end), 0);
}
else
{
ans += dfs (cur - 1, pro, sum + i * (cur - pro), flag && (i == end), 0);
}
}
if (!flag)
{
dp[cur][pro][2000 - sum] = ans;
}
return ans;
}
LL calc (LL n)
{
int cnt = 0;
while (n)
{
bit[cnt++] = n % 10;
n /= 10;
}
LL ans = 0;
for (int i = 0; i < cnt; ++i)
{
ans += dfs (cnt - 1, i, 0, 1, 1);
}
ans -= (cnt - 1);
return ans;
}
int main ()
{
memset (dp, -1, sizeof(dp));
int t;
scanf("%d", &t);
while (t--)
{
LL l, r;
scanf("%I64d%I64d", &l, &r);
printf("%I64d\n", calc (r) - calc (l - 1));
}
return 0;
}