题意:灯有三种颜色R,G,B。只要同一种颜色相邻就不可以。问最少需要换几次,可以使在一串灯中没有相邻灯的颜色相同。
思路:贪心思路:我们知道一个程序都是要子阶段,然后子阶段各个组合起来形成这个程序。那么对于每一个子阶段的贪心,就能形成整个程序的贪心。
贪心思路就是:只要出现相邻的相同a[i]==a[i+1], 然后,就选择一个a[i+1]!=a[i]&&a[i+1]!=a[i+2]的情况。注意:最后2个字母相同时,需要自己处理一下。
#include<iostream>
using namespace std;
const int maxn = 2e5 + ;
int main(){
int n; char st[maxn];
cin >> n; cin >> st;
if (n < ){
cout << << endl;
cout << st << endl;
}
else{
int ans = ;
for (int i = ; i < n - ; ++i){
if (st[i] == st[i + ]&&i<n-){
if (st[i] == 'G'&&st[i + ] == 'G'){ st[i + ] = 'R'; }
else if (st[i] == 'G'&&st[i + ] == 'R'){ st[i + ] = 'B'; }
else if (st[i] == 'G'&&st[i + ] == 'B'){ st[i + ] = 'R'; }
else if (st[i] == 'B'&&st[i + ] == 'B'){ st[i + ] = 'R'; }
else if (st[i] == 'B'&&st[i + ] == 'R'){ st[i + ] = 'G'; }
else if (st[i] == 'B'&&st[i + ] == 'G'){ st[i + ] = 'R'; }
else if (st[i] == 'R'&&st[i + ] == 'R'){ st[i + ] = 'B'; }
else if (st[i] == 'R'&&st[i + ] == 'G'){ st[i + ] = 'B'; }
else if (st[i] == 'R'&&st[i + ] == 'B'){ st[i + ] = 'G'; }
ans++;
}
else if (i == n - && st[i] == st[i + ]){
// cout << st[i] << st[i + 1] << endl;
if (st[i] == 'B'){ st[i + ] = 'G'; }
else if (st[i] == 'G'){ st[i + ] = 'R'; }
else if (st[i] == 'R'){ st[i + ] = 'G'; }
ans++;
}
}
cout << ans << endl;
cout << st << endl;
}
}