Description
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
1
5
bbbbb
2
3
rbr
0
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
正解:贪心
解题报告;
Xlight他们都看成了只能交换相邻的,调了好久,论不看题的危害。
考虑最终序列只有可能有2种情况,那么分别枚举,两个答案取一个min即可。
考虑直接贪心,首先我们可以统计出有多少个错位的元素,最后直接把能交换的全部交换,否则就暴力染色就可以了。
//It is made by jump~
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
typedef long long LL;
const int inf = (<<);
const int MAXN = ;
int n,a[MAXN];
int cnt[];
int ans,ans2; inline int getint()
{
int w=,q=; char c=getchar();
while((c<'' || c>'') && c!='-') c=getchar(); if(c=='-') q=,c=getchar();
while (c>='' && c<='') w=w*+c-'', c=getchar(); return q ? -w : w;
} inline void work(){
n=getint(); char c;
for(int i=;i<=n;i++) {
c=getchar(); while(c!='r' && c!='b') c=getchar();
if(c=='b') a[i]=; else a[i]=;
}
int tag=; int minl;
for(int i=;i<=n;i++) {
if(tag!=a[i]){
cnt[tag]++;
if(cnt[tag^]>) {
minl=min(cnt[tag^],cnt[tag]);
cnt[tag]-=minl; cnt[tag^]-=minl;
ans+=minl;
}
}
tag^=;
}
minl=min(cnt[],cnt[]); ans+=minl; cnt[]-=minl; cnt[]-=minl;
ans+=cnt[]; ans+=cnt[]; tag=; cnt[]=cnt[]=;
for(int i=;i<=n;i++) {
if(tag!=a[i]){
cnt[tag]++;
if(cnt[tag^]>) {
minl=min(cnt[tag^],cnt[tag]);
cnt[tag]-=minl; cnt[tag^]-=minl;
ans2+=minl;
}
}
tag^=;
}
minl=min(cnt[],cnt[]); ans2+=minl; cnt[]-=minl; cnt[]-=minl;
ans2+=cnt[]; ans2+=cnt[]; printf("%d",min(ans,ans2));
} int main()
{
work();
return ;
}