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.
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.
Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
6 3 ABBACC
2 ABCACA
3 2 BBB
1 BAB
題意:給一個字符串,只有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;
}