B. Vova and Trophies
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 n (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.
Examples
inputCopy
10
GGGSGGGSGG
outputCopy
7
inputCopy
4
GGGG
outputCopy
4
inputCopy
3
SSS
outputCopy
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.
题意:
思路:
标程写的挺好的,推荐一下吧。
细节见代码:
#include <bits/stdc++.h>
using namespace std;
int n;
string s;
int main() {
cin >> n >> s;
vector <int> l(n), r(n);
for(int i = 0; i < n; ++i){
if(s[i] == 'G'){
l[i] = 1;
if(i > 0) l[i] += l[i - 1];
}
}
for(int i = n - 1; i >= 0; --i){
if(s[i] == 'G'){
r[i] = 1;
if(i + 1 < n) r[i] += r[i + 1];
}
}
int res = 0;
int cntG = 0;
for(int i = 0; i < n; ++i)
cntG += s[i] == 'G';
for(int i = 0; i < n; ++i){
if(s[i] == 'G') continue;
int nres = 1;
if(i > 0) nres += l[i - 1];
if(i + 1 < n) nres += r[i + 1];
res = max(res, nres);
}
res = min(res, cntG);
if(cntG == n) res = cntG;
cout << res << endl;
return 0;
}