You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

AcWing 1082. 数字游戏

一、题目描述

科协里最近很流行数字游戏。

某人命名了一种不降数,这种数字必须满足从左到右各位数字呈非下降关系,如 123446

现在大家决定玩一个游戏,指定一个整数闭区间 [a,b],问这个区间内有多少个不降数。

输入格式 输入包含多组测试数据。

每组数据占一行,包含两个整数 ab

输出格式 每行给出一组测试数据的答案,即 [a,b] 之间有多少不降数。

数据范围 1≤a≤b≤2^{31}1

输入样例

1 9
1 19

输出样例

9
18

二、Code

无脑模板,套进去AC

#include <bits/stdc++.h>

using namespace std;

const int N = 32;

int l, r;
int a[N], al;
int f[N][N];
/**
 *
 * @param u 当前的数位
 * @param st  前一位填写的是什么
 * @param op  是不是贴上界
 * @return    在当前情况下,后续符合条件的有多少个
 */
int dfs(int u, int st, bool op) {
    if (u == 0) return 1; // 如果走完所有情况,还活着,说明前面的都符合条件,就是一个合理解++
    if (!op && ~f[u][st]) return f[u][st];
    int ans = 0, up = op ? a[u] : 9;
    for (int i = st; i <= up; i++) // 注意起始点,i >= st
        ans += dfs(u - 1, i, op && i == a[u]);

    if (!op) f[u][st] = ans;
    return ans;
}

int calc(int x) {
    al = 0;
    while (x) a[++al] = x % 10, x /= 10;
    return dfs(al, 0, true);
}

int main() {
    memset(f, -1, sizeof f);
    while (~scanf("%d%d", &l, &r))
        printf("%d\n", calc(r) - calc(l - 1));
    return 0;
}