zl程序教程

您现在的位置是:首页 >  其他

当前栏目

AcWing 1084. 数字游戏 II

游戏 数字 II AcWing
2023-09-27 14:28:12 时间

\(AcWing\) \(1084\). 数字游戏 $II $

题目传送门

一、方法1

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 32;
const int M = 100; // n<=100,所有 mod n 的结果最大是99

int mod;
int a[N];
int f[N][M];

int dfs(int pos, int sum, bool limit) {
    if (pos == 0) return sum % mod == 0; //各位数字和 %n == 0就是一个答案

    if (!limit && ~f[pos][sum]) return f[pos][sum];

    int ans = 0, up = limit ? a[pos] : 9;
    for (int i = 0; i <= up; i++)
        ans += dfs(pos - 1, (sum + i) % mod, limit && i == a[pos]);

    if (!limit) f[pos][sum] = ans;
    return ans;
}

int calc(int x) {
    //疑问:为什么本题不能将memset放在整体上呢?是因为取模造成的吗?
    //答:是的,因为n是每次全新输入的,如果有兴趣,可以再加一维,维护n
    memset(f, -1, sizeof f);
    int al = 0;
    while (x) a[++al] = x % 10, x /= 10;
    //某人又命名了一种取模数,这种数字必须满足各位数字之和 mod N 为 0。
    //前0位数字和为0,st = 0
    return dfs(al, 0, true);
}

int main() {
    //加快读入
    ios::sync_with_stdio(false);
    cin.tie(0);

    int l, r;
    while (cin >> l >> r >> mod)
        printf("%d\n", calc(r) - calc(l - 1));
    return 0;
}

二、方法2

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 32;
const int M = 100; // n<=100,所有 mod n 的结果最大是99

int mod;
int a[N];
int f[N][M][M];

int dfs(int pos, int sum, bool limit) {
    if (pos == 0) return sum % mod == 0; //各位数字和 %n == 0就是一个答案

    if (!limit && ~f[pos][sum][mod]) return f[pos][sum][mod];

    int ans = 0, up = limit ? a[pos] : 9;
    for (int i = 0; i <= up; i++)
        ans += dfs(pos - 1, (sum + i) % mod, limit && i == a[pos]);

    if (!limit) f[pos][sum][mod] = ans;
    return ans;
}

int calc(int x) {
    int al = 0;
    while (x) a[++al] = x % 10, x /= 10;
    //某人又命名了一种取模数,这种数字必须满足各位数字之和 mod N 为 0。
    //前0位数字和为0,st = 0
    return dfs(al, 0, true);
}

int main() {
    //加快读入
    ios::sync_with_stdio(false);
    cin.tie(0);
    //疑问:为什么本题不能将memset放在整体上呢?是因为取模造成的吗?
    //答:是的,因为n是每次全新输入的,如果有兴趣,可以再加一维,维护n
    memset(f, -1, sizeof f);

    int l, r;
    while (cin >> l >> r >> mod)
        printf("%d\n", calc(r) - calc(l - 1));
    return 0;
}