题目描述:
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly’s room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it’s color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
输入描述:
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters ‘b’ and ‘r’ that denote black cockroach and red cockroach respectively.
输出描述:
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
输入:
5
rbbrr
5
bbbbb
3
rbr
输出:
1
2
0
题意:
给你一个字符串 然后给你了这个字符串的长度 然后让你从这个字符串中找到一种最有的策略 让这个字符串变成指定的格式 这种格式是brbrbr… 或者rbrbrbrbr…任意一种你有两种操作 第一种是交换一个b和一个r的位置第二种操作是把任意的一个b改成r 或者把任意的r改成b问你最少的操作次数
题解:
贪心,最后结果要么rbrbrb…要么brbrbr…。然后找放错的位置,
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
char s[maxn];
int main(){
int n;
while(scanf("%d",&n)!=EOF){
getchar();
for(int i = 1; i <= n; i ++){
scanf("%c",&s[i]);
}
int r = 0,b = 0;
//1.rb
for(int i = 1; i <= n; i ++){
if(i % 2 == 0 && s[i] == 'r') r ++;
else if(i % 2 != 0 && s[i] == 'b') b ++;
}
int maxx = max(r,b);
r = 0;
b = 0;
//2.rb
for(int i = 1; i <= n; i ++){
if(i % 2 == 0 && s[i] == 'b') b ++;
else if(i % 2 != 0 && s[i] == 'r') r ++;
}
int maxx2 = max(r,b);
int ans = min(maxx,maxx2);
printf("%d\n",ans);
}
return 0;
}