Codeforces Round #135 (Div. 2) C. Color Stripe(字符串dp)

37 篇文章 0 订阅
7 篇文章 0 订阅



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.

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

题意:输入n和k,n代表大写英语单词(即颜色的个数)的个数,k代表颜色的种类,求经过多少步使得每两个相邻的颜色不同,输出步数和变化后的字符串。

其实是一个字符串dp题

  

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 500005
char s[N];
int main() {
    int n,k,ans,i,j,a,b,c;

    while(~scanf("%d%d",&n,&k)) {
        scanf("%s",s);
        if(k==2) 
        {
            a=b=c=0;
            for(i=0;i<n;i++) 
            {
                if((i%2==0&&s[i]=='B')||(i%2==1&&s[i]=='A'))    a++;
                else 
                  if((i%2==0&&s[i]=='A')||(i%2==1&&s[i]=='B'))  b++;   
            }
            c=a<b?a:b;
            cout<<min(a,b)<<endl;
            for(i=0;i<n;i++) {
                if(c==a) 
                printf("%c",!(i&1)?'A':'B'); 
                else 
                printf("%c",(i&1)?'A':'B');    
            }
        } 
        else {
            int ans=0,l=1;
            for(i=1;i<n;i++)
             {
                if(s[i-1]==s[i]) l++;
                else
                 { ans+=l/2;
                    l=1;    }
            }
            ans += (l/2);
            printf("%d\n",ans);
            printf("%c",s[0]);
            for(i = 1 ; i < n ; i ++) 
            {
                if(s[i-1]!=s[i]) 
                   printf("%c",s[i]);
                else 
                {
                    for(j=0;j<k;j++) 
                    {
                        if(s[i]!='A'+j&&s[i+1]!='A'+j) 
                        {
                            printf("%c",'A'+j);
                            s[i]='A'+j;
                            break;   }    
                       }
                   } 
            }   }    
        printf("\n");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值