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 42 + 11 = 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
题意:求给出区间 [l,r] 内平衡数的个数:平衡数:以某位数字作为中心轴,此位左边的 数字X距离的和与右边的数字X距离的和相等的数的个数。
思路:我们枚举每一位数作为中心轴,然后dfs搜索其余位上的数字,记录一个sum,sum表示左边的数字X距离的和与右边的数字X距离的和的差值,即题目要求sum=0的数的个数,值得注意的一点是,我们是从高位向低位搜索,因此sum是先变大后变小,当sum<0时,不可能再重新回到0,因此我们可以剪枝,sum小于0时直接return。我们用一个三维数组dp[pos][st][sum],表示pos位数以st为轴时左边的数字X距离的和与右边的数字X距离的和的差值为sum的数的个数。
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll dp[20][20][1600],dit[20];
ll dfs(int pos,int st,int sum,int limit)
{
if(pos<0) return sum==0;
if(sum<0) return 0;
if(!limit&&dp[pos][st][sum]!=-1) return dp[pos][st][sum];
int up=limit?dit[pos]:9;
ll ans=0;
for(int i=0;i<=up;i++)
{
ans+=dfs(pos-1,st,sum+(pos-st)*i,limit&&i==dit[pos]);
}
if(!limit) dp[pos][st][sum]=ans;
return ans;
}
ll solve(ll x)
{
int len=0;
ll ans=0;
while(x)
{
dit[len++]=x%10;
x/=10;
}
for(int i=0;i<len;i++)
ans+=dfs(len-1,i,0,1);
return ans-(len-1);//00,000,0000....为重复的,因此需要减去
int main()
{
int t;
ll n,m;
cin>>t;
memset(dp,-1,sizeof(dp));
while(t--)
{
cin>>n>>m;
cout<<solve(m)-solve(n-1)<<endl;
}
return 0;
}