Ai
1 Star 0 Fork 0

JJustRight/ACM-ICPC-Algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LIS_(nlogn).cpp 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
ayush268 提交于 2017-10-28 03:40 +08:00 . Added algo for LIS - O(N log N)
#include <iostream>
#include <vector>
using namespace std;
// Binary search (note boundaries in the caller)
int index(vector<int> &v, int l, int r, int key) {
while (r-l > 1) {
int m = l + (r-l)/2;
if (v[m] >= key)
r = m;
else
l = m;
}
return r;
}
int LIS(vector<int> &v) {
if (v.size() == 0)
return 0;
vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (size_t i = 1; i < v.size(); i++) {
if (v[i] < tail[0])
// new smallest value
tail[0] = v[i];
else if (v[i] > tail[length-1])
// v[i] extends largest subsequence
tail[length++] = v[i];
else
// v[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than v[i]
// (and also, v[i] would have already appeared in one of LIS, identify the location and replace it)
tail[index(tail, -1, length-1, v[i])] = v[i];
}
return length;
}
int main() {
vector<int> v{ 2, 5, 3, 7, 11, 8, 10, 13, 6 };
cout << "Length of Longest Increasing Subsequence is " << LIS(v) << endl;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/jjustright/ACM-ICPC-Algorithms.git
git@gitee.com:jjustright/ACM-ICPC-Algorithms.git
jjustright
ACM-ICPC-Algorithms
ACM-ICPC-Algorithms
master

搜索帮助