51node 1134 最长递增子序列 (数据结构)

题意:

最长递增子序列

思路:

普通的$O(n^2)$的会超时。。

然后在网上找到了另一种不是dp的写法,膜拜一下,自己写了一下解释

来自:https://blog.csdn.net/Adusts/article/details/80764782

代码:

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
	int n = 0, buf = 0, max = 0;
	scanf("%d", &n);
	vector<int>a;
	vector<int>::iterator it;//迭代器,像指针一样的东西 
	while(n--) {
		scanf("%d", &buf);
		if((it = upper_bound(a.begin(), a.end(), buf)) == a.end()) {
		//upper_bound返回第一个大于buf的数字的位置,这里判断新数字buf是不是比vector中所有的值大 
			a.push_back(buf);//如果是最大值,push进去 
			max++;//结果加1 
		} else {
			*it = buf;//这个的意思是很重要
			//在上面用过一次it,返回的值一直保存在it中,现在*it是一个指针,可以改变当前内存中的值
			//重新赋值为buf,覆盖原来的值
			//为什么这么做呢,例如输入5个数字,5,6,1,2,3,很明显答案是3,5和6都去掉 
			//if很好理解,碰到大数就加到vector中,第一次触发else是输入1的时候,it指向5,把5替换为1,下一次触发把6替换为2,然后push(3)
			//每次替换一个不会影响结果 
		}
	}
	printf("%d
", max);
	return 0;
}

原文地址:https://www.cnblogs.com/somliy/p/9774502.html