1. 程式人生 > >CF1082B Vova and Trophies(模擬)

CF1082B Vova and Trophies(模擬)

Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.

The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.

Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.
 

Input

The first line contains one integer nn (2≤n≤105) — the number of trophies.

The second line contains n characters, each of them is either G or S. If the i-th character is G, then the i-th trophy is a golden one, otherwise it's a silver trophy.
 

Output

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.
 

input

10
GGGSGGGSGG
output
7

input
4
GGGG
output
4


input
3
SSS


output
0
 

Note

In the first example Vova has to swap trophies with indices 4 and 10. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is 7.

In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is 4.

In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than 

題意:你現在有 nn 枚獎牌,每枚獎牌為金牌或銀牌。這些獎牌現在按順序排成一排。現在你可以調換任意一對獎牌的位置,求金牌最長連續段。注意只能調換一對,但是這兩個獎牌可以位置不相鄰

思路:

建立一個結構體,儲存下這個字串中 連續G串的G的數目,起始位置和結束位置

然後就是分類討論:

  1. 兩個相鄰G串中間隔了一個字元S,且除了這兩個串以外還有別的G可以用來替換這個S ,則maxx=max(maxx,兩個字串長度相加再+1)
  2. 兩個相鄰G串中間隔了一個S,但是並沒有剩餘的G替換這個S了,也就是說只能從某一個串的一端拿下一個G換過來,則maxx=max(maxx,兩個字串長度相加)
  3. 兩個相鄰串中間隔的大於1,那麼只能把某一個字串的一個G替換一個S,使另一個串的長度+1,則則maxx=max(maxx,max(字串a+1,字串b+1);

AC程式碼:

#include<iostream>
#include<cstring>
#define MAX 100005
using namespace std;
int sum=0;  //儲存總的G的數量 
struct node{
	int num;//g的數量
	int st;
	int end;//起始和終止位置 
}e[MAX];
int main()
{
	int n,i;
	int cnt=0,maxx=0;
	char s[MAX];
	scanf("%d",&n);
	scanf("%s",s);
	for(i=0;i<strlen(s);)
	{
		while(s[i]=='G')
		{
			sum++;//全域性變數 
			e[cnt].num++;
			i++;
		}
		if(e[cnt].num>0)
		{
			e[cnt].end=i-1;
			e[cnt].st=e[cnt].end-e[cnt].num+1;
			cnt++;
		}
		else 
		{
			i++;
		}
	}
	if(cnt==1)
	{
		cout<<e[cnt-1].num<<endl;
		return 0;
	}
	if(cnt==0)
	{
		cout<<"0"<<endl;
		
		return 0;
	}
	
	for(i=0;i<cnt-1;i++)
	{
		if(e[i+1].st-e[i].end==2)
		{
			if(sum>e[i+1].num+e[i].num)
			{
				maxx=max(maxx,e[i+1].num+e[i].num+1);
			}
			else maxx=max(maxx,e[i+1].num+e[i].num);
			
		}
		else maxx=max(maxx,max(e[i].num+1,e[i+1].num+1));
	//	cout<<e[i].st<<" "<<e[i].end<<endl;	
	}
	cout<<maxx<<endl;
	return 0;
}