1. 程式人生 > >hdu3709 Balanced Number (數位dp)

hdu3709 Balanced Number (數位dp)

careful href multi true search target tar sta total

題目傳送門

Balanced Number

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


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

Author GAO, Yuan

Source 2010 Asia Chengdu Regional Contest

Recommend zhengfeng | We have carefully selected several similar problems for you: 3711 3715 3718 3713 3712 題意:求平衡數,就是以一個數位為支點,左右兩邊的力矩相等
比如4139 以3為支點,則4*2+1+1==9*1 題解:數位dp,dp[i][j][k]:i表示數位,j表示支點,k表示力矩和
代碼:
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
typedef long long ll;
ll n,m;
ll dp[20][20][2000];//多加一維表示力矩
int bit[20];
ll dfs(int pos,int center,int sum,bool limit)
{
    if(pos==-1) return sum==0;
    if(sum<0)return 0;//剪枝
    if(!limit&&dp[pos][center][sum]!=-1) return dp[pos][center][sum];
    int up=limit?bit[pos]:9;
    ll ans=0;
    for(int i=0;i<=up;i++)
        ans+=dfs(pos-1,center,sum+(pos-center)*i,limit&&i==up);
    if(!limit) dp[pos][center][sum]=ans;
    return ans;
}
ll calc(ll n)
{
    int len=0;
    while(n)
    {
        bit[len++]=n%10;
        n/=10;
    }
    ll ans=0;
    for(int i=len-1;i>=0;i--)
        ans+=dfs(len-1,i,0,true);
    return ans-(len-1);//排除0、00、000....的幹擾
}
int main()
{
    int T;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        scanf("%lld %lld",&n,&m);
        printf("%lld\n",calc(m)-calc(n-1));
    }
    return 0;
}

hdu3709 Balanced Number (數位dp)