Atcoder wide flip解題報告

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, rl+1K must be satisfied). For each integer i such that lir, do the following: if Si is 0, replace it with 1; if Si is 1, replace it with 0.

Constraints

  • 1|S|105
  • Si(1iN) is either 0 or 1.

題意分析

給定一個只有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;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章