HDU 3709 Balanced Number

标签(空格分隔): 数位DP


题目链接

枚举作为枢纽的点,注意零的情况

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
ll read()
{
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
int T,num[20];
ll f[20][20][10000];
ll dp(int step,int pos,int r,int lim)
{
    if(step==0)return r==0;
    if(!lim&&~f[step][pos][r])return f[step][pos][r];
    int x=lim?num[step]:9;ll res=0;
    for(int i=0;i<=x;i++)
    {
        if(step==pos){res+=dp(step-1,pos,r,lim&&i==x);continue;}
        if(r+(step-pos)*i<0)continue;
        res+=dp(step-1,pos,r+(step-pos)*i,lim&&i==x);
    }
    if(!lim)f[step][pos][r]=res;
    return res;
}
ll calc(ll x)
{
    if(x<0)return 0;
    if(x==0)return 1;
    int len=0;
    while(x)num[++len]=x%10,x/=10;
    ll res=1-len;
    for(int i=1;i<=len;i++)res+=dp(len,i,0,1);
    return res;
}
int main()
{
    memset(f,-1,sizeof(f));
    int T=read();
    while(T--)
    {
        ll L=read(),R=read();
        printf("%lld\n",calc(R)-calc(L-1));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/ljzalc1022/p/9018981.html