Beautiful Numbers (数位dp)

题目:找1...n之间能被自身digits和整除的数字有多少。

就是一个简单的数位dp题,一共n最大1e12我特么以为是一共12位,直接开了个wei[13]的从1开始的数组。。脑子短路了感觉,想了好长一会才看到。。。写博客提醒下自己我好菜啊

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[15][120][120];
int wei[15],k;
ll dfs(int pos,int sum,int s,int limit)
{
    if(pos<1)
        return s==k&&sum%s==0;
    if(!limit&&dp[pos][sum][s]>-1)
        return dp[pos][sum][s];
    int up=limit?wei[pos]:9;
    ll ans=0;
    for(int i=0;i<=up;i++)
    {
        ans+=dfs(pos-1,(sum*10+i)%k,s+i,limit&&i==up);
    }
    if(!limit) dp[pos][sum][s]=ans;
    return ans;
}
ll solve(ll x)
{
    int len=0;
    while(x)
    {
        wei[++len]=x%10;
        x/=10;
    }
    ll ans=0;
    for(k=1;k<=9*len;k++)
    {
        memset(dp,-1,sizeof dp);
        ans+=dfs(len,0,0,1);
    }
    return ans;
}
ll n;
int main()
{
    int t,cas;
    scanf("%d",&t);
    for(cas=1;cas<=t;cas++)
    {
        scanf("%lld",&n);
        printf("Case %d: %lld\n",cas,solve(n));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dllpXFire/article/details/81448503