1134 最长递增子序列
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
给出长度为N的数组,找出这个数组的最长递增子序列。(递增子序列是指,子序列的元素是递增的)
例如:5 1 6 8 2 4 5 10,最长递增子序列是1 2 4 5 10。
Input
第1行:1个数N,N为序列的长度(2 <= N <= 50000)
第2 - N + 1行:每行1个数,对应序列的元素(-10^9 <= S[i] <= 10^9)
Output
输出最长递增子序列的长度。
Input示例
8
5
1
6
8
2
4
5
10
Output示例
5
思路:
维护一个数组,数组下标为子序列长度,数组保存的值为该长度的子序列最小的数
将原序列不断加入到该数组中,遇到第一个小于原序列当前元素的值后,将后一个的值替换
注意元素可能为负
代码:
/*************************************************************************
> File Name: lis.cpp
> Author: SIU
> Created Time: 2016年11月21日 星期一 16时48分28秒
************************************************************************/
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int num[50050];
int main()
{
int n;
scanf("%d",&n);
int str[50050];
int len=0;
int max=0;
for(int i=1;i<=n;i++)
scanf("%d",&str[i]);
for(int i=0;i<=n;i++)
num[i]=-9999999999;
for(int i=1;i<=n;i++)
{
if(len==0)
{
len++;
num[i]=str[i];
if(len>max)
max=len;
}
else
{
for(int j=len;j>=0;j--)
{
if(str[i]>num[j])
{
num[j+1]=str[i];
if(j+1>len)
len=j+1;
if(len>max)
max=len;
break;
}
}
}
}
printf("%d\n",max);
return 0;
}