下面两题异曲同工;
主要思想:建立一个用来储存最长上升子序列的数组 d[] (第一个元素设为目标数组第一个元素),逐个遍历所有元素,比较目标值与 d[] 数组中最后一个值比较大小。如果大于 d[] 数组,则直接填入 d[] 数组,不然就用 lower_bound()找到第一个大于目标值的下标并替换。时间复杂度就为 O( nlog(n) );
题目:
一个数的序列 bi,当 b1 < b2 < ... < bS的时候,我们称这个序列是上升的。对于给定的一个序列( a1, a2, ..., aN),我们可以得到一些上升的子序列( ai1, ai2, ..., aiK),这里1 <= i1 < i2 < ... < iK <= N。比如,对于序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。这些子序列中最长的长度是4,比如子序列(1, 3, 5, 8).
你的任务,就是对于给定的序列,求出最长上升子序列的长度。
Input
输入的第一行是序列的长度N (1 <= N <= 1000)。第二行给出序列中的N个整数,这些整数的取值范围都在0到10000。
Output
最长上升子序列的长度。
Sample Input
7 1 7 3 5 9 4 8
Sample Output
4
代码附上(时间复杂度 nlog(n)):
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5+10;
const int INF =0x3f3f3f3f;
int d[maxn],a[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
cin>>a[i];
}
d[1] = a[1];
int len =1;
for(int i =2; i <= n; i++)
{
if(a[i] > d[len])
d[++len] = a[i];
else
{
int j = lower_bound(d+1,d+1+len,a[i])-d; //返回下标
d[j] = a[i];
}
}
cout<<len<<endl;
}
某国为了防御敌国的导弹袭击,开发出一种导弹拦截系统。但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。某天,雷达捕捉到敌国的导弹来袭,并观测到导弹依次飞来的高度,请计算这套系统最多能拦截多少导弹。拦截来袭导弹时,必须按来袭导弹袭击的时间顺序,不允许先拦截后面的导弹,再拦截前面的导弹。
Input
输入有两行,
第一行,输入雷达捕捉到的敌国导弹的数量k(k<=25),
第二行,输入k个正整数,表示k枚导弹的高度,按来袭导弹的袭击时间顺序给出,以空格分隔。
Output
输出只有一行,包含一个整数,表示最多能拦截多少枚导弹。
Sample Input
8 300 207 155 300 299 170 158 65
Sample Output
6
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5+10;
const int INF =0x3f3f3f3f;
int d[maxn],a[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
cin>>a[i];
d[1] = a[1];
int len =1;
for(int i =2; i <= n; i++)
{
if(a[i] <= d[len])
d[++len] = a[i];
else
{
int j = upper_bound(d+1,d+1+len,a[i],greater<int>() )-d; //返回下标
d[j] = a[i];
}
}
cout<<len<<endl;
return 0;
}