解题报告 『不要62(数位动规)』

原题地址

又学会了骂人的新词语。

 

代码实现如下:

#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (register int i = (a); i <= (b); i++)

const int maxn = 10;

int l, r, ans, len;
int num[maxn], dp[maxn][maxn];

void origin() {memset(dp, -1, sizeof(dp));}

int dfs(int pos, int limit, int lead, int is_six) {
    int ans = 0;
    if (!pos) return 1;
    if (!limit && !lead && dp[pos][is_six] != -1) return dp[pos][is_six];
    int res = limit ? num[pos] : 9;
    rep(i, 0, res) {
        if (i == 4 || (is_six && i == 2)) continue;
        if (!i && lead) ans += dfs(pos - 1, (i == res) && limit, 0, i == 6);
        else ans += dfs(pos - 1, (i == res) && limit, 1, i == 6);
    }
    if (!limit && !lead) dp[pos][is_six] = ans;
    return ans;
}

int work(int x) {
    origin();
    len = 0;
    while (x) {
        num[++len] = x % 10;
        x /= 10;
    }
    return dfs(len, 1, 1, 0);
}

void write(int x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

int main() {
    while (scanf("%d%d", &l, &r) && l && r) {
        write(work(r) - work(l - 1));
        printf("\n");
    }
    return 0;
}
View Code

 

但实际上我更习惯顺着搜:

#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (register int i = (a); i <= (b); i++)

const int maxn = 10;

int l, r, ans, len;
int num[maxn], dp[maxn][maxn];

void origin() {memset(dp, -1, sizeof(dp));}

int dfs(int pos, int limit, int lead, int is_six) {
    int ans = 0;
    if (pos > len) return 1;
    if (!limit && !lead && dp[pos][is_six] != -1) return dp[pos][is_six];
    int res = limit ? num[len - pos + 1] : 9;
    rep(i, 0, res) {
        if (i == 4 || (is_six && i == 2)) continue;
        if (!i && lead) ans += dfs(pos + 1, (i == res) && limit, 0, i == 6);
        else ans += dfs(pos + 1, (i == res) && limit, 1, i == 6);
    }
    if (!limit && !lead) dp[pos][is_six] = ans;
    return ans;
}

int work(int x) {
    origin();
    len = 0;
    while (x) {
        num[++len] = x % 10;
        x /= 10;
    }
    return dfs(1, 1, 1, 0);
}

void write(int x) {
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

int main() {
    while (scanf("%d%d", &l, &r) && l && r) {
        write(work(r) - work(l - 1));
        printf("\n");
    }
    return 0;
}
View Code
posted @ 2019-06-11 20:36  雲裏霧裏沙  阅读(161)  评论(0编辑  收藏  举报