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;
    }
}
复制代码

 

作者:ALINGMAOMAO

出处:https://www.cnblogs.com/ALINGMAOMAO/p/10320090.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   青山新雨  阅读(276)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示