B. Diverse Garland

GDUT 2020寒假训练 排位赛四 B

原题链接

题目

原题截图
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is si (‘R’, ‘G’ and ‘B’ — colors of lamps in the garland).

You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.

A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.

In other words, if the obtained garland is t then for each i from 1 to n−1 the condition ti≠ti+1 should be satisfied.

Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

Input
The first line of the input contains one integer n (1≤n≤2⋅105) — the number of lamps.

The second line of the input contains the string s consisting of n characters ‘R’, ‘G’ and ‘B’ — colors of lamps in the garland.

Output
In the first line of the output print one integer r — the minimum number of recolors needed to obtain a diverse garland from the given one.

In the second line of the output print one string t of length n — a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

样例

input
9
RBGRRBRGG
output
2
RBGRGBRGR

input
8
BBBGBRRR
output
2
BRBGBRGR

input
13
BBRRRRGGGGGRR
output
6
BGRBRBGBGBGRG

题目大意

给出一串仅含有‘R’‘G’‘B’的字符串,要想让字符串中相邻两个字符都不相同,求出最少要改变的字符个数,输出其中一种改变后的结果

思路

模拟
遍历字符串,检查当前位的字符是否与前一个字符相同,若相同,就在RGB这三个字符中挑一个字符,满足这个字符不与前一个还有后一个字符相同。

代码

#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
string str;
char change[6]={'R','G','B','R','G','B'};
int main()
{
	int n;
	cin>>n>>str;
	int ans=0;
	for(int i=1;i<n;i++)
	{
		if(str[i]==str[i-1])
		{
			for(int j=0;j<3;j++)
			{
				if(change[j]!=str[i-1]&&change[j]!=str[i+1])
				{
					str[i]=change[j];
					break;
				}
			}
			ans++;
		}
	}
	cout<<ans<<endl<<str<<endl;
	
	return 0;
}

发布了21 篇原创文章 · 获赞 1 · 访问量 405

猜你喜欢

转载自blog.csdn.net/xcy2001/article/details/104634343