跳到正文

题解

题解:AT_abc465_e [ABC465E] Digit Circus

IsaacPang2012约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月30日
更新
2026年7月30日
篇幅
约 5 分钟

版本

  1. v1当前

题意简述

题目意思很简单,就是问有多少个 ≤n\le n 的数,满足恰好一个条件成立,分别为:

  1. 整除 33;
  2. 包括 33;
  3. 刚好用了 33 个不同数字。

由于 nn 高达 1050010^{500},只能用字符串读入,考虑数位 DP。
由于状态转移较为复杂,不妨用记忆化搜索。


状态设计

我们用字符串去表示当前数。

dp[pos][sameprefix][allzero][mod3][has3][mask]dp[pos][sameprefix][allzero][mod3][has3][mask] 表示当前处理到第 pospos 位(可以有前导 00)

状态定义
sameprefixbool,表示当前 ii 位是否和 nn 一致
allzerobool,表示当前是否全为 00
mod3int 当前数除 33 的余数
has3bool,表示当前字符串是否包括 33
maskint 一个 1010 位的二进制压缩数,表示当前构造出现了哪些数字

转移

对于转移为两种情况:

  • 若当前 sameprefix 为 true,则只能取 0∼s[pos]0 \sim s[pos];
  • 否则能取 0∼90 \sim 9。

新的状态为(定义i为新的位所取数字):

  • newsameprefix = sameprefix && (i == s[pos])
  • newmod3 = (mod3 * 10 + i) % 3
  • newallzero = allzero && (i == 0)
  • newhas3 = has3 || (i == 3)
  • newmask = mask | (1 << i)

对于所有 ii:

dp[pos][sameprefix][allzero][mod3][has3][mask]+=dp[pos+1][newsameprefix][newallzero][newmod3][newhas3][newmask]dp[pos][sameprefix][allzero][mod3][has3][mask] += dp[pos+1][newsameprefix][newallzero][newmod3][newhas3][newmask]

对于搜索,终止条件为 pos == n.length() + 1,检查是否恰好有一个成立,若成立则 return 1,否则 return 0。


代码

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=505, maxmask=(1<<10)+5;
const ll P=998244353;
int n;
string s;
ll dp[maxn][2][2][3][2][maxmask];
ll dfs (int pos, bool sameprefix, bool allzero, int mod3, bool has3, int mask){
    if (pos==n+1){
        if (allzero){
            return 0;
        }
        bool A=(mod3==0), B=has3, C=(__builtin_popcount(mask)==3);
        if (A+B+C==1){
            return 1;
        }
        else{
            return 0;
        }
    }
    if (dp[pos][sameprefix][allzero][mod3][has3][mask]!=-1){
        return dp[pos][sameprefix][allzero][mod3][has3][mask];
    }
    ll limit=9;
    if (sameprefix){
        limit=s[pos]-'0';
    }
    ll res=0;
    for (int i=0;i<=limit;i++){
        bool newsameprefix=sameprefix && (i==limit), newallzero=allzero && (!i), newhas3;
        int newmod3, newmask;
        if (newallzero){
            newmod3=0;
            newhas3=false;
            newmask=0;
        }
        else{
            newmod3=(mod3*10+i)%3;
            newhas3=has3 || (i==3);
            newmask=mask | (1<<i);
        }
        res+=dfs(pos+1,newsameprefix,newallzero,newmod3,newhas3,newmask);
    }
    res%=P;
    dp[pos][sameprefix][allzero][mod3][has3][mask]=res;
    return res;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>s;
    n=s.length();
    s=" "+s;
    memset(dp,-1,sizeof(dp));
    cout<<dfs(1,true,true,0,false,0);
    return 0;
}
原文