Balanced Number (HDU-3709)数位DP

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

题意:一个数,当以其中一位为中心轴的时候,如果左面的数乘以左面的数离中心轴的距离=右面的数乘以右面的数离中心轴的距离时,我们便称这个数为平衡数。现在给定你一个区间[a,b],问你在这个区间里,有多少个平衡数。

思路:遍历每一位做为平衡点,进行搜索,sum保存数字乘以距离的和,若sum为0,则说明平衡。要注意因为遍历了pos次,所以0多加了pos-1次。还有个小技巧是当sum<0时就可以直接return了,可以加速。因为,pos由大到小的过程中,sum是由大到小的变化,但绝不会小于0,否则就是不能平衡。

AC代码:

#include <bits/stdc++.h>
typedef long long ll;
const int maxx=2010;
const int inf=0x3f3f3f3f;
using namespace std;
ll a[20];
ll dp[20][20][maxx];
ll dfs(int pos,int state,int sum,bool limit)
{
    if(pos==-1)
        return sum?0:1;
    if(sum<0)
        return 0;
    if(!limit && dp[pos][state][sum]!=-1)
        return dp[pos][state][sum];
    int up=limit?a[pos]:9;
    ll ans=0;
    for(int i=0; i<=up; i++)
    {
        ans+=dfs(pos-1,state,sum+(pos-state)*i,limit && i==a[pos]);
    }
    if(!limit)
        dp[pos][state][sum]=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;i++)
   {
       ans+=dfs(pos-1,i,0,true);
   }
   return ans-(pos-1);
}
int main()
{
    int t;
    ll l,r;
    cin>>t;
    memset(dp,-1,sizeof(dp));
    while(t--)
    {
        cin>>l>>r;
        cout<<solve(r)-solve(l-1)<<endl;
    }
    return 0;
}
发布了204 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43846139/article/details/103896888