D1. Kirk and a Binary String (easy version)

D1. Kirk and a Binary String (easy version)

01串找最长不降子序列

给定字符串s,要求生成一个等长字符串t,使得任意l到r位置的最长不降子序列长度一致

从后往前暴力枚举,枚举每个一替换成0后是否改变了l到r位置的最长不降子序列长度

01串的最长不降子序列,可以通过线性dp求解

dp i表示以i结尾的最长不降子序列长度

dp[0]=dp[0]+s[i]=='0';

dp[1]=max(dp[0],dp[1])+s[i]=='1';

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define sc(x) scanf("%I64d",&(x));
typedef long long ll;
#define maxn 2005

#define INF 1e18
ll N;
ll val[2][maxn];
ll dp[2];
void LIS(string s,int st,int  val[])
{
    dp[0]=dp[1]=0;
    for(int i=st;i<N;i++){
        if(s[i]=='0'){
            dp[0]++;
        }else dp[1]=max(dp[0],dp[1])+1;
        val[i]=max(dp[0],dp[1]);
    }

}
signed main()
{
    string s,t;
    cin>>s;
    N=s.size();
    t=s;
    //int len=0;
    for(int i=N-1; i>=0;i--)
    {
        if(s[i]=='1')
        {
            t[i]='0';
            LIS(s,i,val[0]);
            LIS(t,i,val[1]);
            for(int j=i;j<N;j++){
                if(val[0][j]!=val[1][j]){
                    t[i]='1';
                    break;
                }
            }
        }
    }
    cout<<t<<'\n';
}

猜你喜欢

转载自www.cnblogs.com/liulex/p/11386740.html