Atcoder Grand Contest 037B(DP,组合数学,思维)

#include<bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
string s;
int a[300007];
long long x[7],y[7];
int main(){
int n;
cin>>n;
cin>>s;
int len=s.size();
for(int i=0;i<len;++i){
if(s[i]=='B')
a[i]=1;
else if(s[i]=='G')
a[i]=2;
}
long long ans=1;
for(int i=2;i<=n;++i)
ans=1ll*ans*i%mod;//每三个球可以分配给n~1个人。
for(int i=0;i<len;++i){//遇到第一种颜色的球,记录它的个数,当遇到另一种颜色的时候从第一种颜色的球中任选一个,同时记录第二种颜色的球的个数,当遇到第三种颜色的时候,从第二种颜色的球中任选一个。
//这里第一种颜色的球的个数是用x[a[i]]存的,第二种颜色的球的个数是存在y[(a[i]+1or2)%3]中的,当遇到第三种颜色即(a[i]+1or2)%3时从第二种颜色的球中任选一个
if(y[a[i]])//i前面有y[a[i]]个(a[i]+2)%3颜色的球,遇到i时前面可以从y[a[i]]个中选取一个
ans=ans*y[a[i]]--%mod;
else if(x[(a[i]+1)%3])//和下一个else if等价,另两种颜色地位相同,遇到哪一种都可以组合,三种颜色都是等价的
ans=ans*x[(a[i]+1)%3]--%mod,y[(a[i]+2)%3]++;//前面有x[(a[i]+1)%3]个(a[i]+1)%3颜色的球,遇到i时可以从x[(a[i]+1)%3]个中选取一个
else if(x[(a[i]+2)%3])//和上一个else if等价,另两种颜色地位相同,遇到哪一种都可以组合,三种颜色都是等价的
ans=ans*x[(a[i]+2)%3]--%mod,y[(a[i]+1)%3]++;//前面有x[(a[i]+2)%3]个(a[i]+2)%3颜色的球,遇到i时可以从x[(a[i]+2)%3]个中选取一个
else
x[a[i]]++;//记录当前a[i]颜色的球的数量
}
cout<<ans;
return 0;
}

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/11371526.html