codeforces C. Color Stripe

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.

Input

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.

Output

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;
}
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值