【模板】最长上升子序列

一、O(n2)

#include <cstdio>
#define max(a, b) ((a) > (b) ? a : b)
const int N = 1005;
int dp[N], a[N], n;
int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	int ans = 1;
	dp[1] = 1;
	for (int i = 2; i <= n; i++) {
		for (int j = 1; j < i; j++) {
			if (a[i] > a[j]) {
				dp[i] = max(dp[i], dp[j] + 1);
			} else {
				dp[i] = max(dp[i], 1);
			}
		}
		printf("%d--%d\n", dp[i], i);
		ans = max(ans, dp[i]);
	}
	printf("%d", ans);
	return 0;
}

二、O(nlogn)

#include <cstdio>
#include <iostream>
using namespace std;
const int N = 100005;
int f[N], n, rec[N], cnt = 1;
//返回大于等于的下标 
int search(int l, int r, int x) {
	while (l < r) {
		int mid = (l + r) >> 1;
		if (f[mid] >= x) {
			r = mid;
		} else {
			l = mid + 1;
		}
	}
	//判断最后一个是否小于它 
	if (r == cnt - 1 && f[l] < x) {
	    return cnt++;
	}
	return l;
}
int main() {
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", rec + i); 
	} 
	f[0] = 0x7f7f7f7f;//存一个最大的 
	for (int i = 0; i < n; i++) {
		int t = search(0, cnt - 1, rec[i]);
		f[t] = rec[i]; 	
	} 
	printf("%d\n", cnt);
	return 0;
}
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页