Codeforces 219C 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.

Examples
Input
6 3
ABBACC
Output
2
ABCACA
Input
3 2
BBB
Output
1
BAB

题意:给出一个n个字符构成的字符串,只包含k种字符,问最少修改多少个字符能够得到一个相邻的字符没有相同的字符串。

思路:分两种情况,如果k>2正常贪心(i改变能使i-1和i+1同时满足条件),如果k=2分情况(ABAB或BABA)

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=500010;
char s[N];
int a[N];
int main()
{
    int n,k;
	cin>>n>>k;
		scanf("%s",s+1);
		int ans=0;
		for(int i=1;i<=n;i++)
			a[i]=s[i]-'A';
		int l=0,r=0;
		if(k==2)
		{
			for(int i=1;i<=n;i++)
			{
				if(i%2&&s[i]=='A'||(i%2==0&&s[i]=='B'))
					r++;
				if(i%2&&s[i]=='B'||(i%2==0&&s[i]=='A'))
					l++;
			}
			if(l<r)
			{
				cout<<l<<endl;
				for(int i=1;i<=n;i++)
				{
					if(i%2)
					cout<<'A';
					else
					cout<<'B';
				}
			}
			else
			{
				cout<<r<<endl;
				for(int i=1;i<=n;i++)
				{
					if(i%2)
					cout<<'B';
					else
					cout<<'A';
				}
			}
			cout<<endl;
		}
		else
		{
		    a[0]=-1;
		for(int i=1;i<=n;i++)
		{
			if(a[i]==a[i-1])
			{
				ans++;
				a[i]=(a[i]+1)%k;
				if(a[i]==a[i+1])
					a[i]=(a[i]+1)%k;
			}
		}
		cout<<ans<<endl;
		for(int i=1;i<=n;i++)
			cout<<char(a[i]+'A');
		cout<<endl;
		}
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值