HDOJ 3709 Balanced Number (数位DP)

题意:求[x , y]中有多少个平衡数。

平衡数:选定一位作为支点,若左右的力矩平衡则该数是平衡数,否则不是。For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9

View Code
#include <stdio.h>
#include <string.h>
#define N 19
#define M 1378
typedef __int64 LL;
LL dp[N][N][M];
int digit[N];
LL dfs(int pos,int o,int sum,int f)
{
    if(sum<0)   return 0;
    if(pos==-1) return sum==0;
    if(!f&&dp[pos][o][sum]!=-1) return dp[pos][o][sum];

    LL ret=0;
    int max=f?digit[pos]:9;
    for(int i=0;i<=max;i++)
    {
        ret+=dfs(pos-1,o,sum+(pos-o)*i,f&&i==max);
    }
    if(!f)  dp[pos][o][sum]=ret;
    return ret;
}
LL cal(LL x)
{
    int pos=0;
    while(x)
    {
        digit[pos++]=x%10;
        x/=10;
    }
    LL ret=0;
    for(int o=0;o<pos;o++)
    {
        ret+=dfs(pos-1,o,0,1);
    }
    return ret-pos+1;
}
int main()
{
    int t;
    memset(dp,-1,sizeof(dp));
    scanf("%d",&t);
    while(t--)
    {
        LL x,y;
        scanf("%I64d%I64d",&x,&y);
        printf("%I64d\n",cal(y)-cal(x-1));
    }
    return 0;
}
posted @ 2012-09-02 16:26  BeatLJ  阅读(427)  评论(0编辑  收藏  举报