原题链接:https://beta.atcoder.jp/contests/arc094/tasks/arc094_d
Normalization
Problem Statement
You are given a string S S consisting of ‘a’,’b’ and ‘c’. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo :
Choose an integer i i such that and the i i -th and -th characters in S S are different. Replace each of the -th and (i+1) ( i + 1 ) -th characters in S S with the character that differs from both of them (among a, b and c).
Constraints
S
S
consists of ‘a’, ‘b’ and ‘c’.
Input
Input is given from Standard Input in the following format:
Output
Print the number of strings that can be possibly obtained by repeatedly performing the operation, modulo 998244353 998244353 .
Sample Input 1
abc
Sample Output 1
3
abc, aaa and ccc can be obtained.
Sample Input 2
abbac
Sample Output 2
65
Sample Input 3
babacabac
Sample Output 3
6310
Sample Input 4
ababacbcacbacacbcbbcbbacbaccacbacbacba
Sample Output 4
148010497
题目大意
给定一个由 a,b,c a , b , c 组成的字符串 S(|S|<=2×105) S ( | S | <= 2 × 10 5 ) ,每次可以选择两个相邻的不同字符,把它们修改成与两者都不同的字符,求能得到的不同的字符串的个数。
题解
%%%watson,watson is so strong!!! % % % w a t s o n , w a t s o n i s s o s t r o n g ! ! !
感觉这道题真神(虽然watson说很水),如果把
a,b,c
a
,
b
,
c
表示为
0,1,2
0
,
1
,
2
,可以发现上述替换操作在
mod 3
m
o
d
3
意义下是不改变整个序列的和的。
然后开始 dp d p , dp[i][j][k][p] d p [ i ] [ j ] [ k ] [ p ] 表示在第 i i 个位置,前缀和为,当前字符为 k k ,有/无连续的相同字符时的字符个数,枚举一下的字符分别是什么就可以转移了。
最后的答案为 dp[n][tot][0][1]+dp[n][tot][1][1]+dp[n][tot][2][1]+[原串没有连续的相同字母] d p [ n ] [ t o t ] [ 0 ] [ 1 ] + d p [ n ] [ t o t ] [ 1 ] [ 1 ] + d p [ n ] [ t o t ] [ 2 ] [ 1 ] + [ 原 串 没 有 连 续 的 相 同 字 母 ] 。
代码
#include<bits/stdc++.h>
using namespace std;
const int M=2e5+5,mod=998244353;
char ch[M];
int n,sum,i,j,k,a,b,dp[M][3][3][2];
bool flag=1;
void spj()
{
for(i=2;i<=n;++i)if(ch[i]!=ch[i-1]){flag=0;break;}
if(flag)puts("1"),exit(0);
if(n<=3)(n==2?puts("2"):((ch[1]!=ch[2]&&ch[1]!=ch[3]&&ch[2]!=ch[3])?puts("3"):((ch[1]==ch[3])?puts("7"):puts("6")))),exit(0);
}
bool check(){for(int i=1;i<=n;++i)if(ch[i]==ch[i-1])return 0;return 1;}
void in(){scanf("%s",ch+1);}
void ac()
{
n=strlen(ch+1);spj();
for(i=1;i<=n;++i)sum=(sum+ch[i]-'a')%3;
for(i=0;i<=2;++i)dp[1][i][i][0]=1;
for(i=1;i<=n-1;++i)for(j=0;j<=2;++j)for(k=0;k<=2;++k)for(a=0;a<=1;++a)for(b=0;b<=2;++b)
(dp[i+1][(j+b)%3][b][a|(k==b)]+=dp[i][j][k][a])%=mod;
printf("%d",(0ll+dp[n][sum][0][1]+dp[n][sum][1][1]+dp[n][sum][2][1]+check())%mod);
}
int main(){in();ac();}