题意简述
题目意思很简单,就是问有多少个 的数,满足恰好一个条件成立,分别为:
- 整除 ;
- 包括 ;
- 刚好用了 个不同数字。
由于 高达 ,只能用字符串读入,考虑数位 DP。
由于状态转移较为复杂,不妨用记忆化搜索。
状态设计
我们用字符串去表示当前数。
表示当前处理到第 位(可以有前导 )
| 状态 | 定义 |
|---|---|
sameprefix | bool,表示当前 位是否和 一致 |
allzero | bool,表示当前是否全为 |
mod3 | int 当前数除 的余数 |
has3 | bool,表示当前字符串是否包括 |
mask | int 一个 位的二进制压缩数,表示当前构造出现了哪些数字 |
转移
对于转移为两种情况:
- 若当前
sameprefix为true,则只能取 ; - 否则能取 。
新的状态为(定义i为新的位所取数字):
newsameprefix = sameprefix && (i == s[pos])newmod3 = (mod3 * 10 + i) % 3newallzero = allzero && (i == 0)newhas3 = has3 || (i == 3)newmask = mask | (1 << i)
对于所有 :
对于搜索,终止条件为 pos == n.length() + 1,检查是否恰好有一个成立,若成立则 return 1,否则 return 0。
代码
#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;
}