HDOJ 3709 balanced number (digit dp)

来源:互联网 发布:淘宝平均停留时间 编辑:程序博客网 时间:2024/06/08 03:10

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;}
原创粉丝点击