题意:给出一个01串,要求在不改变所有子串的最长非递减子序列长度的情况下把它改造成一个0尽可能多的串
题解:显然原串中的0不用改变,那么考虑1什么情况下可以进行改变。
假如把某个位置的1改为0导致一个子串的最长非递减子序列长度改变了,那么考虑整个串的最长非递减子序列是否改变。
假设不改变,那么显然就是整个串的最长非递减子序列长度不增也不减,考虑不增,显然原串的最长非递减子序列在该子串左端时末尾已经是1了,而末尾是1时改变当前子串的1为0显然会减少长度这与假设矛盾,同理,考虑不减,显然原串的最长非递减子序列在该子串左端时末尾是0,而末尾是0时改变当前子串的1为0显然会增加长度这与假设矛盾。
因此当一个子串的最长非递减子序列长度改变时整个串的最长非递减子序列长度也改变了,取其逆否命题可知当整个串的最长非递减子序列长度不变时那么子串最长非递减子序列长度也不变,所以只考虑整个串最长非递减子序列长度是否改变即可。
dp[0][i]表示1i子串的最长非递减子序列的长度,dp[1][i]表示in子串的最长非递减子序列的长度,sum[0][i]表示1i子串0的个数,sum[1][i]表示in子串1的个数。当改变某个1为0时,整个串的最长非递减子序列长度应变为max(dp[0][i-1]+sum[1][i+1],dp[1][i+1]+sum[0][i-1]+1),判断是否与最初的dp[0][n]相等即可确定是否可以改变当前1
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define debug(x) cout<<#x<<" is "<<x<<endl;
const ll mod=1e9+7;
const ll inf=1e15;
const int maxn=1e5+5;
char ch[maxn];
int dp[2][maxn],sum[2][maxn],b[maxn];
int main(){
scanf("%s",ch+1);
int len=strlen(ch+1);
int top=0;
for(int i=1;i<=len;i++){
if(top==0){
b[++top]=ch[i]-'0';
}
else if(b[top]<=ch[i]-'0'){
b[++top]=ch[i]-'0';
}
else{
int w=ch[i]-'0';
int pos=upper_bound(b+1,b+1+top,w)-b;
b[pos]=w;
}
dp[0][i]=top;
sum[0][i]=sum[0][i-1]+(ch[i]=='0');
}
top=0;
for(int i=len;i>=1;i--){
if(top==0){
b[++top]=-ch[i]+'0';
}
else if(b[top]<=-ch[i]+'0'){
b[++top]=-ch[i]+'0';
}
else{
int w=-ch[i]+'0';
int pos=upper_bound(b+1,b+1+top,w)-b;
b[pos]=w;
}
dp[1][i]=top;
sum[1][i]=sum[1][i+1]+(ch[i]=='1');
}
for(int i=1;i<=len;i++){
if(ch[i]=='0');
else if(max(dp[0][i-1]+sum[1][i+1],dp[1][i+1]+sum[0][i-1]+1)==dp[0][len]){
ch[i]='0';
}
sum[0][i]=sum[0][i-1]+(ch[i]=='0');
}
printf("%s\n",ch+1);
return 0;
}