HDU 3709 Balanced Number

18 篇文章 0 订阅

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3709

数位DP专题:http://blog.csdn.net/chy20142109/article/details/50930004


题意:求区间范围内的平衡数。所谓平衡数就是找一个数位作为中心,其他位产生的值为到中心的距离*该位的数值,如果中心左边的值等于右边的值,就叫

做平衡数。比如4139,3作为中心,左边 = 4 * 2 + 1 * 1 = 右边 = 9 * 1.

思路: 枚举固定每一位作为中心位进行统计。如果第k位作为中心位,那么可以通过判断∑digit[i]*( i - k )(i = m to 1)这个值最后是否为0从而确定

是否为平衡数。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
int T;
LL a,b;
LL dp[20][20][3600];
int digit[20];
LL dfs(int pos,int num,int k,bool flag)
{
    if( k==0 ) return num == 0;
    if ( num < 0 ) return 0;
    if ( !flag && dp[k][pos][num]!=-1 ) return dp[k][pos][num];
    int ed = flag?digit[k]:9;
    LL ans = 0;
    rep(i,0,ed)
    {
        ans+=dfs(pos,num+i*(k - pos),k-1,flag && (i == ed));
    }
    if(!flag) dp[k][pos][num] = ans;
    return ans;
}

LL cal(LL x)
{
    int len = 0;
    while(x)
    {
        digit[++len] = x % 10;
        x/=10;
    }
    LL ans = 0;
    rep(i,1,len) ans+=dfs(i,0,len,1);
    ans-=len-1;
    return ans;
}


int main()
{
    Clean(dp,-1);
    cin>>T;
    while(T--)
    {
        scanf("%I64d %I64d",&a,&b);
        printf("%I64d\n",cal(b) - cal(a-1));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值