题意: 和上题差不多, 一个包含RGB三种颜色的序列, 求改动颜色的最小次数, 使得所有相邻的元素都不相同.
这道题贪心+枚举就可以解了, 把所有可能储存的颜色组合以及需要改成的组合存起来, 最后遍历一下就好了, 由于边界问题, 特判一下最后两格, 有个小细节一直让我出错, 记得把所有的可能都写上.
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const LL maxn = 1e5+10;
int main()
{
int n;
string s, tar[][2] = {{"RB","GB"}, {"RG","BG"}, {"BR","GR"}, {"BG","RG"}, {"GB","RB"}, {"GR","BR"}, {"BB","RB"}, {"BB","GB"}, {"GG","BG"}, {"GG","RG"}, {"RR","GR"}, {"RR","BR"}};
cin >> n >> s;
int ans = 0;
for(int i = 0; i < n-2; i++){
//cout << s.substr(i+1, 2) << " ";
if(s[i] == s[i+1])
for(int j = 0; j < 12; j++)
if(s.substr(i+1, 2)==tar[j][0]){
s.replace(i+1, 2, tar[j][1]);
i++, ans++;
break;
}
}
if(s[n-2]==s[n-1]){
for(int j = 0; j < 12; j++)
if(s.substr(n-2, 2)==tar[j][0] && s[n-3] != tar[j][1][0]){
//cout << s[n-3] <<" " << tar[j][1][0] << endl;
s.replace(n-2, 2, tar[j][1]);
ans++;
break;
}
}
cout << ans << endl << s << endl;
return 0;
}