Educational Codeforces Round 97 (Rated for Div. 2)-B. Reverse Binary Strings

B. Reverse Binary Strings
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a string s of even length n. String s is binary, in other words, consists only of 0’s and 1’s.

String s has exactly n2 zeroes and n2 ones (n is even).

In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.

What is the minimum number of operations you need to make string s alternating? A string is alternating if si≠si+1 for all i. There are two types of alternating strings in general: 01010101… or 10101010…

Input
The first line contains a single integer t (1≤t≤1000) — the number of test cases.

The first line of each test case contains a single integer n (2≤n≤105; n is even) — the length of string s.

The second line of each test case contains a binary string s of length n (si∈ {0, 1}). String s has exactly n2 zeroes and n2 ones.

It’s guaranteed that the total sum of n over test cases doesn’t exceed 105.

Output
For each test case, print the minimum number of operations to make s alternating.

Example
inputCopy
3
2
10
4
0110
8
11101000
outputCopy
0
1
2
Note
In the first test case, string 10 is already alternating.

In the second test case, we can, for example, reverse the last two elements of s and get: 0110 → 0101.

In the third test case, we can, for example, make the following two operations:

11101000 → 10101100;
10101100 → 10101010.

思路: 因为只有0和1,,我们需要把这一列数字变成0和1相间的,我们只有一个操作,就是可以选择一部分连续的数字然后把他们反转。通过观察,我们可以很容易的发现对于每一次翻转,我们最多形成两组01,而且只有连续的0或者连续的1才需要改变,所以本题就非常简单了,找出有几个连续的1,比如01110算2个连续的1每一段的第一个不算,在找出有几个连续的0,然后比较0多还是1多,多的那个就是最后的操作数。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char a[1000007];
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		getchar();
		scanf("%s",a);
		int cnt1=0,cnt2=0;
		for(int i=1;i<n;i++)
		{
				if(a[i]-'0'==1&&a[i-1]-'0'==1)cnt1++;
				if(a[i]-'0'==0&&a[i-1]-'0'==0)cnt2++;
		}
		printf("%d\n",max(cnt1,cnt2));
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值