Codeforces 1082B Vova and Trophies (思维题)

Codeforces 1082B Vova and Trophies (思维题)

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 nn (2≤n≤1052≤n≤105) — 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 44 and 1010. Thus he will obtain the sequence “GGGGGGGSGS”, the length of the longest subsegment of golden trophies is 77.

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

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

题目大意:

有一排奖牌,有金的,有银的,问最多交换一次,让最多的金牌连在一块,求出这个最长的连续金牌数

解题思路:

我们不要去想金牌,我们来想银牌
只要三个连续的银牌之间的奖牌数,就是交换后的金牌数
在这里插入图片描述
看这个图,这三个银牌之间 把中间的银牌换成金的 就是五块金牌了
我们记录一下每个银牌的位置,然后就找最大的区间就好了。
这是一般情况,然后会有些地方需要特判一下
1.全是金牌
直接输出就ok了
2.全是银牌
直接输出0
3.银牌数量等于1
这样我们只要把这个银牌移动到最左边就行,然后就有n-1块金牌联排了 输出n-1
4.银牌数量等于2
—a.这两块银牌有在最左边或者最右边的
在这里插入图片描述
ans=s[1]-s[0]+max(s[0]-1,n-s[1])-1
----b.这两块都在中间的时候
ans=s[1]-s[0]+max(s[0]-1,n-s[1]);

所以说 把这些特殊情况特判了 其他的按普通情况处理就行了

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn=1e5+10;
char a[maxn];
int s[maxn];
int sum_g=0;
int sum_s=0;
int n;
int main() 
{
	while(cin>>n)
	{
		memset(s,0,sizeof(s));
		sum_g=0;
		sum_s=0;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
			if(a[i]=='G')
				sum_g++;
			if(a[i]=='S')
			{
				s[sum_s]=i;
				sum_s++;
			}
		}
		if(sum_g==n)
		{
			cout<<n<<endl;
			continue;
		}
		if(sum_g<=2)
		{
			cout<<sum_g<<endl;
			continue;
		}
		if(sum_s==1)
		{
			cout<<n-1<<endl;
			continue;
		}
		if(sum_s==2)
		{
			int ans;
			if(s[0]==1||s[1]==n)
				ans=s[1]-s[0]+max(s[0]-1,n-s[1])-1;
			else
				ans=s[1]-s[0]+max(s[0]-1,n-s[1]);
			cout<<ans<<endl;
			continue;
		}
	
		int max_num=max(min(s[1]-1,sum_g),min(n-s[sum_s-2],sum_g));
		for(int i=0;i<sum_s-2;i++)
		{
			max_num=max(max_num,min(s[i+2]-s[i]-1,sum_g));
		}
		cout<<max_num<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43179892/article/details/85110598
今日推荐