LIS的定义
LIS(Longest Increasing Subsequence)最长上升子序列
一个数的序列bi,当b1 < b2 < … < bS的时候,我们称这个序列是上升的。
对于给定的一个序列(a1, a2, …, aN),我们可以得到一些上升的子序列(ai1, ai2, …, aiK),
这里1 <= i1 < i2 < … < iK <= N。
比如,对于序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。
这些子序列中最长的长度是4,比如子序列(1, 3, 5, 8).
你的任务,就是对于给定的序列,求出最长上升子序列的长度。
做法一:动态规划 O(N^2)
状态设计:dp[i]代表以a[i]结尾的LIS的长度
状态转移:dp[i]=max(dp[i], dp[j]+1) (1<=j< i, a[j]< a[i])
边界处理:dp[i]=1 (1<=i<=n)
时间复杂度:O(N^2)
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#define MAXN 1000
using namespace std;
typedef long long ll;
int ans[MAXN+5];
int dp[MAXN+5];
int main()
{
int n,re=1;
cin>>n;
for(int i=1;i<=n;++i){
cin>>ans[i];
}
for(int i=1;i<=n;++i){
dp[i]=1;
for(int j=1;j<=i-1;++j){
if(ans[j]<ans[i]) dp[i]=max(dp[i],dp[j]+1);
}
re=max(re,dp[i]);
}
cout<<re<<endl;
}
做法二:贪心+二分 O(N*logN)
维护一个单调的队列
新的元素,如果大于队尾元素,即插入队尾
否则二分查找比它大的最小元素,替换掉
最后队列长度即为LIS的解
如下例:
1 3 7 5 9 4 8
1
1 3
1 3 7
1 3 5
1 3 5 9
1 3 4 9
1 3 4 8
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#define MAXN 1000
using namespace std;
typedef long long ll;
int ans[MAXN+5];
vector<int> b;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;++i){
cin>>ans[i];
if(b.empty()) b.push_back(ans[i]);
else{
if(ans[i]>b.back()) b.push_back(ans[i]);
else{
vector<int>::iterator it=upper_bound(b.begin(),b.end(),ans[i]);
*it=ans[i];
}
}
}
cout<<b.size()<<endl;
}
poj2533 Longest Ordered Subsequence
题目链接:http://poj.org/problem?id=2533