Luogu P1091 [NOIP2004 Improvement Group] Chorus formation (LIS linear dp, dichotomy)

Problem Description:

Insert picture description here


code show as below:

#include<bits/stdc++.h>
using namespace std;
const int N=105;
int n;
int a[N];
int l[N],r[N];
void dp1()
{
    
    
	int f[N];
	int len=1;
	f[1]=a[1];
	l[1]=1;
	for(int i=2;i<=n;i++){
    
    
		if(f[len]<a[i]) f[++len]=a[i];
		else{
    
    
			int pos=lower_bound(f+1,f+1+len,a[i])-f;
			f[pos]=a[i];
		}
		l[i]=len;
	}
}
void dp2()
{
    
    
	int f[N];
	int len=1;
	f[1]=a[n];
	r[n]=1;
	for(int i=n-1;i>=1;i--){
    
    
		if(f[len]<a[i]) f[++len]=a[i];
		else{
    
    
			int pos=lower_bound(f+1,f+1+len,a[i])-f;
			f[pos]=a[i];
		}
		r[i]=len;
	}
}
int main()
{
    
    
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	dp1();
	dp2();
	int ans=0;
	for(int i=1;i<=n;i++){
    
    
		ans=max(ans,l[i]+r[i]-1);
	}
	cout<<n-ans;
	return 0;
}

to sum up:

Calculate the longest ascending subsequence from left to right and from right to left respectively, and then traverse all cases to obtain the optimal solution

Guess you like

Origin blog.csdn.net/Lzhzl211/article/details/114650157