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,yx,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,yx,y in a line.
Sample Input
2
0 9
7604 24324
Sample Output
10
897
大致题意:当一个数存在一个平衡点,使得平衡点左侧的力矩和等于右侧的力矩和时,这个数是平衡数,
问你区间[x,y]中平衡数的个数。
思路:加一维表示力矩和,枚举支点。
代码如下
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<cstring>
#include<cmath>
#define LL long long
#define ULL unsigned long long
using namespace std;
LL dp[20][20][2000];//dp[l][dian][he] 第i位, 支点 dian 力矩和 he
int digit[20];
LL dfs(int l, int dian,int he,int jud) {
if ( l==-1) return he==0;
if(he<0) return 0;//因为力矩和是先增大后减少的,如果此时已经小于0则说明这种情况不行,剪枝
if ( !jud && dp[l][dian][he]!=-1) return dp[l][dian][he];
LL ans = 0;
int nex = jud ? digit[l] : 9;
for (int i = 0; i <= nex; i++)
{
ans += dfs( l-1 ,dian, he+i*(l-dian),jud && i==nex );
}
if(!jud)
{
dp[l][dian][he]=ans;
}
return ans;
}
LL f(LL num){
memset(dp,-1,sizeof(dp));
int tol = 0;
while(num){
digit[tol++]=num%10;
num/=10;
}
LL sum=0;
for(int i=0;i<tol;i++)//枚举支点为i
{
sum+=dfs(tol-1,i,0,1);
}
return sum-tol+1;//减去全为0的情况
}
int main()
{
int T;
LL x,y;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&x,&y);
printf("%lld\n",f(y)-f(x-1));
}
return 0;
}