D2. Kirk and a Binary String (hard version)

Posted by phpQuestioner_v5.0 on Tue, 08 Oct 2019 09:05:36 +0200

[Learning Blog] From https://blog.csdn.net/qcwlmqy/article/details/99973051

What I find useful is this section of the screenshot below.

Because you just need to consider that the maximum length of the left and right parts of the 10 decreases is the same. So let me first look at the back dp and find out the longest non-decreasing sequence length for each position of the suffix (from the back to the back).

Because the above illustration is divided into a number of 01 strings, the leading is 0, and the leading is 1.

Considering that the longest non-decreasing length is unchanged, the longest non-decreasing length of the interval is guaranteed to be unchanged.

Then start the new dp from the back of s to see if the new dp value (the longest non-decreasing length) changes when the current 1 changes to 0, if it does not indicate that the current position can be changed to 0.

AC Code:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
char s[N],t[N];
int dp[N][2],newdp[N][2];
int main()
{
	cin>>s+1;
	int n=strlen(s+1);
	for(int i=n;i>=1;--i)
    {
        if(s[i]=='1')
        {
            dp[i][1]=dp[i+1][1]+1;
            dp[i][0]=dp[i+1][0];
        }
        else{
            dp[i][0]=max(dp[i+1][1],dp[i+1][0])+1;
            dp[i][1]=dp[i+1][1];
        }
    }
    /*for(int i=1;i<=n;++i)
    {
        printf("1:%d ",dp[i][1]);
        printf("0:%d\n",dp[i][0]);
    }*/
    for(int i=n;i>=1;--i)
    {
        if(s[i]=='0')
        {
            t[i]='0';
            newdp[i][0]=max(newdp[i+1][1],newdp[i+1][0])+1;
            newdp[i][1]=newdp[i+1][1];
        }
        else{
            int tmp=max(newdp[i+1][1],newdp[i+1][0])+1;
            //printf("tmp:%d dp[i][0]:%d\n",tmp,dp[i][0]);
            if(tmp==dp[i][1])
            {
                t[i]='0';
                newdp[i][0]=tmp;
                newdp[i][1]=newdp[i+1][1];
            }
            else{
                t[i]='1';
                newdp[i][1]=newdp[i+1][1]+1;
                newdp[i][0]=newdp[i+1][0];
            }
        }
    }
    for(int i=1;i<=n;++i) printf("%c",t[i]);

}