题解:P16815 [蓝桥杯 2026 国 Python B] 糖果转盘
需要仔细观察。
思路
直接暴力枚举是不行的,
仔细观察之后,可以得到以下结论:
-
如果字符串中没有一对相邻的字符是相同的,那么切哪里都是合法的;
-
如果字符串中只有一对相邻的字符是相同的,那么只能从这两个字符中间切;
-
如果字符串中有很多(
数量\ge2 )对相邻的字符是相同的,那么从哪切都是不合法的。
所以,聪明的你又过了一道题,吗?
注意:题目给的字符串是个环!
所以需要特判一下字符串的第一位和最后一位。
代码
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll N=1e5+10;
int n;
int cnt;
string s;
int main(){
ios::sync_with_stdio(false),cin.tie(0);
cin>>n;
cin>>s;
for(int i=1;i<n;++i){
if(s[i]==s[i-1]){
cnt++;
}
}
if(s[0]==s[n-1]) cnt++;
if(cnt==0) cout<<n;
else if(cnt==1) cout<<1;
else cout<<0;
return 0;
}