基准时间限制: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
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
long long a[50010];
long long b[50010];
int main()
{
int n;
cin>>n;
scanf("%lld",&a[1]);
int cot=1;
for(int i=2;i<=n;i++)
{
long long t;
scanf("%lld",&t);
if(t>a[cot])
{
a[++cot]=t;
}
else
{
a[upper_bound(a+1,a+cot,t)-a]=t;
}
}
printf("%d\n",cot);
return 0;
}
代码实现upper_bound
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
long long a[50010];
long long b[50010];
int binary(int l,int r,int num)
{
while(l<=r)
{
int mid=(l+r)>>1;
if(a[mid]<=num)
l=mid+1;
else
r=mid-1;
}
return l;
}
int main()
{
int n;
cin>>n;
scanf("%lld",&a[1]);
int cot=1;
for(int i=2;i<=n;i++)
{
long long t;
scanf("%lld",&t);
if(t>a[cot])
{
a[++cot]=t;
}
else
{
a[binary(1,cot,t)]=t;
}
}
printf("%d\n",cot);
return 0;
}