CodeForces 719B Anatoly and Cockroaches(思维锻炼题+贪心)

小希到了大学,发现宿舍里有很多蟑螂,蟑螂有两种颜色:红色和黑色

他把宿舍里的蟑螂排成一排,一共n只,小希想让他们变成颜色交替。 每次操作可以为:一、将一只蟑螂染成另一种颜色,二、交换两个蟑螂的位置

小希没有带电脑,他请你帮忙计算一下,最少需要操作几次才能形成颜色交替的一排蟑螂

Input

第一行一个整数 n (1 ≤ n ≤ 100 000) 

第二行一个字符串,长度为 n, 仅含有字符'b' 和 'r' r表示红色,b表示黑色.

Output

输出最少操作的次数

sample1

Input

3
rbr

Output

0

sample2

Input

5
rbbrr

Output

1

sample3

Input

5
bbbbb

Output

2

Hint

样例1中,可以交换第三只和第四只蟑螂. 这样共需要 1 次操作.

样例2中,把第2只和第4只蟑螂染成红色. 共两次操作.

样例3,不需要操作,操作数为0

这道题卡了一个小时还没写出来(太蒻了)

WA思路:开始想着把两种颜色蟑螂变得符合相邻不同色的数量,然后再进行换位,结果显然换位不知道怎么换,写的不知道是什么东西。

AC思路:由于是相邻必须是不同色,所以我们可以按照 奇数偶数位 的方法来进行思考

①假设 所有的奇数位都是“r” ,所有的偶数位都是“b”  此时奇数位 r 的数量为 x1  偶数位 b 的数量为 x2
②假设 所有的奇数位都是“b” ,所有的偶数位都是“r”  此时奇数位 b 的数量为 x3  偶数位 r 的数量为 x4

然后我们就可以判断出是 奇数位的 r 数量多 还是偶数位 r 的数量多, b同理

然后题目要求进行的最小操作数,所以我们尽可能地让 b 或者 r 安排在合理的位置上
即 max(x1,x4), 表示当奇数位为‘r’ 偶数位为‘b’ 情况下的符合要求的最多数量
    max(x2,x3),表示当奇数位为‘r’ 偶数位为‘b’ 情况下的符合要求的最多数量
那么我们肯定要取 b 或者 r 安排在合理的位置上的情况
那么另外一种情况就表示全变成相邻时候的最小操作数 即 min(max(x1,x4), max(x2,x3))

代码:

#include <iostream>
#include <algorithm>
#include <string.h>
#include <cstdio>
#include <string>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
//#include <unordered_map>
#define Fbo friend bool operator < (node a, node b)
#define mem(a, b) memset(a, b, sizeof(a))
#define FOR(a, b, c) for (int a = b; a <= c; a++)
#define RFOR(a, b, c) for (int a = b; a >= c; a--)
#define off ios::sync_with_stdio(0)
#define sc(a) scanf("%lld",&a)
#define pr(a) printf("%d\n",a);
#define SC(n,m) scanf("%d%d",&n,&m)
bool check1(int a) { return (a & (a - 1)) == 0 ? true : false; }

using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
const int INF = 0x3f3f3f3f;//1e10
const int mod = 1e9 + 7;
const int Maxn = 1e5 + 5;
const int M = Maxn * 20;
const double pi = acos(-1.0);
const double eps = 1e-8;

char s[Maxn];
int n;

int main() {
    int xr=0, xb=0, yr=0, yb=0;
    cin >> n >> s+1;
    for (int i = 1; i <= n; i++) {
        if (i & 1) {
            if (s[i] == 'r')
                xr++;
            else
                xb++;
        }
        else {
            if (s[i] == 'r')
                yr++;
            else
                yb++;
        }
    }
    //cout << "r:" << xr << " " << "b:" << xb << endl;
    //cout << "odd r:" << yr << " " << "odd b:" << yb << endl;
    int ans = min(max(xr, yb), max(xb, yr));
    cout << ans << endl;
}

猜你喜欢

转载自www.cnblogs.com/AlexLINS/p/12702593.html