time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You have a garland consisting of nn lamps. Each lamp is colored red, green or blue. The color of the ii-th lamp is sisi ('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 11) have distinct colors.
In other words, if the obtained garland is tt then for each ii from 11 to n−1n−1 the condition ti≠ti+1ti≠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 nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of lamps.
The second line of the input contains the string ss consisting of nn characters 'R', 'G' and 'B' — colors of lamps in the garland.
Output
In the first line of the output print one integer rr — 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 tt of length nn — a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
input
Copy
9
RBGRRBRGG
output
Copy
2
RBGRGBRGR
input
Copy
8
BBBGBRRR
output
Copy
2
BRBGBRGR
input
Copy
13
BBRRRRGGGGGRR
output
Copy
6
BGRBRBGBGBGRG
题意:
给出一个有RGB组成的字符串,问最少需要多少步可以变成相邻两字符不同的字符串。
解题思路:
dp[i][x]表示由前i个字母组成的子字符串且第i个字符为x的字符串需要改的最少步骤。递推公式dp[i][x] = min(dp[i][x],dp[i-1][y]+(a[i]!=x))a[i]!=x如果返回1不成立返回0
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
const int maxn=2e5+2;
using namespace std;
char G[] = {'R','G','B'};
int dp[maxn][3],f[maxn][3];// dp[i][x] 满足前i个数第i个正好是x的最小的改变数量
char result[maxn];
int a[maxn];
string s;
int main()
{
int t;
cin>>t;
cin>>s;
for(int i = 1;i <= t;i++){
if(s[i-1] == 'R')
a[i] = 0;
else if(s[i-1] == 'G')
a[i] = 1;
else if(s[i-1] == 'B')
a[i] = 2;
}
memset(dp,0x3f3f3f,sizeof(dp));
dp[1][0] = (a[1]!=0);
dp[1][1] = (a[1]!=1);
dp[1][2] = (a[1]!=2);
for(int i = 2;i <= t;i++)
{
for(int x=0;x<3;x++)
{
for(int y=0;y<3;y++)
{
if(x==y) continue;
if(dp[i][x] > dp[i-1][y]+(a[i]!=x))
{
dp[i][x]=dp[i-1][y]+(a[i]!=x);
f[i][x] = y; //记录前一种状态最优情况,即第i-1位置的字符
}
}
}
}
int e;
int ans = 0x3f3f3f;
for(int i = 0;i<3;i++){//找最优情况
if(ans >dp[t][i]){
ans = dp[t][i];
e = i;//存最后一个字母
}
}
cout<<ans<<endl;
int l = t;
result[l--] = G[e];//从后往前,根据前存储的前一个最优情况,得到最优序列
for(int i = t;i>=2;i--){
result[l--] = G[f[i][e]];
e = f[i][e];
}
for(int i = 1;i<=t;i++)
cout<<result[i];
}