1 /* 2 贪心:当m == 2时,结果肯定是ABABAB或BABABA,取最小改变量;当m > 2时,当与前一个相等时, 改变一个字母 3 同时不和下一个相等就是最优的解法 4 */ 5 #include <cstdio> 6 #include <cstring> 7 #include <algorithm> 8 using namespace std; 9 10 const int MAXN = 5e5 + 10; 11 const int INF = 0x3f3f3f3f; 12 char s[MAXN]; 13 14 int main(void) { //Codeforces Round #135 (Div. 2) C. Color Stripe 15 //freopen ("C.in", "r", stdin); 16 17 int n, m; 18 while (scanf ("%d%d", &n, &m) == 2) { 19 scanf ("%s", s + 1); int len = strlen (s + 1); 20 21 if (m == 2) { 22 int c1 = 0, c2 = 0; 23 for (int i=1; i<=len; ++i) { 24 if (i & 1) { 25 if (s[i] == ‘A‘) c2++; 26 else c1++; 27 } 28 else { 29 if (s[i] == ‘A‘) c1++; 30 else c2++; 31 } 32 } 33 34 printf ("%d\n", min (c1, c2)); 35 for (int i=1; i<=len; ++i) { 36 if (i & 1) printf ("%c", (c1 < c2) ? ‘A‘ : ‘B‘); 37 else printf ("%c", (c1 < c2) ? ‘B‘ : ‘A‘); 38 } 39 puts (""); 40 } 41 else { 42 int ans = 0; s[len+1] = s[0] = ‘@‘; 43 for (int i=2; i<=len; ++i) { 44 if (s[i] == s[i-1]) { 45 ans++; 46 for (int j=1; j<=m; ++j) { 47 char ch = ‘A‘ + j - 1; 48 if (s[i] == ch || s[i+1] == ch) continue; 49 else { 50 s[i] = ch; break; 51 } 52 } 53 } 54 } 55 printf ("%d\n", ans); s[len+1] = ‘\0‘; 56 printf ("%s\n", s + 1); 57 } 58 } 59 60 return 0; 61 }
时间: 2024-10-10 10:32:18