HDOJ 3709 balanced number (digit dp)

link to the question
I spend almost a whole afternoon to figure this question out and I did it! I made annotation right after the code to help understand. Although I use some else’s code for reference , I think I ,now,understand how to solve the questions alike.

#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
//d[pos][sum][axis]
using namespace std;
__int64 dp[20][30][2050];
__int64 a[20];
__int64 dfs(int pos,int sum,int axis,bool limit)
{
    if(pos==0) {return sum == 0;}     //whether the number is acceptable!!!!
    if(sum<0) return 0;  //edge_cutting
    if(!limit && dp[pos][axis][sum]!=-1) return dp[pos][axis][sum];    //has been calculate
    int up=limit ? a[pos] : 9;
    __int64 ans=0;
    for(int i=0;i<=up;i++)
    {
        ans+=dfs(pos-1,sum+i*(pos-axis),axis,limit && i==a[pos]);  //using sum of negative
    }
    //end of calculation
    if(!limit) dp[pos][axis][sum]=ans;
    return ans;
}
__int64 solve(__int64 x)    //x = maximum
{
    int pos=0;
    if(x<0)
    {
        return 0;
    }
    while(x)
    {
        a[++pos]=x%10;
        x/=10;
    }
    //start form digit 1
    __int64 ans = 0;
    int len = pos;
    for(int i=1;i<=len;i++)
    {
        ans+=dfs(pos,0,i,1);
    }
    return ans-len+1;
}
int main()
{
    __int64 li,ri;
    int T_T;
    cin>>T_T;
    memset(dp,-1,sizeof(dp));
    while(T_T--)
    {
       scanf("%I64d%I64d",&li,&ri);
       printf("%I64d\n",solve(ri)-solve(li-1));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值