2020 GDUT Winter Personal Training Contest I (Div. 2) C - Nice Garland 题解

原题

在这里插入图片描述

题目大意

给出一段字符串,在这个字符串中仅包含’R’,‘B’,'G’三个字符(也就是三原色),修改该字符串使得它某个字符旁边以及旁边的旁边不能出现他自己,输出修改次数最小的方案和修改后的字符串

题目分析

一开始我是想用贪心的,就是三格三格找,最后一个入队的和要出队的一样就将入队的改掉
核心代码如下

    while (ft < n)
    {
        if (ori[ft] == ori[fs])
        {
            ft++,fs++;
        }
        else
        {
            ori[ft] = ori[fs];
            ft++,fs++,ans++;
        }        
    }

结果发现不行……还是交上去之后才想到的
反例很容易想得到(证明我是zz)

9
RGBBRGBRG

我的程序会输出

6
RGBRGBRGB

标准答案

3
BRGBRG

其实很容易发现答案(wo)是重(nao)复(can)的,也就是说它的前三个一旦确定,后面就是这三个的重复
然后我脑子进水了,写了一个这样的东西
在这里插入图片描述
在你打出3个以上循环的strcat之后,编译器会很好心地帮你一直连接下去,并且throw出一个error
其实写一个mod滚动一下就行
然后我这题卡了90min……在这里插入图片描述
最后一个错是测试完没把数组改回来(日常犯傻)
下面AC代码

代码

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
 
char ori[200010];
bool been[128];
int ans = 0x3f3f3f3f,fs = 0,ft = 0,tot = 0;
int main()
{
    int n;
    char t;
    scanf("%d",&n);
    scanf("%s",ori);
    std::string test,min;
    test = "RGB";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }    
    test = "RBG";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }
    test = "BRG";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }
    test = "BGR";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }
    test = "GRB";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }
    test = "GBR";
    tot = 0;
    for (int i = 0;i < n;i++)
    {
        if (ori[i] != test[i % 3]) tot++;
    }
    if (tot < ans) 
    {
        min = test;
        ans = tot;
    }
    printf("%d\n",ans);
    int len = 0;
    while (len + 3 < n)
    {
        std::cout << min;
        len += 3;
    }
    for (int i = 0;i < n - len;i++)
        putchar(min[i]);
    return 0;
}

我是真的懒得写搜索了……反正这么小枚举一下也没所谓
还有这个string就是我鼓捣快速循环字符串(?)的时候弄出来的

发布了16 篇原创文章 · 获赞 0 · 访问量 283

猜你喜欢

转载自blog.csdn.net/juseice/article/details/104024212