POJ3903 Stock Exchange 最长上升子序列

Stock Exchange

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9901 Accepted: 3430
Description

The world financial crisis is quite a subject. Some people are more relaxed while others are quite anxious. John is one of them. He is very concerned about the evolution of the stock exchange. He follows stock prices every day looking for rising trends. Given a sequence of numbers p1, p2,…,pn representing stock prices, a rising trend is a subsequence pi1 < pi2 < … < pik, with i1 < i2 < … < ik. John’s problem is to find very quickly the longest rising trend.
Input

Each data set in the file stands for a particular set of stock prices. A data set starts with the length L (L ≤ 100000) of the sequence of numbers, followed by the numbers (a number fits a long integer).
White spaces can occur freely in the input. The input data are correct and terminate with an end of file.
Output

The program prints the length of the longest rising trend.
For each set of data the program prints the result to the standard output from the beginning of a line.
Sample Input

6
5 2 1 4 5 3
3
1 1 1
4
4 3 2 1
Sample Output

3
1
1

问题连接

问题描述

给了一组序列,求最长的上升子序列的长度。

问题分析

贪心算法+二分查找做法。因为数据较多,不能使用O(n2)的dp做法。这个算法的思想是子序列的最后一个元素越小,那么就越有可能得到一个更长的子序列。定义一个low数组,如果当前的数d[i]比low数组里最后一个数大(或者low数组为空)那么直接放到low数组最后面。否则,也就是不比它大,那么从low数组中找到第一个不小于d[i]的数,用d[i]替换它,由于low数组是单调递增的,所以找位置的时候可以用二分查找快速找到位置。最后low数组中元素的个数即为最大上升子序列的长度。

代码如下

#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+5;

int d[N];
int low[N];

int binary_search(int a[],int r,int x){//从a[]中,找到并返回第一个不小于x的下标
	int l=0;
	while(l<r){
		int mid=(l+r)/2;
		if(x>a[mid]) l=mid+1;
		else r=mid; 
	}
	return l;
}

int lis(int d[],int n){
	int ans,i;
	low[0]=d[0];
	ans=0;
	for(i=1;i<n;i++)
	if(d[i]>low[ans]) low[++ans]=d[i];
	else low[binary_search(low,ans,d[i])]=d[i];
	return ans+1;
} 

int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int n;
	while(cin>>n){
		for(int i=0;i<n;i++) cin>>d[i];
		cout<<lis(d,n)<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值