Codeforces 55D Beautiful Number (數位統計)

把數位dp寫成記憶化搜索的形式,方法很贊,代碼量少了不少。git

下面爲轉載內容:數組

   a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits.
    問一個區間內[l,r]有多少個Beautiful數字
    範圍9*10^18
    
    數位統計問題,構造狀態也挺難的,我想不出,個人思惟侷限在用遞推去初始化狀態,而這裏的狀態定義也比較難
    跟pre的具體數字有關

    問了NotOnlySuccess的,豁然開朗  Orz
    
    一個數字要被它的全部非零位整除,即被他們的LCM整除,能夠存已有數字的Mask,但更好的方法是存它們的LCM{digit[i]}
    int MOD = LCM{1,2,9} = 5 * 7 * 8 * 9 = 2520
    按照定義,數字x爲Beautiful : 
    x % LCM{digit[xi]} = 0
    即 x % MOD % LCM{digit[xi]} = 0
    因此能夠只需存x % MOD,範圍縮小了
    而在逐位統計時,假設到了pre***(pre指前面的一段已知的數字,而*是任意變)
        ( preSum * 10^pos + next )  % MOD % LCM(preLcm , nextLcm)
    =  ( preSum * 10 ^ pos % MOD + next % MOD ) % LCM(preLcm , nextLcm)
    == 0
    而next,nextLcm是變量,上面的比較式的意義就是
    在已知pos , preSum , preLcm狀況下有多少種(next,nextLcm)知足式子爲0
    而這個就是一個重複子問題所在的地方了,須要記錄下來,用記憶化搜索
    dfs(pos , preSum , preLcm , doing)
    加一個標記爲doing表示目前是在計算給定數字的上限,仍是沒有上限,即***類型的
    這樣就將初始化以及逐位統計寫在一個dfs了,好神奇!!!
    
    還有一點,10之內的數字狀況爲2^3 , 3^2 , 5 , 7
    因此最小公倍數組合的狀況只有4*3*2*2 = 48
    能夠存起來,我看NotOnlySuccess的寫法是
    for(int i = 1 ; i <= MOD ; i ++)
    {
        if(MOD % i == 0)
            index[i] = num++;
    }
    很棒!!

    因此複雜度大概爲19*2520*48*10(狀態數*決策數)

    我以爲這題狀態的設計不能跟具體數字分開,不然會很難設計吧
    因此用記憶化搜索,存起來
    用具體數字去計算,重複的子問題跟pre關係比較密切
    有一個比較重要的切入點就是LCM,還有%MOD縮小範圍,才能存儲

    還有優化到只需%252的,更快
    不過我以爲%2520比較好理解ide

代碼:優化

 1 const int MOD = 2520;
 2 
 3 LL dp[21][MOD][50];
 4 int digit[21];
 5 int indx[MOD+5];
 6 
 7 void init() {
 8     int num = 0;
 9     for(int i = 1; i <= MOD; ++i) {
10         if(MOD%i == 0) indx[i] = num++;
11     }
12     CL(dp, -1);
13 }
14 
15 LL gcd(LL a, LL b) {
16     return b == 0 ? a : gcd(b, a%b);
17 }
18 
19 LL lcm(LL a, LL b) {
20     return a/gcd(a, b)*b;
21 }
22 
23 LL dfs(int pos, int presum, int prelcm, bool edge) {
24     if(pos == -1)    return presum%prelcm == 0;
25     if(!edge && dp[pos][presum][indx[prelcm]] != -1)
26         return dp[pos][presum][indx[prelcm]];
27     int ed = edge ? digit[pos] : 9;
28     LL ans = 0;
29     for(int i = 0; i <= ed; ++i) {
30         int nowlcm = prelcm;
31         int nowsum = (presum*10 + i)%MOD;
32         if(i)   nowlcm = lcm(prelcm, i);
33         ans += dfs(pos - 1, nowsum, nowlcm, edge && i == ed);
34     }
35     if(!edge)    dp[pos][presum][indx[prelcm]] = ans;
36     return ans;
37 }
38 
39 LL cal(LL x) {
40     CL(digit, 0);
41     int pos = 0;
42     while(x) {
43         digit[pos++] = x%10;
44         x /= 10;
45     }
46     return dfs(pos - 1, 0, 1, 1);
47 }
48 
49 int main() {
50     //Read();
51 
52     init();
53     int T;
54     LL a, b;
55     cin >> T;
56     while(T--) {
57         cin >> a >> b;
58         cout << cal(b) - cal(a - 1) << endl;
59     }
60     return 0;
61 }
View Code
相關文章
相關標籤/搜索