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.
Source
Codeforces Round #373 (Div. 2)
My Solution
贪心、字符串
对于 1010101...... (0 ~ n-1) 如果奇数的地方不是1就 ans1++, 如果偶数的地方不是0就 ans0++,
ans = max(ans0, ans1); //min(ans0, ans1)次交换, ans - min(ans0, ans1) 次改变颜色
然后再对 010101......(0 ~ n-1) 的情况跑一遍
2个ans取最小值
复杂度 O(n)
此外 用 x & 1 表示偶数的时候 要写成 ((x & 1) == 0),(x & 1)要加括号,位运算符的优先级比逻辑运算符低,由于当时没有注意这个问题迷之WA,然后Debug很久。⊙﹏⊙‖∣
#include <iostream> #include <cstdio> #include <string> #include <cstring> using namespace std; typedef long long LL; const int maxn = 1e5 + 8; bool v[maxn]; int main() { #ifdef LOCAL freopen("b.txt", "r", stdin); //freopen("b.out", "w", stdout); int T = 5; while(T--){ #endif // LOCAL ios::sync_with_stdio(false); cin.tie(0); string s, s1, s2; LL n, ans0 = 0, ans1 = 0, ans = 0; cin >> n; cin >> s; s1 = s; s2 = s; for(int i = 0; i < n; i++){ if(s[i] == 'r'){ v[i] = 0; v[i] = 0; } else{ v[i] = 1; v[i] = 1; } } for(int i = 0; i < n; i++){ //cout << v[i] <<" "; if(i % 2 == 0){ if(v[i] == 0) ; else ans0++; } else{ if(v[i] == 1) ; else ans1++; } } //cout << endl; //cout <<ans0 << " " << ans1 << endl; ans = max(ans0, ans1); ans0 = ans1 = 0; for(int i = 0; i < n; i++){ //cout << v[i] <<" "; if(i % 2 == 0){ if(v[i] == 1) ; else ans0++; } else{ if(v[i] == 0) ; else ans1++; } } //cout <<ans0 << " " << ans1 << endl; ans = min(ans, max(ans0, ans1)); cout << ans << endl; #ifdef LOCAL cout << endl; } #endif // LOCAL return 0; }
Thank you!
------from ProLights