1. 程式人生 > >【最長上升和下降子序列】導彈攔截

【最長上升和下降子序列】導彈攔截


大致思路

主要是思路問題 我本來以為用dp 想半天也沒想出來 最後一看題解 其實就是最長上升(也可以用dp做,只是我有現成方法)和下降子序列來做最簡單

po一個題解


然後我就寫了個求最長下降和最長上升子序列的程式碼,洛谷上是unknown error,我在本地執行第一個樣例是正確的。

程式碼:

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int des[maxn]; //最長下降子序列 
int asc[maxn]; //最長上升子序列 
int a[maxn];
int main()
{
	int cnt=1;
	while(scanf("%d",&a[cnt])!=EOF)  //這裡輸入有一手新東西。
	{
		cnt++;
	}
	cnt--;
	//求最長下降子序列
	int len1=1;
	des[1]=a[1];
	for(int i=2;i<=cnt;i++)
	{
		if(a[i]<=des[len1])
			des[++len1]=a[i];
		else
		{
			int pos=len1;
			while(des[pos]<a[i] && pos!=0)
				pos--;
			des[pos+1]=a[i];
		}
	} 
	int len2=1;
	asc[1]=a[1];
	for(int i=2;i<=cnt;i++)
	{
		if(a[i]>=asc[len2])
			asc[++len2]=a[i];
		else
		{
			int pos=lower_bound(asc,asc+len2,a[i])-asc;
			asc[pos]=a[i];
		}
	}
	cout<<len1<<endl<<len2;
	return 0;
}