寒假训练1.17训练赛D

匆匆过客 提交于 2020-01-22 03:33:09

题目
有一个长度为n(1<=n<=2*10^5)且仅包含着"R",“B”,"G"三种字母的字符串s。
你可以将任意一个字母修改成另外两个字母。
要求相邻两个字母不能相同,求最小的修改次数。
解题思路
如果有字符串中一段连续的B,例如BBBBB,那么可以看一下连续的B后面接着是哪一种字母(末尾没有,初始化加上一个),这样的话可以把第偶数位的B改成另一位字母。
例如
BBBBR可以改为BGBGR
BBBBBR可以改为BGBGBR
代码

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main()
{
   int len;
   string st;
   int ans=0;
   cin>>len;
   cin>>st;
   if (st[len-1]=='B') st=st+"G";
   else if (st[len-1]=='G') st=st+"B";
   else if (st[len-1]=='R') st=st+"B";
   char sym=st[0];
   int num=0;
   for (int i=0;i<=len;i++)
     if (st[i]==sym) num++;
     	else 
		 {
		   ans+=num/2;
		   num=1;
		   sym=st[i];
	     }
   cout<<ans<<endl;  		     
   sym=st[0];
   num=0;
   for (int i=0;i<=len;i++)
     {
     	if (st[i]==sym) num++;
     	else
     	{
     		char x;
     		     if (sym=='G' && st[i]=='B') x='R';
     		else if (sym=='G' && st[i]=='R') x='B';
     		else if (sym=='B' && st[i]=='G') x='R';
     		else if (sym=='B' && st[i]=='R') x='G';
     		else if (sym=='R' && st[i]=='B') x='G';
     		else if (sym=='R' && st[i]=='G') x='B';
     		string s="";
     		s=s+sym+x;
     		for (int j=1;j<=num/2;j++)
     		  cout<<s;
     		if (num%2==1) cout<<sym;
     		sym=st[i];
			num=1;  
     	}
     }
     
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!