最长上升子序列
题意:给定N个整数,请你求出最长上升子序列的个数
思路:设dp[ i ] 表示以
a
i
a_i
ai为终点的最长上升子序列的长度
d
p
[
i
]
=
m
a
x
(
d
p
[
j
]
,
1
≤
j
<
i
且
a
j
<
a
i
)
dp[i]=max(dp[j],1\leq j<i 且 a_j<a_i)
dp[i]=max(dp[j],1≤j<i且aj<ai)
时间复杂度:O( n 2 n^2 n2)
#include <iostream>
#include <algorithm>
#include <cstdio>
#define rep(i,a,b) for (int i=a; i<=b; ++i)
#define mes(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn=1000+5,INF=0x3f3f3f3f;
const int mod=1e9+7;
int n,a[maxn],dp[maxn];
int main()
{
cin>>n;
rep(i,1,n)
cin>>a[i];
rep(i,1,n)
dp[i]=1;
for(int i=2;i<=n;++i)
for(int j=1;j<i;++j)
if(a[j]<a[i])
dp[i]=max(dp[j]+1,dp[i]);
cout<<*max_element(dp+1,dp+1+n)<<endl;
return 0;
}
P1020 导弹拦截
题意:求最长不上升子序列长度和最长上升子序列的长度
思路:贪心+二分。
方法:求最长不上升子序列的时候,我们维护下个类似单调栈 的非降序列(可以取等于)。遍历a数组,当
s
t
a
c
k
[
t
o
p
]
>
=
a
[
i
]
stack[top]>=a[i]
stack[top]>=a[i]时,直接入栈,如果
s
t
a
c
k
[
t
o
p
]
<
a
[
i
]
stack[top]<a[i]
stack[top]<a[i]那么就在stack中找到第一个小于
a
[
i
]
a[i]
a[i]的数,换成
a
[
i
]
a[i]
a[i]。求最长上升子序列的时候也是同样的方法
分析:
1、 为什么是求最长上升子序列呢?
每一个导弹最终的结果都是要被打的,如果它后面有一个比它高的导弹,那打它的这个装置无论如何也不能打那个导弹了,也就是说最少要打最长上升子序列长度那么多次可以打完!
2、为什么这样贪心是正确的?
假设被替换的数x位于末尾,那么被换成更大的a[i]之后,在a[i]后面就可以接更长的子序列。假如被替换的x位于中间,那么把它替换成更大的数a[i]也是对答案无影响的。但是如果不替换,是会出错的。假设有一种情况是将原本的序列从当前x开始替换,一直换到序列末尾。那么这个新的序列会有更高的上限(序列的最后一个元素更大了 ),这样也就可以接更长的子序列了
其实对于下降序列来说,就是想维护一个下降更平缓的序列(最后一个元素越大序列越长)。对于求上升子序列的操作,就是为了维护一个上升更慢的序列(最后一个元素越小序列越长)
时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <string>
#include <cmath>
#define rep(i,a,b) for (int i=a; i<=b; ++i)
#define per(i,b,a) for (int i=b; i>=a; --i)
#define mes(a,b) memset(a,b,sizeof(a))
#define mp make_pair
#define ll long long
#define pb push_back
#define ls (rt<<1)
#define rs ((rt<<1)|1)
#define isZero(d) (abs(d) < 1e-8)
using namespace std;
const int maxn=1e5+5,INF=0x3f3f3f3f;
int a[maxn];
int stack1[maxn],stack2[maxn];
int main()
{
int n=1;
while(cin>>a[n])
n++;
n--;
int top1=1,top2=1;
stack1[1]=stack2[1]=a[1];
rep(i,2,n)
{
if(stack1[top1]>=a[i])
stack1[++top1]=a[i];
else
{
int p=upper_bound(stack1+1,stack1+1+top1,a[i],greater<int>())-stack1;
stack1[p]=a[i];
}
if(stack2[top2]<a[i])
stack2[++top2]=a[i];
else
{
int p=lower_bound(stack2+1,stack2+1+top2,a[i])-stack2;
stack2[p]=a[i];
}
}
cout<<top1<<"\n"<<top2<<"\n";
return 0;
}