POJ 2533 —— Longest Ordered Subsequence 最长上升子序列裸题

原题:http://poj.org/problem?id=2533

题意:求最长递增子序列

注意:n = 0  n = 1 答案都是1


O(n²)

#include<cstdio>
const int maxn = 1100;
int n;
int dp[maxn];
int a[maxn];
int main()
{
	while(~scanf("%d", &n))
	{
		int ans = 0;	
		for(int i = 1;i<=n;i++)
		{
			scanf("%d", &a[i]);
			dp[i] = 1;
		}		
		if(n == 0 || n == 1)
		{
			printf("1\n");
			continue;
		}		
		for(int i = 2;i<=n;i++)
		{
			dp[i] = 1;
			for(int j = 1;j<i;j++)
			{
				if(a[i] > a[j] && dp[i] < dp[j] + 1)
				dp[i] = dp[j] + 1;
				if(ans < dp[i])
				ans = dp[i];
			}
		}
		printf("%d\n", ans);
	}	
	return 0;
}



O(nlogn)

<span style="font-size:10px;">#include<cstdio>
const int maxn = 1100;
int stack[maxn];
int n;
int main()
{
	while(~scanf("%d", &n))
	{
		int top = 0;
		stack[0] = -1;
		for(int i = 1;i<=n;i++)
		{
			int temp;
			scanf("%d", &temp);
			if(temp > stack[top])
				stack[++top] = temp;
			else
			{
				int l = 1, r = top;
				int mid;
				while(l <= r)
				{
					mid = (l + r) / 2;
					if(temp > stack[mid])
						l = mid + 1;
					else
						r = mid - 1;
				}
				stack[l] = temp;
			}
		}
		printf("%d\n", top);
	}
	return 0;
}</span>



用lower_bound()

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1100;
int a[maxn], stack[maxn];
int n;

int main()
{
	while(~scanf("%d", &n))
	{
		for(int i = 0;i<n;i++)
			scanf("%d", &a[i]);
		int top = 0;
		stack[0] = -1;
		for(int i = 0;i<n;i++)
		{
			if(a[i] > stack[top])
			{
				stack[++top] = a[i];
				continue;
			}				
			int pos = lower_bound(stack, stack+top, a[i]) - stack;
			stack[pos] = a[i];
		}
		printf("%d\n", top);
	}
	return 0;
}


你可能感兴趣的:(POJ 2533 —— Longest Ordered Subsequence 最长上升子序列裸题)