D. Diverse Garland

题意:灯有三种颜色R,G,B。只要同一种颜色相邻就不可以。问最少需要换几次,可以使在一串灯中没有相邻灯的颜色相同。

思路:贪心思路:我们知道一个程序都是要子阶段,然后子阶段各个组合起来形成这个程序。那么对于每一个子阶段的贪心,就能形成整个程序的贪心。

贪心思路就是:只要出现相邻的相同a[i]==a[i+1], 然后,就选择一个a[i+1]!=a[i]&&a[i+1]!=a[i+2]的情况。注意:最后2个字母相同时,需要自己处理一下。

#include<iostream>
using namespace std;
const int maxn = 2e5 + 10;
int main(){
    int n;        char st[maxn];
    cin >> n;    cin >> st;
    if (n < 2){
        cout << 0 << endl;
        cout << st << endl;
    }
    else{
        int ans = 0;
        for (int i = 0; i < n - 1; ++i){
            if (st[i] == st[i + 1]&&i<n-2){
                if (st[i] == 'G'&&st[i + 2] == 'G'){ st[i + 1] = 'R'; }
                else if (st[i] == 'G'&&st[i + 2] == 'R'){ st[i + 1] = 'B'; }
                else if (st[i] == 'G'&&st[i + 2] == 'B'){ st[i + 1] = 'R'; }
                else if (st[i] == 'B'&&st[i + 2] == 'B'){ st[i + 1] = 'R'; }
                else if (st[i] == 'B'&&st[i + 2] == 'R'){ st[i + 1] = 'G'; }
                else if (st[i] == 'B'&&st[i + 2] == 'G'){ st[i + 1] = 'R'; }
                else if (st[i] == 'R'&&st[i + 2] == 'R'){ st[i + 1] = 'B'; }
                else if (st[i] == 'R'&&st[i + 2] == 'G'){ st[i + 1] = 'B'; }
                else if (st[i] == 'R'&&st[i + 2] == 'B'){ st[i + 1] = 'G'; }
                ans++;
            }
            else if (i == n - 2 && st[i] == st[i + 1]){
            //    cout << st[i] << st[i + 1] << endl;
                if (st[i] == 'B'){ st[i + 1] = 'G'; }
                else if (st[i] == 'G'){ st[i + 1] = 'R'; }
                else if (st[i] == 'R'){ st[i + 1] = 'G'; }
                ans++;
            }
        }
        cout << ans << endl;
        cout << st << endl;
    }
}

 

转载于:https://www.cnblogs.com/ALINGMAOMAO/p/10320090.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值