当前位置:网站首页>HDU 3709 Balanced Number

HDU 3709 Balanced Number

2022-06-26 13:12:00 YJEthan

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

a number , Choose a digit as the fulcrum , If the sum of the numbers on both sides multiplied by the distance from the fulcrum is equal, it is the equilibrium number , Such as abcd if a*1=c*1+d*2 Is a balanced tree , You can choose any fulcrum , if 0=b*1+c*2+d*3, It is also an equilibrium number

You can work it out first y And then subtract x-1 Equilibrium number in  

First enumerate the fulcrum , Then enumerate the digits

digit dp

#include<bits\stdc++.h>
using namespace std;

typedef long long ll;
ll dp[20][20][2005];
ll a[20];
ll dfs(ll pos,ll o,ll s,ll lim)// The current number of digits , Current fulcrum , The left side of the current position is heavier than the right side s, Whether the current bit has reached the maximum value 
{
    if(pos==-1)
        return s==0;
    if(s<0) return 0;// If the weight of the left side is less than that of the right side , Then skip directly , Because it is calculated from left to right 
    if(!lim&&dp[pos][o][s]!=-1)
        return dp[pos][o][s];
    ll ans=0;
    int up=lim?a[pos]:9;
    for(ll i=0;i<=up;i++)
    {
        ans+=dfs(pos-1,o,s+(pos-o)*i,lim&&i==up);
    }
    if(!lim) dp[pos][o][s]=ans;
    return ans;
}
ll solve(ll n)
{
    int i=0;
    while(n)
    {
        a[i++]=n%10;
        n/=10;
    }
    ll ans=0;
    for(int j=0;j<i;j++)// Enumerate every fulcrum 
        ans+=dfs(i-1,j,0,1);
    return ans-(i-1);
}
int main()
{
    int t;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));
    while(t--)
    {
        ll n,m;
        scanf("%I64d%I64d",&n,&m);
        printf("%I64d\n",solve(m)-solve(n-1));
    }
}



原网站

版权声明
本文为[YJEthan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261223286048.html