Codeforces Round #135 (Div. 2)-C. Color Stripe

原题链接

C. Color Stripe
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
6 3
ABBACC
output
2
ABCACA
input
3 2
BBB
output
1
BAB

1.如果n == 1则不需要改动。

2.如果k == 2 && n > 1则比较将原字符串改为ABABABA..和BABABAB...的代价哪个小

3.如果k > 2 && n > 1从下标1开始遍历整个字符串str, 若str[i] == str[i-1]则改动str[i]这个字符使之不等于str[i-1]和str[i+1]

#include <bits/stdc++.h>
#define maxn 500005
using namespace std;
typedef long long ll;

char str[maxn];
char p[26];
int main(){
	
	//freopen("in.txt", "r", stdin);
	for(int i = 0; i < 26; i++)
	 p[i] = 'A' + i;
	int n, k;
	
	scanf("%d%d%s", &n, &k, str);
	int len = strlen(str);
	if(n == 1){
		puts("0");
		puts(str);
	}
	else if(k == 2){
		
		int k1 = 0, k2 = 0, d1 = 0, d2 = 1;
		for(int i = 0; i < len; i++){
			if(str[i] != p[d1]){
				k1++;
			}
			if(str[i] != p[d2]){
				k2++;
			}
			d1 ^= 1;
			d2 ^= 1;
		}
		if(k1 < k2){
			d1 = 0;
			for(int i = 0; str[i]; i++, d1 ^= 1)
			 str[i] = p[d1];
			printf("%d\n", k1);
			puts(str);
		}
		else{
			d2 = 1;
			for(int i = 0; str[i]; i++, d2 ^= 1)
			  str[i] = p[d2];
			printf("%d\n", k2);
			puts(str);
		}
	}
	else{
		int ans = 0;
		for(int i = 1; i < len; i++){
			if(str[i] == str[i-1]){
				for(int j = 0; j < k; j++){
					if(p[j] != str[i-1]){
						if(i < len-1){
							if(p[j] != str[i+1]){
								str[i] = p[j];
								ans++;
								break;
							} 
						}
						else{
						 str[i] = p[j];
						 ans++;
						 break;
					    }
					}
				}
			}
		}
		printf("%d\n", ans);
		puts(str);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值