【數位dp】Beautiful numbers CodeForces - 55D

CN_swords發表於2017-05-21

Beautiful numbers  CodeForces - 55D

碰到的第二類數位dp的問題:求被整除的個數

這一種不同的特徵在於餘數,所以將餘數作為dp的變數。

這題比較麻煩,題意簡單的來說是:找(非0)的所有位數都能整除這個數的數。

要使所有非0位數整除這個數,那麼 這個數%這些非0位數的最小公倍數==0。

那麼不同的特徵不僅在餘數,還有最小公倍數上。

因為最小公倍數最大是2520,那麼餘數最大也就是2520,那麼要開dp[20][2520][2520],會爆記憶體。

發現0-9之間最小公倍數只有48個,那麼離散化下,則開個dp[20][2520][50]即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<map>
#include<queue>
#include<cmath>
#include<algorithm>
#include<deque>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const int N = 20;
const double eps = 1e-6;
#pragma comment(linker, "/STACK:102400000,102400000")

map<int,int> mp;
int all[1<<10],cut[50];
LL gcd(LL a,LL b) {
    return b==0 ? a:gcd(b,a%b);
}
LL lcm(LL a,LL b){
    return a/gcd(a,b)*b;
}
void init() //離散化所有公倍數
{
    int cnt = 0;
    for(int i = 1; i < (1 << 10); i++)
    {
        int ans = 1;
        for(int j = 1; j < 10; j++)
        {
            if((1<<j) & i)
               ans = lcm(ans,j);
        }
        if(!mp.count(ans))
        {
            mp[ans] = cnt;
            cut[cnt++] = ans;
        }
        all[i] = mp[ans];
    }
}
char bit[N];
LL dp[N][2520][50]; // 餘數<2520 公約數個數<50
LL dfs(int pos,int res,int state,int limit)
{
    if(pos == 0)
    {
        if(cut[all[state]] == 0)   return 0;
        else return res%cut[all[state]] == 0;
    }
    if(!limit && dp[pos][res][all[state]] != -1 && cut[all[state]] != 0)
        return dp[pos][res][all[state]];
    int up = limit ? bit[pos]:9;
    LL ans = 0;
    for(int i = 0; i <= up; i++)
        ans += dfs(pos-1,(res*10+i)%2520,state|(1<<i),limit && (i == bit[pos]));
    if(!limit && cut[all[state]] != 0)  dp[pos][res][all[state]] = ans;
    return ans;
}
LL solve(LL a)
{
    int pos = 0;
    while(a)
    {
        bit[++pos] = a%10;
        a /= 10;
    }
    return dfs(pos,0,0,1);
}
int main()
{
    int T;
    scanf("%d",&T);
    init();
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        LL a,b;
        scanf("%lld%lld",&a,&b);
        printf("%lld\n",solve(b)-solve(a-1));
    }
    return 0;
}


相關文章