题解:P14225 [ICPC 2024 Kunming I] 左移 2
zyen11451425 · · 题解
P14225 [ICPC 2024 Kunming I] 左移 2
题目描述
给定一个由小写字母组成的字符串,称该字符串是美丽的,若字符串中每一对相邻的字符都不相同。例如,
给定由小写英文字母组成的,长度为
令
找到一个非负整数
输入格式
有多组测试数据。第一行输入一个整数
第一行输入一个仅由小写字母组成的字符串
保证所有数据
输出格式
每组数据输出一行一个整数,表示最小的
输入输出样例 #1
输入 #1
3
abccbbbbd
abcde
x
输出 #1
2
0
0
说明/提示
对于第一组样例数据,考虑
思路
字符串中不能有两个相邻的相同字符,所以我们将字符串首尾相接(长度乘
然后考虑“左移”这一操作对答案的影响。
当我们将一个偶数长度的字符串左移到字符串首尾时,可以使其变为两个奇数长度字符串,就能使操作次数减
代码
#include<bits/stdc++.h>
using namespace std;
int t,n;
string s;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>t;
while(t--){
cin>>s;
s+=s;
n=s.size();
if(n==2){
cout<<"0\n";
continue;
}
int ans=0,cnt=1;
bool f=0;
for(int i=1;i<n;i++){
if(s[i]==s[i-1])cnt++;
else{
if(cnt%2==0)f=1;
ans+=cnt/2;
cnt=1;
}
}
ans+=cnt/2;
if(f)ans--;
cout<<ans/2<<'\n';
}
return 0;
}