Codeforces 219C Color Stripe(思维+字符串)

题目链接:http://codeforces.com/problemset/problem/219/C

题目大意:

给出一个字符串,只包含k种字符,问最少修改多少个字符(不增长新的种类)能够得到一个新的字符串,这个字符串满足相邻的字符没有相同的。
解题思路:
k=2时:
字符串只能是ABABAB.....或者BABABA.....两种都枚举一下即可。
k>2时:
若有奇数个相同,如AAAAA则可变为ABABA的形式即可。
若有偶数个相同,如AAAAAA则变为ABABAC的形式即可,C保证与后一个不同。

代码

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<string>
 5 #define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
 6 using namespace std;
 7 const int N=5e5+5;
 8 
 9 int dp[N][28];
10 
11 int main(){
12     FAST_IO;
13     int n,k;
14     string str,s1,s2;
15     cin>>n>>k;
16     cin>>str;
17     s1=str,s2=str;
18     int ans=0,sum=0;
19     if(k==2){
20         for(int i=0;i<n;i++){
21             if(i%2&&s1[i]!='A')
22                 sum++,s1[i]='A';
23             else if(i%2==0&&s1[i]!='B')
24                 sum++,s1[i]='B';
25         }
26         ans=sum;
27         sum=0;
28         for(int i=0;i<n;i++){
29             if(i%2&&s2[i]!='B')
30                 sum++,s2[i]='B';
31             else if(i%2==0&&s2[i]!='A')
32                 sum++,s2[i]='A';
33         }
34         ans=min(ans,sum);
35         cout<<ans<<endl;
36         if(ans==sum)
37             cout<<s2<<endl;
38         else
39             cout<<s1<<endl;
40     }
41     else{
42         for(int i=1;i<n;i++){
43             if(str[i]==str[i-1]){
44                 ans++;
45                 for(int j=0;j<k;j++){
46                     if(i!=n-1){
47                         if('A'+j!=str[i-1]&&'A'+j!=str[i+1]){
48                             str[i]='A'+j;
49                             break;
50                         }
51                     }
52                     else{
53                         if('A'+j!=str[i-1]){
54                             str[i]='A'+j;
55                             break;
56                         }
57                     }
58                 }
59             }
60         }
61         cout<<ans<<endl;
62         cout<<str<<endl;
63     }
64     return 0;
65 }

 

posted @ 2018-11-01 20:19  Yeader  阅读(212)  评论(0编辑  收藏  举报