Codeforces Round #535 (Div. 3)C

本文探讨了一个编程竞赛问题,即如何通过最小数量的颜色更改使一串由红、绿、蓝三色组成的灯饰花环变得“漂亮”。漂亮花环的定义为任意两个相同颜色的灯之间的距离必须能被3整除。文章提供了一种有效的解决方案,通过预设六种可能的漂亮排列,逐一比较原序列与这些模式的差异,找到所需更改次数最少的一种。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:https://codeforces.com/problemset/problem/1108/C
You have a garland consisting of ? lamps. Each lamp is colored red, green or blue. The color of the ?-th lamp is ?? (‘R’, ‘G’ and ‘B’ — colors of lamps in the garland).

You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.

A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is ?, then for each ?,? such that ??=?? should be satisfied |?−?| ??? 3=0. The value |?| means absolute value of ?, the operation ? ??? ? means remainder of ? when divided by ?.

For example, the following garlands are nice: “RGBRGBRG”, “GB”, “R”, “GRBGRBG”, “BRGBRGB”. The following garlands are not nice: “RR”, “RGBG”.

Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

Input
The first line of the input contains one integer ? (1≤?≤2⋅105) — the number of lamps.

The second line of the input contains the string ? consisting of ? characters ‘R’, ‘G’ and ‘B’ — colors of lamps in the garland.

Output
In the first line of the output print one integer ? — the minimum number of recolors needed to obtain a nice garland from the given one.

In the second line of the output print one string ? of length ? — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

Examples
inputCopy
3
BRB
outputCopy
1
GRB
inputCopy
7
RGBGRBB
outputCopy
3
RGBRGBR

大意:替换最少的字符使得字符串符合漂亮花环的定义。漂亮花环定义:如果任何两个相同颜色的灯具有可被3整除的距离,那么花环就会被称为漂亮

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#define inf 0x3f3f3f3f
using namespace std;
int main(){
string col[6]={"RGB","RBG","GBR","GRB","BGR","BRG"};//二维数组,字符串数组更方便
int n;
scanf("%d",&n);
string s;
cin>>s;
int ans=inf ,idx;
for(int i=0;i<6;i++){
int cnt=0;//计数变量要放在这,每次换成不同的字符串重新计算。例如:从“RGB”到“RBG”要重新计算不同字符个数
for(int j=0;j<n;j++)
if(s[j]!=col[i][j%3])
  cnt++;
  if(ans>cnt){
  ans=cnt;//更新最小值
  idx=i;//纪录下标,看是匹配成哪个字符串
                  }
}
printf("%d\n",ans);
for(int i=0;i<n;i++)
printf("%c",col[idx][i%3]);//匹配成哪个字符串,就直接循环输出
printf("\n");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值