Balanced Number
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
题意:对于A~B之间的一些数,在其中的n位中选一个位置作为中间,类似于天平,天平两边的数的权值等于数值*距离中间的曼哈顿距离,当两边的总权值相等时那么这个数就是个平衡数,具体方法代码里面解释的很清楚
代码:
/*遍历每一位做为平衡点,进行搜索,sum保存数字乘以距离的和,若sum为0,则说明平衡。
要注意因为遍历了len次,所以0多加了len-1次。
还有个小技巧是当sum<0时就可以直接return了,可以加速。因为,len由大到小的过程中,sum是由大到小的变化,但绝不会小于0,否则就是不能平衡。
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<cmath>
#include<stack>
#define LL long long
using namespace std;
int t;
LL x,y;
LL a[20],f[20][20][2005];
//多少位,第多少个为中间,和
LL dfs(int num,int mid,int limit,int sum)
{
int up;
LL ans=0;
if(num==0)return (sum==0);
if(sum<0)return 0;//因为前面的num是大于mid的,那么sum是先大于0的,然后再慢慢的减少的,所以到小于0的时候就已经你敢不行了
if(!limit&&f[num][mid][sum]!=-1)return f[num][mid][sum];
if(!limit)up=9;
else up=a[num];
for(int i=0;i<=up;i++)
{
ans+=dfs(num-1,mid,limit&&i==a[num],sum+(num-mid)*i);
}
if(!limit)f[num][mid][sum]=ans;
return ans;
}
LL slove(LL x)
{
int num=0;
LL sum=0;
if(x<0)return 0;
//不能等于0,因为数字为1的时候是可以的
while(x!=0)
{
a[++num]=x%10;
x/=10;
}
for(int i=1;i<=num;i++)
{
sum+=dfs(num,i,1,0);
//多少位,中间,限制,和
}
return sum-(num-1);
//当0在枚举中点时,不管中点选在哪儿都是满足的,所以重复了(num-1)个
}
int main()
{
scanf("%d",&t);
memset(f,-1,sizeof(f));
memset(a,0,sizeof(a));
while(t--)
{
scanf("%lld%lld",&x,&y);
printf("%lld\n",slove(y)-slove(x-1));
}
}