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

Question: Given a string consisting of n characters, which only contains k kinds of characters, ask how many characters can be modified at least to get an adjacent character string that does not have the same string.

Idea: There are two situations, if k>2 is normal greedy (change of i can make i-1 and i+1 satisfy the conditions at the same time), if k=2 points (ABAB or BABA)

AC code:

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


Guess you like

Origin blog.csdn.net/weixin_43244265/article/details/104458597