2018 ACM 國際大學生程序設計競賽上海大都會賽 J [Beautiful Number]

鏈接:https://www.nowcoder.com/acm/contest/163/J
來源:牛客網

時間限制:C/C++ 8秒,其他語言16秒
空間限制:C/C++ 262144K,其他語言524288K
64bit IO Format: %lld

題目描述

NIBGNAUK is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by the sum of its digits.
We will not argue with this and just count the quantity of beautiful numbers from 1 to N.

輸入描述:

The first line of the input is T(1≤ T ≤ 100), which stands for the number of test cases you need to solve.
Each test case contains a line with a positive integer N (1 ≤ N ≤ 1012 ).

輸出描述:

For each test case, print the case number and the quantity of beautiful numbers in [1, N].

示例1

輸入

2
10
18

輸出

Case 1: 10
Case 2: 12

Solution

數位DP。與BZOJ1799如出一轍,數據小了些,測試樣例變多組而已。
考慮枚舉1..12*9這108個可能的除數,因1..1012 之內數字的各位數字之和最小是1最大是12*9=108;
還是從高位到低位枚舉,下標pos-1到0,每次枚舉的數位和作爲令符合要求的被除數可以整除的模數mod,同時也是各位數字之和sum.
dp[pos][sum][val][0]: 表示到了第pos位,各位數字和是sum,前面pos位形成的數模當前枚舉的mod爲val,且前pos位全都和原數x相等的數的個數;
dp[pos][sum][val][1]: 表示到了第pos位,各位數字和是sum,前面pos位形成的數模當前枚舉的mod爲val,且前pos位全都小於原數x的數的個數.

#include <bits/stdc++.h>

#define ll long long
using namespace std;
ll dp[12][110][110][2];
int bit[15];

ll dfs(int pos, int sum, int val, int mod, bool limit) {
    if (sum - 9 * pos > 9) return 0;
    if (pos == -1) return sum == 0 && val == 0;
    if (dp[pos][sum][val][limit] != -1) return dp[pos][sum][val][limit];
    int up = limit ? bit[pos] : 9;
    ll ans = 0;
    for (int i = 0; i <= up; i++) {
        if (sum < i) break;
        ans += dfs(pos - 1, sum - i, (val * 10 + i) % mod, mod, limit && i == bit[pos]);
    }
    return dp[pos][sum][val][limit] = ans;
}

ll solve(ll n) {
    int l = 0;
    while (n) {
        bit[l++] = n % 10;
        n /= 10;
    }
    ll res = 0;
    for (int i = 1; i <= l * 9; ++i) {
        memset(dp, -1, sizeof(dp));
        res += dfs(l - 1, i, 0, i, 1);
    }
    return res;
}

int T;
ll x;

int main() {
    //freopen("../in", "r", stdin);
    scanf("%d", &T);
    for (int I = 1; I <= T; ++I) {
        printf("Case %d: ",I);
        scanf("%lld", &x);
        if (x == 1000000000000) printf("%lld\n", solve(999999999999) + 1);
        else printf("%lld\n", solve(x));
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章