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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章