题解:AT_abc465_e [ABC465E] Digit Circus
暴力很好写,略去。
自然的,想到数位 DP,下面分析每个条件:
分析空间复杂度:
实现时注意
:::success[代码]
ATcoder 提交记录。
/*
Start Code At 2026-07-04 20:30:44 .
Code by Bestart (luogu uid : 1062290) .
*/
#include <bits/stdc++.h>
#define gc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf , 1 , fread_cnt , stdin) , p1 == p2) ? EOF : *p1 ++)
using namespace std ;
using db = double ;
using i128 = __int128 ;
using ll = long long ;
using ldb = long double ;
using uint = unsigned int ;
using ui128 = unsigned __int128 ;
using ull = unsigned long long ;
#define inline
//#define int long long
mt19937 rnd( chrono :: system_clock :: now() .time_since_epoch() .count() ) ;
const uint fread_cnt = 1 << 20 | 10 ;
const uint mod = 998244353 ;
const uint MN = 1e6 + 10 ;
const int inf = 1e9 + 7 ;
//const ll inf = 1e18 ;
char buf[fread_cnt] , *p1 = buf , *p2 = buf ;
template <typename T = int>
inline T read()
{
bool f = 0 ; T x = 0 ; char ch = gc() ;
while(ch < '0' || ch > '9') f ^= ch == '-' , ch = gc() ;
while(ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + (ch ^ 48) , ch = gc() ;
return f ? -x : x ;
}
/*
210
88
100
38
*/
string s ;
uint dp[501][3][2][1024] , cnt ;
inline uint dfs (uint pos , bool limit , bool lead , uint sum , bool jud3 , uint S)
{
if(pos == 0)
{
bool ok1 = sum == 0 ; // 已提前对 $3$ 取模
bool ok2 = jud3 ; // 是否含有 `3`
bool ok3 = __builtin_popcount(S) == 3 ; // __builtin_popcount 是 GCC 编译器内置的计算二进制下为 `1` 的位置个数的函数
if(ok1 && !ok2 && !ok3) return 1 ;
if(!ok1 && ok2 && !ok3) return 1 ;
if(!ok1 && !ok2 && ok3) return 1 ; // 只满足一个条件的才进行统计
return 0 ;
}
if(!limit && !lead && dp[pos][sum][jud3][S]) return dp[pos][sum][jud3][S] ; // 记忆化
uint up = limit ? s[pos]^48 : 9 , res = 0 ;
for(uint i = 0 ; i <= up ; ++ i)
{
res = (res + dfs(pos-1 , limit && i==up , lead && i==0 , (sum+i)%3 , jud3 || i==3 , i!=0 || !lead ? S | (1u << i) : S)) % mod ; // 对于 S,没有前导 0 时加入 i
}
return dp[pos][sum][jud3][S] = res ; // 记忆化
}
inline bool solve()
{
// 暴力代码
// uint n , ans = 0 ;
// cin >> n ;
// set<uint> st ;
// for(uint i = 1 ; i <= n ; ++ i)
// {
// st .clear() ;
// uint x = i ;
// bool ok1 = x % 3 == 0 ;
// bool ok2 = 0 ;
// while(x) ok2 |= x%10 == 3 , st .insert(x % 10) , x /= 10 ;
// bool ok3 = st .size() == 3 ;
// if(ok1 && !ok2 && !ok3) ++ ans ;
// if(!ok1 && ok2 && !ok3) ++ ans ;
// if(!ok1 && !ok2 && ok3) ++ ans ;
// }
// cout << ans << '\n' ;
cin >> s ;
uint n = s .size() ;
reverse(s .begin() , s .end()) , s = " " + s ;
cout << dfs(n , 1 , 1 , 0 , 0 , 0) - 1 << '\n' ; // 高位往低位枚举,需要去掉 0
return 0 ;
}
signed main()
{
// freopen(".in" , "r" , stdin) ;
// freopen(".out" , "w" , stdout) ;
cin.tie(0) -> sync_with_stdio(0) ;
// system("fc .out .ans") ;
// int t = 1 ; cin >> t ; while(t --) solve() ;
// while(!solve()) ;
solve() ;
return 0 ;
}
:::