传送门:http://codeforces.com/problemset/problem/719/B
题目大意:
给你一个由'r','b'
组成的字符串,你可以进行两种操作:(1)把任意两个位置的字母互换;(2)把任意一个位置的r变成b,或b变成r。
输入一个字符串,问至少变几次才能成为r,b交错的序列?(rbrbrb….或者brbrbr…都行)
题目分析:
这是一个贪心策略,不过我一开始没想到。
分别考虑两种最终结果,计算字符串与目标串中r错位和b错位的个数(即目标为b,但实际为r和目标为r和实际为b),设为x1,x2,则要想把该字符串变成目标字符串,需要操作的次数为
max(x1,x2)
.
(想想为什么?其实道理很简单,首先通过
min(x1,x2)
次互换操作,再把剩下的r变成b或b变成r,需要
|x1−x2|
次操作,这俩加起来就是
max(x1,x2)
.)
最后取两种目标串操作的最小值就可以了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
char s[100005];
int main() {
scanf("%d",&n);
scanf("%s",s);
int ans1=0,ans2=0;
int t1=0,t2=0;
for(int i=0;i<n;i++) { //brbrbr...
if(i&1) {//r
if(s[i]=='b')
t1++;
}
else {// b
if(s[i]=='r')
t2++;
}
}
ans1=max(t1,t2);
t1=0;t2=0;
for(int i=0;i<n;i++) { //rbrbrb...
if(i&1) {//b
if(s[i]=='r')
t1++;
}
else {// r
if(s[i]=='b')
t2++;
}
}
ans2=max(t1,t2);
printf("%d\n", min(ans1,ans2));
}