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
思路:需要枚举数的每一位,看是否构成平衡数,最后还需要进去去重,因为00,000,,,,这些和0是等价的
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <math.h>
#include <stack>
typedef long long ll;
#define INF 0x3f3f3f3f
const int maxn=3e5+10;
const int MAXN=1e3+10;
using namespace std;
int a[30];
ll dp[30][30][2500];
ll dfs(int pos,int num,int sta,bool limit)
{
if(pos==-1)
{
return sta==0;
}
if(sta<0)
{
return 0;
}
if(limit==0&&dp[pos][num][sta]!=-1)
{
return dp[pos][num][sta];
}
int up=limit?a[pos]:9;
ll ans=0;
for(int i=0;i<=up;i++)
{
ans+=dfs(pos-1,num,sta+(pos-num)*i,limit&&i==up);
}
if(limit==0)
{
dp[pos][num][sta]=ans;
}
return ans;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
ll ans=0;
for(int i=0;i<=pos-1;i++)
{
ans+=dfs(pos-1,i,0,1);
}
return ans-pos+1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int T;
cin>>T;
memset(dp,-1,sizeof(dp));
while(T--)
{
ll l,r;
cin>>l>>r;
cout<<solve(r)-solve(l-1)<<endl;
}
return 0;
}