非常套路的计数 DP 题,不过对于一些 DP 萌新来说确实很有意思。
设 f[i,0/1/2] 表示前 i 个字符构成的分别以 a,b,c 结尾的子序列的个数,那么 f[n,2] 即为答案。
考虑转移。
当 ai=? 时:
⎩⎨⎧f[i,0]=f[i−1,0]+3cnti−1f[i,1]=f[i−1,1]+f[i−1,0]f[i,2]=f[i−1,2]+f[i−1,1]
当 ai=? 时:
⎩⎨⎧f[i,0]=f[i−1,0]×3+3cnti−1f[i,1]=f[i−1,1]×3+f[i−1,0]f[i,2]=f[i−1,2]×3+f[i−1,1]
按上式转移,这题就做完了。
cnti 表示前 i 个字符中有 cnti 个问号。这里解释一下 3cnti−1 的意义,之前的 ? 会将一个串变为 3cnti−1 个不同的串,每个串中都含有 i 这个位置的字符 a(无论是从 ? 变换而来还是原先就是 a),所以需要计算 3cnti−1 次,其他的意义也是差不多的,都是为了统计 ? 对答案的影响。
记得开 long long ,菜鸡不开 long long WA 了好几发,呜呜呜
Show the Code
C++#include<cstdio>
#define int ll
typedef long long ll;
const int mod=1e9+7;
int f[200005][3];
char s[200005];
signed main() {
int n,pw=1;
scanf("%lld%s",&n,s+1);
for(register int i=1;i<=n;++i) {
if(s[i]=='?') {
f[i][0]=(3*f[i-1][0]%mod+pw)%mod;
f[i][1]=(3*f[i-1][1]%mod+f[i-1][0])%mod;
f[i][2]=(3*f[i-1][2]%mod+f[i-1][1])%mod;
pw=(ll)pw*3%mod;
}
else {
f[i][0]=f[i-1][0];
f[i][1]=f[i-1][1];
f[i][2]=f[i-1][2];
if(s[i]=='a') f[i][0]=(f[i][0]+pw)%mod;
else f[i][s[i]-'a']=(f[i][s[i]-'a']+f[i-1][s[i]-'a'-1])%mod;
}
}
printf("%d\n",f[n][2]);
return 0;
}