A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
当k为2时特判一下,要么ABAB...要么BABA...,当k等于三是,若出现两个连续的相同的,改变后面一个,然让其与前后都不一样,这样的贪心是最优的.
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <queue>
using namespace std;
char s[500010];
int main() {
int k, i, j, n;
scanf("%d%d", &n, &k);
getchar();
scanf("%s", s);
int length=strlen(s);
if(k==2){
int cnt1=0, cnt2=0;
for(i=0; i<strlen(s); i++){
if((s[i]-'A')==0){
if(i%2!=0)
cnt1++;
}
else{
if(i%2!=1){cnt1++;}
}
}
for(i=0; i<=length-1; i++){
if((s[i]-'A')==0){
if(i%2==0)cnt2++;
}
else{
if(i%2==1){cnt2++;}
}
}
if(cnt1<cnt2){
printf("%d\n", cnt1);
for(i=0; i<=length-1; i++){
cout<<(char)(i%2+'A');
}
}
else{
printf("%d\n", cnt2);
for(i=0; i<=length-1; i++){
cout<<(char)('B'-i%2);
}
}
}
else{
int ans=0;
s[length]='0';
for(i=1; i<=length-1; i++){
if(s[i]==s[i-1])
for(j='A'; j<='A'+k-1; j++){
if(j!=s[i]&&j!=s[i+1]){
ans++;
s[i]=j;
break;
}
}
}
printf("%d\n", ans);
for(j=0; j<=length-1; j++){
printf("%c", s[j]);
}
}
return 0;
}