HDU 3709 Balanced Number

【原题目】

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 [xy].

 

【题意】

t组数据,每组给出xy。要求求出xy之间的满足下列条件的数字的个数:

例如 选取数字nnx,y之间;选择n当中第mid个数位为对称轴,设第pos位的 数字为num[pos],  将每个数位的权值num[pos]*(pos-mid)相加,总和为0

【数据范围】

 (0 < t ≤ 30). . (0 ≤ x ≤ y ≤ 1018).

 

【分类】

数位dp

 

【思路】

找到状态转移的规律,每组状态如何转移只和当前的数位上的数字有关;每组状态只与当前处理到哪一个数位,对称轴是哪一位,前驱的权值和为多少有关。

所以可以用数位dp的方式,加上记忆化搜索的思路,将每一个状态所对应的数字的个数计算并保存下来。

 

源代码

 

#include<cstring>

 

#include<cstdio>

 

 

using namespace std;

 

 

long long num[20];

 

long long dp[20][20][5000];

long long help(int pos,int limit,long long pre,int mid)

{

    if(pos<=0)

        return pre==0;

    if(pre<0)

    {

        return 0;

    }

    if(!limit&&dp[pos][mid][pre]!=-1)

        return dp[pos][mid][pre];

 

    int end=limit?num[pos]:9;

    long long ans=0;

    for(int i=0;i<=end;i++)

    {

        ans+=help(pos-1,limit&&(i==end),pre+i*(pos-mid),mid);

    }

    if(!limit)

        dp[pos][mid][pre]=ans;

 

    //printf("ans:%lld\n",ans);

    return ans;

 

}

long long fun(long long x)

{

    memset(num,0,sizeof num);

    int cnt=0;

    while(x)

    {

        num[++cnt]=x%10;

        x=x/10;

    }   

 

    long long res=0;

    for(int i=1;i<=cnt;i++)

    {

        res+=help(cnt,1,0,i);

    }

    return res-cnt+1; //此处会将0 ,00 ,000 ....重复计数,它们都是0,只应//该计算一次,所以应该将重复计入的0删除掉。

}

int main()

{

    int t;

    scanf("%d",&t);

   memset(dp,-1,sizeof dp);

    while(t--)

    {

           //memset(dp,-1,sizeof dp);

        long long x,y;

        scanf("%lld%lld",&x,&y);

        long long temp;

        if(x>y)

        {

            temp=x;

            x=y;

            y=temp;

        }

        printf("%lld\n",fun(y)-fun(x-1));

    }

    return 0;

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值