HDU-3709:Balanced Number(数位DP)

Balanced Number
Time Limit: 10000/5000 MS (Java/Others)
Memory Limit: 65535/65535K(Java/Others)

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 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

思路:数位DP。d[i][j][h][sum]表示第i位的数为j,支点在h位,现在的力矩和为sum的数的个数。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll d[20][10][20][2005];
ll p[20];
int cal(int L,int m,int R)
{
    int Ls=0;
    for(int i=L;i>=R;i--)Ls+=p[i]*(m-i);
    return Ls;
}
int check(int n)
{
    for(int i=n;i>=0;i--)if(cal(n,i,0)==0)return 1;
    return 0;
}
ll cal(ll x)
{
    if(x<=9)return x+1;
    int n=0;
    while(x)p[n++]=x%10,x/=10;n--;
    ll ans=1;
    for(int i=0;i<n;i++)//统计位数不足n的平衡树的个数
    for(int j=1;j<=9;j++)
    for(int h=0;h<=i;h++)ans+=d[i][j][h][0];
    for(int i=n;i>=0;i--)//计算位数等于n的平衡数的个数
    {
        if(i==n)
        {
            for(int j=1;j<p[i];j++)
            for(int h=i;h>=0;h--)ans+=d[i][j][h][0];
        }
        else
        {
            for(int j=0;j<p[i];j++)
            for(int h=n;h>=0;h--)
            {
                int sum=cal(n,h,i+1);
                if(sum<=0)ans+=d[i][j][h][abs(sum)];
            }
        }
    }
    return ans+check(n);//最后check一下x本身是否是平衡数
}
int main()
{
    for(int i=0;i<=18;i++)//预处理
    {
        if(i==0)
        {
            for(int j=0;j<=9;j++)
            for(int k=i;k<=18;k++)d[i][j][k][(k-i)*j]++;
            continue;
        }
        for(int j=0;j<=9;j++)
        for(int k=0;k<=9;k++)
        for(int h=0;h<=18;h++)
        for(int sum=max(0,-(h-i)*j);sum+(h-i)*j<=2000;sum++)
        d[i][j][h][sum+(h-i)*j]+=d[i-1][k][h][sum];
    }
    int T;
    cin>>T;
    while(T--)
    {
        ll L,R;
        scanf("%lld%lld",&L,&R);
        printf("%lld\n",cal(R)-cal(L-1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/81383170