【HDU3709】Balanced Number 数位DP

Balanced Number

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

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学习笔记
我们只需要枚举中间点所在的位置,就可以进行DP了;
假如当前的位在中间点的前面我们就加上这个点到中间点的位数;反之减去;
注意在dfs的时候要判断如果当前状态已经是负的了,就要返回,一是状态已经不合法了;二是在dp数组中不能有负下标。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define ll long long 
using namespace std;
int n;
ll dp[20][20][10000];
int a[30];
int pos;
ll dfs(int pos,int balance,int sum,int limit)
{    
    if(pos==-1) 
        return sum==0;
    if(sum<0) 
        return 0;
    if(dp[pos][balance][sum]!=-1&&(!limit)) 
        return dp[pos][balance][sum];
    int up= limit ? a[pos] : 9;
    ll Tmp=0;
    for(int i=0;i<=up;i++)
        Tmp+=dfs(pos-1,balance,sum+(pos-balance)*i,limit && i==up);
    if(!limit) 
        dp[pos][balance][sum]=Tmp;
    return Tmp;
}
ll solve(ll x)
{
    pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    ll sum=0;
    for(int i=pos-1;i>=0;i--)
        sum+=dfs(pos-1,i,0,true);
    return sum-pos;
}
int main()
{
    memset(dp,-1,sizeof(dp));
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        ll x,y;
        scanf("%I64d%I64d",&x,&y);
        printf("%I64d\n",solve(y)-solve(x-1));
    }
    return 0;
}
阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页