Educational Codeforces Round 55 (Rated for Div. 2) B
程序员文章站
2024-03-19 09:12:40
...
http://codeforces.com/contest/1082/problem/B
题意:给你长为n的字符串,可以置换G和S至多一次,要求最长的全为G的子串
分析:维护字母G数目的前缀和pre[i]和后缀和post[i],遇到S变为0,重新开始计数。
然后遍历该串,如果为G,可能的答案就是pre[i]+post[i+1]
如果为S,分两种情况,1、如果pre[i-1]+post[i+1]=所有的G,则无多余的G来替换S,ans=pre[i-1]+post[i+1]
2、如果pre[i-1]+post[i+1]<G说明还有多余的G来替换S,则ans=pre[i-1]+post[i+1]+1;
AC code:
#include<bits/stdc++.h>
using namespace std;
string s;
int pre[100002],post[100002];
int main()
{
int n;
cin>>n>>s;
s=" "+s;
int G=0;
for(int i=1;i<=n;i++)
G+=s[i]=='G';
for(int i=1;i<=n;i++)///G的数目前缀和
if(s[i]=='G') pre[i]=pre[i-1]+1;
else pre[i]=0;
for(int i=n;i>=1;--i)///G的数目的后缀和
if(s[i]=='G') post[i]=post[i+1]+1;
else post[i]=0;
int ans=0;
for(int i=1;i<=n;i++)
{
if(s[i]=='G')
ans=max(ans,pre[i]+post[i+1]);///如果当前字母为G,则为第i个字母G的前缀和+第i+1个字母G的后缀和
else
{
if(pre[i-1]+post[i+1]==G) ans=G;///如果当前字母为S,i-1的前缀和和i+1的后缀和刚好等于所有的G,
///说明无多余的G来替换该S,则可将前缀中最前面的G或后缀中最后面的G替换S
else ans=max(ans,pre[i-1]+post[i+1]+1);///由多余的G替换S则替换
}
}
cout<<ans<<endl;
return 0;
}
推荐阅读
-
Educational Codeforces Round 55 (Rated for Div. 2) B
-
Educational Codeforces Round 60 (Rated for Div. 2) D. Magic Gems 矩阵优化
-
【Educational Codeforces Round 53 (Rated for Div. 2)】
-
Educational Codeforces Round 42 (Rated for Div. 2) E. Byteland, Berland and Disputed Cities
-
Educational Codeforces Round 53 (Rated for Div. 2)
-
Educational Codeforces Round 53 (Rated for Div. 2)D(模拟)
-
Educational Codeforces Round 53 (Rated for Div. 2) D - Berland Fair
-
Educational Codeforces Round 53 (Rated for Div. 2)
-
Educational Codeforces Round 53 (Rated for Div. 2)D. Berland Fair
-
【 Educational Codeforces Round 53 (Rated for Div. 2) D. Berland Fair】思维题