Atcoder wide flip
题目原文
You are given a string S consisting of 0
and 1
.Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0
by repeating the following operation some number of times.
- Choose a contiguous segment [l,r] in S whose length is at least K (that is, r−l+1≥K must be satisfied). For each integer i such that l≤i≤r, do the following: if Si is
0
, replace it with1
; if Si is1
, replace it with0
.
Constraints
- 1≤|S|≤105
- Si(1≤i≤N) is either
0
or1
.
题意分析
给定一个只有0,1两个字符的字符串,每次翻转其中[l,r]之间的位,且要满足r-l+1>=K,求最大的K,使得字符串S最终被全部变为0.
解法分析
其实全部变为0或者1都一样,因为只需要全部再翻转一次,翻转次数肯定大于等于K,不影响K的最大值。此题也是动态规划问题,假设下标为i的位之前都已经相同,且S[i-1]!=S[i],则为了达到最终目的,一定会选择翻转前i个元素或者翻转后n-i个元素,由于K要取最大值,因此取max(i,n-i),遍历一遍S,res取min(res,max(i,n-i))。C++代码如下:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
string S;
cin>>S;
int res=S.size();
int a=S.size();
for(int i=1;i<S.size();i++){
if(S[i]!=S[i-1])
res=min(res,max(i,a-i));
}
cout<<res<<endl;
return 0;
}