poj1836(LIS的二分写法,模板)

解题思路:以前一直没有试过LIS的二分搜索写法,复杂度只有O(nlogn)。这道题的思路也是很明确,输入的数组从左向右做一遍LIS dp,再从右向左做一遍LIS。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
double s[1005],g[1005];
int d1[1005],d2[1005];
int main()
{
	int n;
	//freopen("t.txt","r",stdin);
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	scanf("%lf",&s[i]);
	for(int i=0;i<n;i++) g[i]=1000000;
	for(int i=0;i<n;i++)
	{
		int k=lower_bound(g,g+n,s[i])-g;
		g[k]=s[i];//更新末尾的数 
		d1[i]=k+1;//记录以第i位为结尾的最长上升子序列长度 
	}
	for(int i=0;i<n;i++) g[i]=1000000;
	for(int i=n-1;i>=0;i--)
	{
		int k=lower_bound(g,g+n,s[i])-g;
		g[k]=s[i];
		d2[i]=k+1;
	}
	int ans=0;
	for(int i=0;i<n;i++)
	{
		for(int j=i+1;j<n;j++)
		{
			ans=max(ans,d1[i]+d2[j]);
		}
	 }
	 printf("%d\n",n-ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39861441/article/details/88585339