gavanwanggw

导航

CF 234 C Weather(粗暴方法)

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




#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)

#define bug printf("hihi\n")

#define eps 1e-8
typedef __int64 ll;
#define INF 0x3f3f3f3f

using namespace std;

int dp[500001][27];
int pre[500001][27];
int n,k;
char c[500005];

void show(int pos,int i)
{
    vector<char>ans;
    ans.clear();
    while(pos!=-1)
    {
       ans.push_back(i+'A');
        i=pre[pos][i];
        pos--;
    }
    for(i=ans.size()-1;i>=0;i--)
        printf("%c",ans[i]);
    printf("\n");
}

int main()
{
    int i,j;
    int kk;
   // cout<<500000*26*26<<endl;
    while(~scanf("%d%d",&n,&kk))
    {
        memset(dp,INF,sizeof(dp));
        scanf("%s",c);
        for(i=0;i<26;i++)
            dp[0][i]=pre[0][i]=1;
        dp[0][c[0]-'A']=0;
        for(i=1;i<n;i++)   //500000*26*26的复杂度能够在2秒内跑完预计仅仅有CF的机子敢试试了
            for(j=0;j<kk;j++)
               for(k=0;k<kk;k++)
               {
                   if(j==k) continue;
                   int t=1;
                   if(k==c[i]-'A') t=0;
                   if(dp[i-1][j]+t<dp[i][k])
                   {
                       dp[i][k]=dp[i-1][j]+t;
                       pre[i][k]=j;
                   }
               }
        i=0;
        for(j=1;j<kk;j++)
            if(dp[n-1][j]<dp[n-1][i]) i=j;
        printf("%d\n",dp[n-1][i]);
        show(n-1,i);
    }
    return 0;
}





posted on 2017-07-18 10:21  gavanwanggw  阅读(319)  评论(0编辑  收藏  举报