P3413 SAC#1 - 萌数【数位DP+回文数】

题目描述
只有满足“存在长度至少为2的回文子串”的数是萌的——也就是说,101是萌的,因为101本身就是一个回文数;110是萌的,因为包含回文子串11;但是102不是萌的,1201也不是萌的。
现在SOL想知道从l到r的所有整数中有多少个萌数。
由于答案可能很大,所以只需要输出答案对1000000007(10^9+7)的余数。
输入格式:
输入包含仅1行,包含两个整数:l、r。
输出格式:
输出仅1行,包含一个整数,即为答案。
输入样例#1:
1 100
输出样例#1:
10
输入样例#2:
100 1000
输出样例#2:
253
说明
记n为r在10进制下的位数。
对于10%的数据,n <= 3。
对于30%的数据,n <= 6。
对于60%的数据,n <= 9。
对于全部的数据,n <= 1000,l < r。

分析:
这个回文数有个特点,判断回文数,只需要回文长度为2和3的情况。
我作的是减法,找不是回文数的个数。

#include <bits/stdc++.h>
using namespace std;
typedef pair<char, int> pi;
typedef pair<int, int> pii;
typedef long long LL;
const LL mod = 1e9 + 7;
const int MAXN = 2010;
LL a[1010], dp[1010][15][15][2];
char A[MAXN], B[MAXN];

inline LL dfs(LL pos, LL x, LL y, LL limit, LL sta) {
    if(pos < 0) return 1;
    if(dp[pos][x][y][sta] >= 0 && !limit) return dp[pos][x][y][sta] % mod;
    LL up = limit ? a[pos] : 9;
    LL ans = 0;
    for(LL i = 0; i <= up; ++i) {
        if(i == x || i == y) continue;
        if(sta && i == 0) ans += dfs(pos - 1, x, y, limit && i == up, 1);
        else ans += dfs(pos - 1, i, x, limit && i == up, 0);
        ans %= mod;
    }
    if(!limit) dp[pos][x][y][sta] = ans;
    return ans;
}

LL so(char s[]) {
    LL p = strlen(s);
    for(LL i = p - 1; i >= 0; --i) {
        a[p - i - 1] = s[i] - '0';
    }
    return dfs(p - 1, 10, 11, 1, 1) % mod;
}

int main() {
    memset(dp, -1, sizeof(dp));
    scanf("%s %s", A, B);
    LL len = strlen(B), cnt1 = 0, cnt2 = 0, cnt = 0;
    for(int i = 0; i < len; ++i) {
        cnt1 = cnt1 * 10 + B[i] - '0';
        cnt1 %= mod;
    }
    len = strlen(A);
    for(int i = 0; i < len; ++i) {
        cnt2 = cnt2 * 10 + A[i] - '0';
        cnt2 %= mod;
    }
    char a1 = 'a', a2 = 'b';
    for(int i = len - 1; i >= 0; --i) {
        if(A[i] == a1 || A[i] == a2) {
            cnt = 1;
            break;
        }
        a2 = a1;
        a1 = A[i];
    }
    printf("%lld\n", (cnt1 - so(B) + so(A) - cnt2 + cnt + mod) % mod);
    return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值