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 nuppercase 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.

Sample test(s)
input
6 3
ABBACC
output
2
ABCACA
input
3 2
BBB
output
1
BAB

题意:给你一个涨肚为n的有大写字母组成的串(每个串有1到k颜色组成),每个字母代表一种颜色,A代表1,依次类推,给你1到k的颜色让你给串改变      颜色,使相邻字符颜色不同问你最少的染色步骤。
思路:对于K>=3的情况,只需判断当前字符是否与前一个字符相同,不同就染色一次,并且染成与前后不同的颜色;对于k==2的情况最后染色完可能为
     两种情况ABABA,BABAB;那么只需判断染成那种情况步骤较少即可
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 5000005

char s[N],s1[N],s2[N];
int main()
{
    int n,k,i;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        memset(s,0,sizeof(s));
        memset(s1,0,sizeof(s1));
        memset(s2,0,sizeof(s2));
        scanf("%s",s);
        int ans=0;
        if(k>=3)
        {
            for(i=1;i<n;i++)
            {
                if(s[i]==s[i-1])
                {
                    ans++;
                    if(s[i-1]!='A'&&s[i+1]!='A')
                    s[i]='A';
                    else if(s[i-1]!='B'&&s[i+1]!='B')
                    s[i]='B';
                    else if(s[i-1]!='C'&&s[i+1]!='C')
                    s[i]='C';
                }
            }
            printf("%d\n",ans);
            puts(s);
        }
        else
        {
            s1[0]='A';
            s2[0]='B';
            for(i=1;i<n;i++)
            {
                if(s1[i-1]=='A')
                    s1[i]='B';
                else if(s1[i-1]=='B')
                    s1[i]='A';
                if(s2[i-1]=='A')
                    s2[i]='B';
                else if(s2[i-1]=='B')
                    s2[i]='A';
            }
            int ans1=0,ans2=0;
            for(i=0;i<n;i++)
            {
                if(s[i]!=s1[i])
                    ans1++;
                if(s[i]!=s2[i])
                    ans2++;
            }
            ans=min(ans1,ans2);
            printf("%d\n",ans);
            if(ans==ans1)
                puts(s1);
            else
                puts(s2);
        }
    }
    return 0;
}

 

发布了34 篇原创文章 · 获赞 0 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章