POJ 2533. Longest Ordered Subsequence
1. 题目
http://poj.org/problem?id=2533
Longest Ordered Subsequence
Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 39666 Accepted: 17428 Description
A numeric sequence of ai is ordered if a1 < a2 < … < aN. Let the subsequence of the given numeric sequence (a1, a2, …, aN) be any sequence (ai1, ai2, …, aiK), where 1 <= i1 < i2 < … < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.
Input
The first line of input file contains the length of sequence N. The second line contains the elements of sequence – N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000Output
Output file must contain a single integer – the length of the longest ordered subsequence of the given sequence.Sample Input
7 1 7 3 5 9 4 8Sample Output
4Source
Northeastern Europe 2002, Far-Eastern Subregion
2. 思路
给出一个序列,求最长上升子序列(Longest Increasing Subsequence,LIS)。
使用seq[i]表示序列中第i个数字,cnt[i]表示以序列中第i个数字结尾所能构成的最长上升序列的长度(注意这里必须使用第i个数字),则有:
cnt[i] = max(cnt[j]) + 1, j∈[1, i-1]且seq[j] < seq[i]
如果当前数字seq[i]大于i之前的某个数字seq[j],则seq[i]可以放在seq[j]后面形成一个长度为cnt[j]+1的上升子序列,查找满足条件的最大的cnt[j],再加1作为cnt[i]的值。如果seq[i]之前的数字都比seq[i]大,则seq[i]只能独自作为一个上升子序列,cnt[i]为1。最后找到cnt[]中的最大值即为答案。
该算法时间复杂度为O(n^2),求LIS还有一种O(nlog(n))的算法,可以参考这里。
3. 代码
#include <cstdio> const int MAX_LENGTH = 1001; void solveE6c_LongestOrderedSubsequence(); int main() { solveE6c_LongestOrderedSubsequence(); return 0; } short seq[MAX_LENGTH], cnt[MAX_LENGTH]; void solveE6c_LongestOrderedSubsequence() { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &seq[i]); } int result = 0; cnt[0] = 0; for (int i = 1; i <= n; ++i) { int max = 0; for (int j = 1; j < i; ++j) { if (seq[j] < seq[i]) max = max > cnt[j] ? max : cnt[j]; } cnt[i] = max + 1; result = result > cnt[i] ? result : cnt[i]; } printf("%d\n", result); }