HDU 3709 Balanced Number (数位DP)

Posted AC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 3709 Balanced Number (数位DP)相关的知识,希望对你有一定的参考价值。

Balanced Number

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 3798    Accepted Submission(s): 1772


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

 


题意:找出区间内平衡数的个数,所谓的平衡数,就是以这个数字的某一位为支点,另外两边的数字大小乘以力矩之和相等,即为平衡数

思路:首先这是一个数位DP题,解此题用枚举的算法,枚举出所有可能的状况进行dfs,最后相加,就是结果了。

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

int bit[19];
__int64 dp[19][19][2005];

__int64 dfs(int pos,int o,int l,int limit)
{
    //根据题意,要改符合答案的条件,所以当l==0时返回1
    if (pos==-1)
        return l==0;
    //注意这里,l<0一定要写,因为有一种情况是在pivot的左边<0之后又在左边==0了,这种情况是不符合的,所以这一步不能少
    if (l<0)
        return 0;
    __int64 &aa=dp[pos][o][l];
    if (!limit&&aa!=-1)
        return aa;
    __int64 ans=0;
    int end=limit?bit[pos]:9;
    for (int i=0;i<=end;i++)
    {
        int next=l;
        next+=(pos-o)*i;
        ans+=dfs(pos-1,o,next,limit&&i==end);
    }
    if (!limit)
        aa=ans;
    return ans;
}

__int64 sol(__int64 n)
{
    int len=0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    __int64 ans=0;
    for (int i=0;i<len;i++)
    {
        ans+=dfs(len-1,i,0,1);
    }
    return ans-(len-1);
}

int main()
{
    int o;
    cin>>o;
    while(o--)
    {
        memset(dp,-1,sizeof(dp));
        __int64 x,y;
        cin>>x>>y;
        cout<<sol(y)-sol(x-1)<<endl;
    }
    return 0;
}

 

以上是关于HDU 3709 Balanced Number (数位DP)的主要内容,如果未能解决你的问题,请参考以下文章

hdu3709 Balanced Number

HDU3709平衡数Balanced Number

HDU 3709 Balanced Number (数位DP)

HDU 3709 Balanced Number

hdu3709 Balanced Number

HDU 3709: Balanced Number