UVa481 - What Goes Up

最大上升子序列。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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值