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.
6 3 ABBACC
2 ABCACA
3 2 BBB
1 BAB
题意:输入n和k,n代表大写英语单词(即颜色的个数)的个数,k代表颜色的种类,求经过多少步使得每两个相邻的颜色不同,输出步数和变化后的字符串。
其实是一个字符串dp题
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 500005
char s[N];
int main() {
int n,k,ans,i,j,a,b,c;
while(~scanf("%d%d",&n,&k)) {
scanf("%s",s);
if(k==2)
{
a=b=c=0;
for(i=0;i<n;i++)
{
if((i%2==0&&s[i]=='B')||(i%2==1&&s[i]=='A')) a++;
else
if((i%2==0&&s[i]=='A')||(i%2==1&&s[i]=='B')) b++;
}
c=a<b?a:b;
cout<<min(a,b)<<endl;
for(i=0;i<n;i++) {
if(c==a)
printf("%c",!(i&1)?'A':'B');
else
printf("%c",(i&1)?'A':'B');
}
}
else {
int ans=0,l=1;
for(i=1;i<n;i++)
{
if(s[i-1]==s[i]) l++;
else
{ ans+=l/2;
l=1; }
}
ans += (l/2);
printf("%d\n",ans);
printf("%c",s[0]);
for(i = 1 ; i < n ; i ++)
{
if(s[i-1]!=s[i])
printf("%c",s[i]);
else
{
for(j=0;j<k;j++)
{
if(s[i]!='A'+j&&s[i+1]!='A'+j)
{
printf("%c",'A'+j);
s[i]='A'+j;
break; }
}
}
} }
printf("\n");
}
}