Longest Increasing Subsequence 2
#include <iostream> #include <vector> using namespace std; /* Finds longest strictly increasing subsequence. O(n log k) algorithm. */ void find_lis(vector<int> &a, vector<int> &b) { vector<int> p(a.size()); int u,v; if(a.empty()) return; b.push_back(0); for(int i=1; i<a.size(); i++) { // Add element to LIS if(a[b.back()]<a[i]) { p[i] = b.back(); b.push_back(i); continue; } // Binary Search in current LIS an index u which is an element just larger than a[i] for(u=0,v=b.size()-1; u<v;) { int c = (u+v)/2; if(a[b[c]]<a[i]) u = c+1; else v = c; } // If u is found, then update if(a[i]<a[b[u]]) { if (u > 0) p[i] = b[u-1]; b[u] = i; } } for (u = b.size(), v = b.back(); u--; v = p[v]) b[u] = v; } int main() { int a[] = {10,22,11,2,4,91,17,18,21,41,8}; vector<int> seq(a, a+sizeof(a)/sizeof(a[0])); vector<int> lis; find_lis(seq, lis); for (int i = 0; i < lis.size(); i++) cout<<seq[lis[i]]<<" "; return 0; }
No comments yet.
Leave a comment