天天看点

最长递增子序列(LIS)的O(NlogN)打印算法

题目:

求一个一维数组arr[n]中的最长递增子序列的长度,如在序列1,5,8,3,6,7中,最长递增子序列长度为4 (即1,3,6,7)。

由于LIS用O(NlogN)也能打印,O(N^2)的DP方法见最后。

从LIS的性质出发,要想得到一个更长的上升序列,该序列前面的数必须尽量的小。

对于原序列1,5,8,3,6,7来说,当子序列为1,5,8时,遇到3时,序列已经不能继续变长了。但是,我们可以通过替换,使“整个序列”看上去更小,从而有更大的机会去变长。这样,当替换5-3和替换8-6完成后(此时序列为1,3,6),我们可以在序列末尾添加一个7了。

那为什么复杂度可以是O(NlogN)呢?

关键就在“替换”这一步上,若直接遍历序列替换,每次替换都要O(N)的时间。但是只要我们再次利用LIS的性质——序列是有序的(单调的),就可以用二分查找,在O(logN)的时间内完成一次替换,所以算法的复杂度是O(NlogN)的。

代码如下:

#include<bits/stdc++.h>
using namespace std;

const int inf = 0x3f3f3f3f;
const int mx = int(1e5) + 5;

int a[mx], dp[mx], pos[mx], fa[mx];
vector<int> ans;

int get_lis(int n)
{
	memset(dp, 0x3f, sizeof(dp));
	pos[0] = -1;
	int i, lpos;
	for (i = 0; i < n; ++i)
	{
		dp[lpos = (lower_bound(dp, dp + n, a[i]) - dp)] = a[i];
		pos[lpos] = i; /// *靠后打印
		fa[i] = (lpos ? pos[lpos - 1] : -1);
	}
	n = lower_bound(dp, dp + n, inf) - dp;
	for (i = pos[n - 1]; ~fa[i]; i = fa[i]) ans.push_back(a[i]);
	ans.push_back(a[i]); /// 最后逆序打印ans即可
	return n;
}
           

例题:

POJ 3903 Stock Exchange

UVA 481 What Goes Up

推广:带权值的最长上升子序列:

UVa 11790 Murcia's Skyline

HDU 1087 Super Jumping! Jumping! Jumping!

另:最长不降子序列:

#include<bits/stdc++.h>
using namespace std;
const int mx = 10005;

int lis[mx];

bool cmp(int a, int b)
{
	return a <= b;
}

int main()
{
	int N, len, i, j, x;
	while (~scanf("%d", &N))
	{
		len = 0;
		for (i = 1; i <= N; ++i)
		{
			scanf("%d", &x);
			j = lower_bound(lis + 1, lis + len + 1, x, cmp) - lis;
			lis[j] = x;
			len = max(len, j);
		}
		printf("%d\n", len);
	}
	return 0;
}
           

最长递减子序列:

#include<bits/stdc++.h>
using namespace std;
const int mx = 10005;

int lis[mx];

int main()
{
	int N, len, i, j, x;
	while (~scanf("%d", &N))
	{
		len = 0;
		for (i = 1; i <= N; ++i)
		{
			scanf("%d", &x);
			j = lower_bound(lis + 1, lis + len + 1, x, greater<int>()) - lis;
			lis[j] = x;
			len = max(len, j);
		}
		printf("%d\n", len);
	}
	return 0;
}
           

附:O(N^2)算法

像LCS一样,从后向前分析,很容易想到,第i个元素之前的最长递增子序列的长度要么是1(单独成一个序列),要么就是第i-1个元素之前的最长递增子序列加1,这样得到状态方程:

        LIS[i] = max{1,LIS[k]+1}  (∀k<i,arr[i] > arr[k])

这样arr[i]才能在arr[k]的基础上构成一个新的递增子序列。

代码如下:在计算好LIS长度之后,递归输出其中的一个最长递增子序列。

#include<cstdio>
#include<algorithm>
using namespace std;

int dp[31]; /* dp[i]记录到[0,i]数组的LIS */
int lis = 1;    /* LIS长度,初始化为1 */

int LIS(int *arr, int arrsize)
{
	for (int i = 0; i < arrsize; ++i)
	{
		dp[i] = 1;
		for (int j = 0; j < i; ++j) /// 注意i只遍历比它小的元素
			if (arr[j] < arr[i])
				dp[i] = max(dp[i], dp[j] + 1);
		lis = max(lis, dp[i]);
	}
	return lis;
}

/* 递归输出LIS,因为数组dp还充当了“标记”作用 */
void outputLIS(int *arr, int index)
{
	bool isLIS = false;
	if (index < 0 || lis == 0)
		return;
	if (dp[index] == lis)
	{
		--lis;
		isLIS = true;
	}
	outputLIS(arr, --index);
	if (isLIS)
		printf("%d ", arr[index + 1]);
}

int main(void)
{
	int arr[] = {1, 5, 8, 3, 6, 7};
	printf("%d\n", LIS(arr, sizeof(arr) / sizeof(*arr)));
	outputLIS(arr, sizeof(arr) / sizeof(*arr) - 1);
	return 0;
}