题目:
https://codeforces.com/contest/1437/problem/B
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…
题意:
给你一个字符串,字符串的长度是偶数,其中有n/2个1,有n/2个0,你可以随便选择一个长度的字符串将其顺序颠倒,问最少操作几次可以使字符串变为010101…或101010…
思路:
思维题。因为你可以选择任意长度的字符串,也就是说你可以尽可能地使前面连续的位置变成不连续并尽可能地保证后面的也是不连续的。因为,如果前面有两(n)个字符连续,那后面一定至少也有两个字符是连续的(也可能是3(n+1)个)。那么,我们最优的答案,也就是变换连续个1的长度-1或者连续个0的长度-1中的较大者。
代码:
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;
const double N = 1e6+10;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const inline int read(){
int k = 0, f = 1; char c = getchar();
for(;!isdigit(c); c = getchar())
if(c == '-') f = -1;
for(;isdigit(c); c = getchar())
k = k * 10 + c - '0';
return k * f;
}
#define ll long long
#define CL(a,b) memset(a,b,sizeof(a))
#define MAXN 500010
int n;
string s;
int main()
{
int t;
cin >> t;
while(t--)
{
cin >> n >> s;
int ans1 = 0;
int ans0 = 0;
for(int i = 0 ; i < s.length()-1 ; i++)
{
if(s[i]=='1'&&s[i+1]=='1')
ans1++;
if(s[i]=='0'&&s[i+1]=='0')
ans0++;
}
cout << max(ans1,ans0) << endl;
}
return 0;
}