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;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值