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

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

题意:给一个长度为n的字符串。字符串只包含两种字母。S 和 G.只有一次交换任意两个位置的字符,求最长的连续的G的长度。

题解:求出每一段连续的G的起始位置,终止位置,和G的个数。如果对于两段之间 S 的个数为 1 的话那么就可以 把两段加起来。如果大于 1 那么长度就为前一段的G的个数 + 1 .然后 一次遍历即可

中间细节很多,不太好写。

代码如下:

#include
using namespace std;

const int maxn = 1e6+5;
struct node{
	int l;
	int r;
	int num;
}duan[maxn];
char a[maxn];
int x,y,n,d;

vector q;
int main(){
	scanf("%d",&n);
	scanf("%s",a+1);
	a[0] = 'S';
	a[n+1] = 'S';
	int cnt = 0 ;
	int pre= -1;
	int temp = 0;
	for(int i = 0 ; i <= n + 1  ; i ++){
		if(a[i] == 'G'){
			temp ++;
			
		}
		else{
			if(temp != 0){
				duan[cnt].num = temp;
				duan[cnt].r = i - 1;
				duan[cnt].l = i - temp;
				
				cnt++;
			}
			
			temp = 0;
		}
	
	}	

	if(temp){
		duan[cnt].num = temp;
		duan[cnt].r = n - 1;
		duan[cnt++].l = n - 1  - temp;
		
	}
//
//	for(int i = 0 ; i < cnt ; i ++){
//		cout << duan[i].l << " " << duan[i].r << " " << duan[i].num << endl;
//	}
	if(cnt == 1){
		cout << duan[0].num << endl;
		return 0;
	}
	if(cnt == 2){
		if(duan[0].r + 2 == duan[1].l){
			cout << duan[0].num + duan[1].num << endl;
		}
		else{
			cout << max(duan[0].num,duan[1].num) + 1 << endl;
		}
		return 0;
	}
	int maxx = 0;
	for(int i = 0 ; i < cnt  ; i ++){
		if(duan[i].r + 2 == duan[i+1].l){
		
			maxx = max(duan[i].num + duan[i+1].num + 1,maxx);
		}
		else{
			maxx = max(duan[i].num+1,maxx);
		}
	}
	cout << maxx << endl;
	
}

/*
11
SGGSGGGSGGS
5
GGSGG
*/

/*
21
SSSGGGSGGGSSSGGGGGGGG

*/

 

你可能感兴趣的:(CodeForces,思维,模拟)