CodeForces - 719B (思维题)

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.

只要明白更改后的字符串只可能为brbrbrbr或者rbrbrbrb.

所以我们可以先求出在只更改不交换的情况下,将字符串更改为目标字符串每种颜色的需要换几次,设需要更改的黑色和红色的个数分别为cb,cr. 红黑各更改一次等于交换一次红黑,所以操作次数为max(cr, cb), 然后比较两种情况下的结果,取小的就好了

#include <vector>
#include <stdio.h>
#include <map>
#include <stdlib.h>
#include<ctype.h>
#define LL long long
using namespace std;

const int MAX = 1e5 + 50;
char a[MAX];
int main(int argc, char const *argv[]){
	int n;
	scanf("%d", &n);
	int cr = 0;
	int cb = 0;
	for(int i = 1; i <= n; i++){
		scanf(" %c", &a[i]);
	}

	//rbrbrbrb
	for(int i = 1; i <= n; i++){
		if(i % 2 == 0 && a[i] == 'r'){
			cr++;
		}
		if(i % 2 == 1 && a[i] == 'b'){
			cb++;
		}
	}
	int ma = max(cr, cb);
	int ans = ma;

	cr = 0;
	cb = 0;
	//brbrbrbr
	for(int i = 1; i <= n; i++){
		if(i % 2 == 0 && a[i] == 'b'){
			cb++;
		}
		if(i % 2 == 1 && a[i] == 'r'){
			cr++;
		}
	}

	ma = max(cb, cr);
	ans = min(ans, ma);
	printf("%d\n", ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43737952/article/details/88985533
今日推荐