POJ 2533 Longest Ordered Subsequence DP(LIS)

题意:求最长不降子序列。
题解:注意 n = 0 时要输出1.

n^2算法

#include <cstdio>

int main()
{
	int dp[1005], a[1005];
	int n, i, j, max;
	while ( scanf("%d",&n) != EOF )
	{
		for ( i = 1; i <= n; i++ )
		{
			scanf("%d",&a[i]);
			dp[i] = 1;
		}
		
		max = 1;
		for ( i = 2; i <= n; i++ )
		{
			for ( j = 1; j < i; j++ )
				if ( a[i] > a[j] && dp[j] >= dp[i] )
					dp[i] = dp[j] + 1;
			if ( max < dp[i] )
				max = dp[i];
		}
		printf("%d\n",max);
	}
	return 0;
}


n*logn算法:

#include <iostream>
using namespace std;

int dp[1005], a[1005];

int bfind ( int l, int r, int key )
{
	while ( l <= r )
	{
		int mid = ( l + r ) / 2;
		if ( key <= dp[mid] )
			r = mid - 1;
		else
			l = mid + 1;
	}
	return l;
}

int main()
{
	int n, i, j, len;	
	while ( scanf("%d",&n) != EOF )
	{	
		for ( i = 1; i <= n; i++ )
			scanf("%d",&a[i]);
		
		dp[1] = a[1]; len = 1;
		for ( i = 2; i <= n; i++ )
		{
			j = bfind ( 1, len, a[i] );
			if ( j > len ) j = ++len;
			dp[j] = a[i];
		}	
		printf("%d\n",len);
	}
	return 0;
}


你可能感兴趣的:(算法)