Educational Codeforces Round 55 (Rated for Div. 2) B. Vova and Trophies(思维模拟)

 

题目链接:http://codeforces.com/contest/1082/problem/B

       题意是输入长度为n的字符串,字符串只包含'S','G',问最多只能交换一次其中的任意两个字符,求出最长的'G'子串长度。

       思路是首先我们先求出共有多少个'G',然后我们遍历字符串去寻找'S',找到后去计算'S'两边的'G'的长度,如果一个'S'两边的'G'的长度是小于Gcnt的,就说明当前的'G'的长度以外还存在'G',可以把其中的'S'替换掉,所以sum++,最后再特判一下只有一个'S'和没有'S'的情况就好了,方法不止这一种,看代码会更好理解一点。


AC代码:

#include <bits/stdc++.h>
using namespace std;
int n;
string str;

int main()
{
	scanf("%d",&n);
	cin>>str;
	int cnt = 0, Gcnt = 0, Scnt = 0, sum;
	for(int i=0;i<n;i++){
		if(str[i] == 'G') Gcnt ++;
	}
	for(int i=0;i<n;i++){
		if(str[i] == 'S'){
			Scnt ++;
			sum = 0;
			int l = i - 1, r = i + 1;
			for(int j=i-1;j>=0;j--){
				if(str[j] == 'G') sum ++;
				else break;
			}
			for(int j=i+1;j<n;j++){
				if(str[j] == 'G') sum ++;
				else break;
			}
			if(Gcnt > sum) sum ++;   // 判断能否把S替换成G
			cnt = max(cnt, sum);
		}
	}
	if(Scnt == 0) cnt = n;
	if(Scnt == 1) cnt = n - 1;
	printf("%d\n", cnt);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值