codeforces 219C Color Stripe(贪心)

来源:互联网 发布:广州淘宝模特拍摄 编辑:程序博客网 时间:2024/05/02 02:15

题目链接

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 3ABBACC
output
2ABCACA
input
3 2BBB
output
1BAB

题意:给一个字符串,只有K个字符,从‘A’开始。问最少修改多少个字符(字符只能是从A开始的K个),可以使字符串相邻的字符都不相同。

题解:贪心。如果K大于2,直接修改偶数位上的字符即可。如果k==2,那么只有两种清楚ABAB....,BABAB.....,判断那种情况更优即可。

代码如下:(比赛时对于k==2的情况是用dp做的)

#include<stdio.h>#include<iostream>#include<algorithm>#include<math.h>#include<queue>#include<stack>#include<set>#include<map>#include<vector>#include<string.h>#include<string>#include<stdlib.h>typedef __int64 LL;typedef unsigned __int64 LLU;const int nn=510000;const int inf=0x3fffffff;const LL mod=1000000007;const LL inf64=(LL)inf*inf;const double pi=acos(-1.0);const double eps=1e-8;using namespace std;int n,k;char s[nn];int dp[nn][2];int pre[nn][2];void solve1(){    int i,ans=0;    int ix;    for(i=1;i<n;i++)    {        ix=s[i]-'A';        if(s[i]==s[i-1])        {            ans++;            ix=(s[i]-'A'+1)%k;            if(i<n-1&&ix==s[i+1]-'A')            {                ix=(ix+1)%k;            }        }        s[i]=ix+'A';    }    printf("%d\n",ans);    printf("%s\n",s);}stack<int>sta;void solve2(){    int i,j;    for(i=0;i<k;i++)    {        if(s[0]-'A'==i)        {            dp[0][i]=0;        }        else            dp[0][i]=1;    }    for(i=1;i<n;i++)    {        for(j=0;j<=k;j++)        {            dp[i][j]=dp[i-1][j^1]+((s[i]-'A')==j?0:1);        }    }    if(dp[n-1][0]<dp[n-1][1])    {        printf("%d\n",dp[n-1][0]);        int ix=n-1,fc=0;        while(ix>=0)        {            sta.push(fc+'A');            ix--;            fc=fc^1;        }    }    else    {        printf("%d\n",dp[n-1][1]);        int ix=n-1,fc=1;        while(ix>=0)        {            sta.push(fc+'A');            ix--;            fc=fc^1;        }    }    while(sta.size())    {        printf("%c",sta.top());        sta.pop();    }    puts("");}int main(){    int i;    while(scanf("%d%d",&n,&k)!=EOF)    {        scanf("%s",s);        if(k>2)        {            solve1();        }        else            solve2();    }    return 0;}


0 0
原创粉丝点击