Longest Ordered Subsequence
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). 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 <= 1000 Output Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence. Sample Input Sample Output Source Northeastern Europe 2002, Far-Eastern Subregion |
方法一:O(n2)法
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 100000
int n, A[MAX+1], L[MAX+1];//A[]含有输入数据,L[i]代表以i结尾的递增序列的长度
int lis()
{
int res = 1;
for(int i=0; i<n; i++)//全部初始化为1
L[i] = 1;
for(int i=1; i<n; i++)
{
for(int j=0; j<i; j++)
{
if(A[i]>A[j] && L[i]<L[j]+1)//如果前面的数字小,且其对应长度没有前面那个数字对应长度长
L[i] = L[j]+1;
}
res = max(res,L[i]);
}
return res;
}
int main()
{
cin >> n;
for(int i=0; i<n; i++)
{
cin >> A[i];
}
cout << lis() << endl;
return 0;
}
方法二:O(nlogn)法
<span style="color:#00008b"><strong> </strong></span>
#include <iostream> #include <algorithm> using namespace std; #define MAX 100000 int n, A[MAX+1], L[MAX+1]; int lis() { L[0] = A[0]; int length = 1; for(int i=1; i<n; i++) { if(L[length-1] < A[i])//如果末尾元素比当前元素小,序列加长 L[length++] = A[i]; else //如果末尾元素大,则序列中按大小插入替换当前元素,序列长度不变 *lower_bound(L, L+length, A[i]) = A[i]; } return length; } int main() { cin >> n; for(int i=0; i<n; i++) { cin >> A[i]; } cout << lis() << endl; return 0; }
//如果末尾元素大,则序列中按大小插入替换当前元素,序列长度不变 *lower_bound(L, L+length, A[i]) = A[i]; } return length; } int main() { cin >> n; for(int i=0; i<n; i++) { cin >> A[i]; } cout << lis() << endl; return 0; }