跳到正文

题解

题解:AT_abc465_e [ABC465E] Digit Circus

UnionRE约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月7日
收录
2026年7月11日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
2

版本

  1. v1当前

考虑数位 DP。我们只需要记录当前用的数字集合、模 33 的值和是否包含 33 这个数字。

对于数字集合,可以使用状态压缩进 2102^{10} 大小的数。然后使用 __builtin_popcount() 即可求出使用的大小。注意不要记录到前导 00。

这样复杂度等于状态数,为 log⁡10N×210×2×2×2×3\log_{10}N\times2^{10}\times2\times2\times2\times3 完全可过。

C++
#include <bits/stdc++.h>
using namespace std;
string n;
const int maxn=550,mod=998244353;
int dp[maxn][1024][2][2][3][2];
int dfs(int pos,int use,bool have3,bool lim,int mod3,bool lead0){
    if(pos==n.size())return ((((__builtin_popcount(use)==3)+have3+(mod3==0))==1)&&(!lead0))?1:0;
    if(dp[pos][use][have3][lim][mod3][lead0]!=-1)return dp[pos][use][have3][lim][mod3][lead0];
    int up=lim?n[pos]-'0':9,ans=0;
    for(int i=0;i<=up;i++){//下面代码中,n 开头的表示新的这个值
        int nuse,nmod3=(mod3+i)%3;
        bool nhave3=have3||(i==3),nlim=lim&&(i==up),nlead0=lead0&&(i==0);
        if(!nlead0)nuse=use|(1<<i);//排除前导0
        else nuse=0;
        ans+=dfs(pos+1,nuse,nhave3,nlim,nmod3,nlead0);
        ans%=mod;
    }
    return dp[pos][use][have3][lim][mod3][lead0]=ans;
}
signed main() 
{
    memset(dp,-1,sizeof(dp));
    cin>>n;
    cout<<dfs(0,0,0,1,0,1);
    return 0;
}

再放一个美观(?)一点的
C++
#include <bits/stdc++.h>
using namespace std;
string n;
const int maxn = 550, mod = 998244353;
int dp[maxn][1024][2][2][3][2];
int dfs(int pos, int use, bool have3, bool lim, int mod3, bool lead0) {
	if (pos == n.size())
	{
		return ((((__builtin_popcount(use) == 3) + have3 + (mod3 == 0)) == 1) && (!lead0)) ? 1 : 0;
	}
	if (dp[pos][use][have3][lim][mod3][lead0] != -1)
	{
		return dp[pos][use][have3][lim][mod3][lead0];
	}
	int up = lim ? n[pos] - '0' : 9, ans = 0;
	for (int i = 0; i <= up; i++) { //下面代码中,n 开头的表示新的这个值
		int nuse, nmod3 = (mod3 + i) % 3;
		bool nhave3 = have3 || (i == 3), nlim = lim&&(i == up), nlead0 = lead0&&(i == 0);
		if (!nlead0)nuse = use | (1 << i); //排除前导0
		else nuse = 0;
		ans += dfs(pos + 1, nuse, nhave3, nlim, nmod3, nlead0);
		ans %= mod;
	}
	return dp[pos][use][have3][lim][mod3][lead0] = ans;
}
signed main() {
	memset(dp, -1, sizeof(dp));
	cin >> n;
	cout << dfs(0, 0, 0, 1, 0, 1);
	return 0;
}
原文
存档评论1 条抓取于