zoukankan      html  css  js  c++  java
  • 贪心 Codeforces Round #135 (Div. 2) C. Color Stripe

    题目传送门

     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
    ", 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
    ", ans);   s[len+1] = '';
    56             printf ("%s
    ", s + 1);
    57         }
    58     }
    59 
    60     return 0;
    61 }
    编译人生,运行世界!
  • 相关阅读:
    MySql常用数据操作
    使用requests+BeaBeautiful Soup爬取妹子图图片
    抓取猫眼电影排行
    Exec执行拼接字符串时遇到的问题及Sql执行函数时需要注意的事项
    c#小知识点
    MVVM 与 sql
    Dictionary
    sql表信息查询
    XAML特殊字符
    编程细节
  • 原文地址:https://www.cnblogs.com/Running-Time/p/4659010.html
Copyright © 2011-2022 走看看