最大上升子序列。dp + 二分优化。用正常求最大上升子序列的算法时间复杂度是O( n * n )。 二分优化后的时间复杂度为O(nlogn)。数据较大,正常求TLE。(没想到数据这么大,我就一直TLE )。用num[i]记录长度为i的LIS最小的元素的位置,最后的i则为LIS。用path[i]数组记录路径。即data[i]大于0~i - 1 中最后一个元素的位置。计算过程中,如果当前元素大于队列中最后一个元素,则直接加入队尾,否则替换之前长度相同的LIS的结尾元素(类似贪心)。最后递归调用输出。
// File Name: UVa481.cpp
// Author: Toy
// Created Time: 2013年03月16日 星期六 09时05分27秒
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#define L(x) x << 1
#define R(x) x << 1 | 1
using namespace std;
int data[100000], path[100000], num[100000];
void out ( int ipo ) {
if ( path[ipo] ) out ( path[ipo] );
printf ( "%d\n", data[ipo] );
}
int bs ( int r, int v ) {
int l = 1;
while ( l < r ) {
int mid = ( l + r ) / 2;
if ( data[num[mid]] < v ) l = mid + 1;
else r = mid;
}
return r;
}
int main ( ) {
int count = 1, id;
while ( scanf ( "%d", &data[count] ) != EOF )
count++;
int tail = 0;
num[++tail] = 1;
for ( int i = 2; i < count; ++i ) {
if ( data[num[tail]] < data[i] ) num[++tail] = i, path[i] = num[tail - 1];
else id = bs ( tail, data[i] ), num[id] = i, path[i] = num[id - 1];
}
printf ( "%d\n-\n", tail );
out ( num[tail] );
return 0;
}