题解:CF603A Alternative Thinking
思路
你猜这个题为什么是 A 题?
很思维的解法。
只允许翻转一次,所以最多只会在原答案上加 \(2\)。
所以我们来讨论仅有的三种可能:
- 加 \(2\),要有两段连续的 \(0\) 或 \(1\)。
- 加 \(1\),要有一段连续的 \(0\) 或 \(1\)。
- 不加,没有连续的 \(0\) 或 \(1\)。
我们的代码模拟上面的三种可能就好了。
AC 代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
string s;
int n;
int main(){
// freopen("text.in","r",stdin);
// freopen("text.out","w",stdout);
ios::sync_with_stdio(0),cout.tie(0),cin.tie(0);
cin>>n>>s;
int ans = 1;
int ctn = 0;
for(int i = 1;i < n;i++){
if(s[i] != s[i-1]){
ans++;
}else{
ctn++;
}
}
if(ctn >= 2)cout<<ans+2;
if(ctn == 1)cout<<ans+1;
else cout<<ans;
return 0;
}

浙公网安备 33010602011771号