Last active
March 22, 2019 13:54
-
-
Save lnikon/8406d0dd1bbeab41f9aca9b581761c72 to your computer and use it in GitHub Desktop.
Longest Increasing subsequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
#include <iterator> | |
template <class ForwardIterator, class Comp = std::less<>> | |
auto lis(ForwardIterator begin, | |
ForwardIterator end, | |
Comp comp = Comp()) { | |
const auto length = std::distance(begin, end); | |
auto maxs = std::vector<size_t>(length, 1); | |
for(auto newBegin{begin}; newBegin != end; ++newBegin) { | |
auto fromBeginToNewBegin = std::distance(begin, newBegin); | |
for(auto beginCopy {begin}; beginCopy != newBegin; ++beginCopy) { | |
auto fromBeginToBeginCopy = std::distance(begin, beginCopy); | |
if(comp(*beginCopy, *newBegin)) { | |
maxs[fromBeginToNewBegin] | |
= std::max( maxs[fromBeginToNewBegin], | |
maxs[fromBeginToBeginCopy] + 1); | |
} | |
} | |
} | |
return *std::max_element(std::begin(maxs), std::end(maxs)); | |
} | |
int main() | |
{ | |
auto seq = std::vector<int>{6, 2, 10, 0, 8, 4, 12, 1, 7, 3, 11, 1, 9, 5, 13}; | |
auto lisLen = lis(std::begin(seq), std::end(seq)); | |
std::cout << "lisLen: " << lisLen << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment