牛客网NOIP赛前集训营-提高组(第一场)B 数数字

数数字

思路:

数位dp

代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pii pair<int, int>
#define piii pair<pii, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
//head

LL L, R, L1, R1;
int tot = 0;
int a[25];
map<LL, LL>dp[25];
LL dfs(int pos, LL mul, bool limit, bool zero) {
    if(pos == 0) {
        if(zero) mul = 0;
        if(L1 <= mul && mul <= R1) return 1;
        else return 0;
    }
    if(!limit && !zero && dp[pos].find(mul) != dp[pos].end()) return dp[pos][mul];
    int up = 9;
    if(limit) up = a[pos];
    LL ans = 0;
    for (int i = 0; i <= up; i++) {
        if(zero) {
            if(i == 0) ans += dfs(pos-1, mul, limit && i == up, zero && i == 0);
            else ans += dfs(pos-1, mul*i, limit && i == up, zero && i == 0);
        }
        else ans += dfs(pos-1, mul*i, limit && i == up, zero && i == 0);
    }
    if(!limit && !zero) dp[pos][mul] = ans;
    return ans;
}
LL solve(LL n) {
    tot = 0;
    if(n == -1) return 0;
    if(n == 0) tot++;
    while(n) {
        a[++tot] = n%10;
        n /= 10;
    } 
    return dfs(tot, 1, 1, 1);
}
int main() {
    scanf("%lld %lld %lld %lld", &L, &R, &L1, &R1);
    printf("%lld\n", solve(R) - solve(L-1));
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/widsom/p/9624151.html