@codeforces1082/B(字符串中由相同字符组成的子字符串长度的处理,思维题)
B. Vova and Trophies
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Vova has won nn 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 n(2≤n≤10^5) — the number of trophies.
The second line contains nn characters, each of them is either G or S. If the ii-th character is G, then the ii-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.
Examples
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 0.
原题:http://codeforces.com/problemset/problem/1082/B
题解:
字符串中包含G和S字符,分别代表金银牌,要你计算出在只能允许交换一次字符的情况下找出最长的连续G字符串长度。
如样例1中可将第四个S与第九个G交换,得到的连续G字符串长度最长,长度为7。
我们可以遍历字符串直到遇到S把前面一段G的长度存起来,在遍历后面直到遇到下一个S的一段G的长度这个两端加1就是交换一次的长度把这个过渡长度存起来,遍历所有长度,过渡长度及时更新,如果最后这个过渡长度比总的G的个数要多,那么过渡长度更新为总和长的!
#include<stdio.h>
#include<iostream>
#define max(a,b) (a>b?a:b)
using namespace std;
int main()
{
int n,yiduan=0,zonghe=0,guodu=0,ans=0;
char t[100005];
scanf("%d",&n);
scanf("%s",&t);
for(int i=0;i<n;i++)
{
if(t[i]=='G')
{
yiduan++;
zonghe++;
}
else
{
guodu=yiduan;
yiduan=0;
}
ans=max(ans,yiduan+guodu+1);
}
if(ans>zonghe)
{
ans=zonghe;
}
printf("%d\n",ans);
}