前言
怎么题解区都是 的啊,我来发一个复杂度比较奇妙的特好写做法。
思路
首先有结论:一个字符串是好的,当且仅当字符串中 的奇偶性相同。
- 充分性:当每个字母的奇偶性相同时,可以先使用操作一使得每个字母的个数小于 ,此时每个字母还剩下其个数对二取模的值,如果还有剩下的就再使用一次操作二消完;
- 必要性:操作一不会使任何字母个数的奇偶性改变,操作二会使每个字母的奇偶性改变,最终的状态需要将每个字母个数变成 ,即都是偶数,所以最初的奇偶性必须相同。
一种朴素的 DP 就是设 表示前 个字母,有 个合法的子串,满足 且 组成的字符串中 对 取模的值分别为 的 的个数为 的方案数。
这样子显然跑不过,考虑优化,将 分为一组,将 分为一组,将 分为一组,将 分为一组。
这样转移仍然是对的,因为这一位填什么所对应的状态贡献是唯一的,转移也仍然是 的。
根据插板法,状态的个数上界为为 ,但是实际上,状态数只有 ,使用记忆化搜索就能轻松通过。
代码
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define int long long
const int N = 55,mod = 998244353;
int n,k;
string s;
gp_hash_table<int,int> mp;
gp_hash_table<int,bool> vis;
int dfs(int p,int now,int a,int b,int c,int d)
{
// cout<<p<<' '<<now<<' '<<a<<' '<<b<<' '<<c<<' '<<d<<'\n';
if(p>n) return (now>=k);
int pp = p+now*100+a*1000000+b*100000000+c*10000000000+d*1000000000000;
if(vis[pp]) return mp[pp];
vis[pp] = 1;
int res = 0;
if(s[p]=='?'||s[p]=='A') res+=dfs(p+1,now+c,c,d,a+1,b);
if(s[p]=='?'||s[p]=='B') res+=dfs(p+1,now+d,d,c,b,a+1);
if(s[p]=='?'||s[p]=='C') res+=dfs(p+1,now+b,b,a+1,d,c);
res%=mod;
return mp[pp] = res;
}
signed main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>k>>s,s = ' '+s;
cout<<dfs(1,0,0,0,0,0);
return 0;
}