CodeForces 219C Color Stripe (贪心)

题意:

用前k个大写字母,替代原来字符串的大写字母,使得两两相邻的字母不一样。要求使用最少的替代次数。


思路:

因为是在dp专题里看到,所以一直想dp的做法,后来实在不知道应该怎么搞。

于是乎看了下别人的思路。

k > 2:直接模拟枚举下去。每个位置与两旁的字母比较,相同就改,做到不与左右相同即可。(证明不会= =,应该是贪心吧)

k = 2:只有两种情况,ABABA……,BABABA……哪种改动次数少选哪种。


code:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MAXN = 5*1e5+5;
const int INF = 0x3f3f3f3f;

int n, k;
char ch[MAXN];
char tt[MAXN];
void spdeal() {
    int len = strlen(ch);
    strcpy(tt, ch);
    int t = 0;
    int res = 0;
    for(int i = 0;i < len; i++) {
        if(ch[i] != t+'A') {
            ch[i] = t+'A';
            res ++;
        }
        t ^= 1;
    }
    int res2 = 0;
    t = 1;
    for(int i = 0;i < len; i++) {
        if(tt[i] != t+'A') {
            tt[i] = t+'A';
            res2++;
        }
        t ^= 1;
    }
    printf("%d\n", min(res, res2));
    if(res < res2)
        printf("%s\n", ch);
    else
        printf("%s\n", tt);
}
void solve() {
    if(k == 2) {
        spdeal();
        return;
    }
    int len = strlen(ch);
    int res = 0;
    for(int i = 1;i < len; i++) {
        if(i == len-1) {
            if(ch[i-1] == ch[i]) {
                for(int t = 0;t < k; t++)
                    if(t+'A' != ch[i-1]) {
                        res++;
                        ch[i] = t+'A';
                        break;
                    }
            }
        } else {
            if(ch[i-1]==ch[i]) {
                for(int t = 0;t < k; t++) {
                    char tmp = t+'A';
                    if(tmp != ch[i-1] && tmp != ch[i+1]) {
                        res++;
                        ch[i] = tmp;
                        break;
                    }
                }
            }
        }
    }
    printf("%d\n", res);
    printf("%s\n", ch);
}
                        
            
                
        

int main() {
    scanf("%d%d", &n, &k);
    scanf("%s", ch);
    solve();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值