求最长上升子序列的nlogn解法

题目链接

https://www.luogu.org/problemnew/show/P1020

题意

非常经典的导弹拦截问题。
第一问是求最长不下降子序列;
第二问是求最长下降子序列。

题解1(DP)

这是个n^2的做法,具体的递推公式是:
若a[j]>=a[i],则dp[i] = max(dp[i],dp[j]+1), 0<=j<i。
这里就不详细叙述了。

代码1

for(int i=0;i<n;i++) {
		for(int j=0;j<i;j++) {
			if(a[i]<=a[j])
				dp[i] = max(dp[i],dp[j]+1);
			if(a[i]>a[j])
				f[i] = max(f[i],f[j]+1);	
		}
	}

题解2

以第一问为例,我们维护一个单调递减的序列f。
假设输入样例为389 207 155 300 299 170 158 65。
那么我们依次遍历,如果当前数比f的最后一个数还要小(或相等),那么就把它插入这个序列;否则,我们就二分查找序列中第一个比它小的位置,用当前数去替换那个位置的数。
这样做的正确性可以自己模拟一下来证明。

代码2

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <cmath>
using namespace std;

#define INIT(x) memset(x,0,sizeof(x))
#define eps 1e-8
#define next next_
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x7fffffff;
const int inf = 0x3f3f3f3f;
const int maxn = 200005;
const int N = 105;

inline void read(int &x) {
    int f=1;x=0;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}

int a[maxn],n,f[maxn],dp[maxn];
bool cmp(int x,int y) {return x>y;}

int main() {
	while(cin>>a[n++]);
	n--;
	int cnt1 = 0, cnt2 = 0;
	f[0] = dp[0] = a[0];
	for(int i=1;i<n;i++) {
		if(a[i]<=dp[cnt1]) dp[++cnt1] = a[i];
		else dp[upper_bound(dp,dp+cnt1,a[i],greater<int>())-dp] = a[i];
		if(a[i]>f[cnt2]) f[++cnt2] = a[i];
		else f[lower_bound(f,f+cnt2,a[i])-f] = a[i];
	}
	cout<<cnt1+1<<endl<<cnt2+1<<endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

总想玩世不恭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值