Educational Codeforces Round 55:B. Vova and Trophies

B. Vova and Trophies

题目链接:https://codeforc.es/contest/1082/problem/B

题意:

给出一个“GS”串,有一次交换两个字母的机会,问最大的连续“G”串是多少。

题解:

在末尾后面放一个哨兵“S”,然后扫两遍,维护S左边和右边连续的“G”分别有多少个,然后求最大就可以了。

注意并不是所有的串都可以通过交换使长度变大这种情况,比如 “SGGGGS”,处理一下就好了。

代码如下:

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5;
char s[N];
int sum1[N],sum2[N];

int main(){
    int n;
    cin>>n;
    scanf("%s",s);
    int len = strlen(s),tot=0;
    s[len]='S';
    for(int i=0;i<=len;i++){
        if(s[i]=='G') tot++;
        else{
            sum1[i]=tot;
            tot=0;
        }
    }
    tot=0;
    for(int i=len;i>=0;i--){
        if(s[i]=='G') tot++;
        else{
            sum2[i]=tot;
            tot=0;
        }
    }
    int ans=0,cnt=0;
    for(int i=0;i<=len;i++){
        if(s[i]=='S') ans=max(ans,sum1[i]+sum2[i]);
        else cnt++;
    }
    if(ans!=cnt) ans++; //处理一下 
    cout<<ans;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/heyuhhh/p/10047909.html