#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>
#include <iomanip>
#include <vector>
#include <stdio.h>
#define fori(i, n) for (int i = 0; i < (n); i++)
using namespace std;
// Longest Increasing Subsequence - LIS O(n log n)
// Fonte: http://www.maratona.dcc.ufmg.br/UFMG-TRD-2011.pdf
// Adaptado por: Jonatas Laet
void lis( const vector< int > & v, vector< int > & asw )
{
vector<int> pd(v.size(), 0), pd_index(v.size()), pred(v.size());
int maxi = 0, x, j, ind;
fori(i, v.size())
{
x = v[i];
j = lower_bound( pd.begin(), pd.begin() + maxi, x ) - pd.begin();
pd[j] = x;
pd_index[j] = i;
if( j == maxi )
{
maxi++;
ind = i;
}
pred[i] = j ? pd_index[j - 1] : -1;
} // return maxi;
int pos = maxi - 1, k = v[ind];
asw.resize( maxi );
while ( pos >= 0 )
{
asw[pos--] = k;
ind = pred[ind];
k = v[ind];
}
}
int main(int argc, char *argv[])
{
vector< int > v; //8, 4, 1, 2, 3, 0, 5, 7, 8
vector< int > v2;
v.push_back(8);
v.push_back(4);
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(0);
v.push_back(5);
v.push_back(7);
v.push_back(8);
lis(v, v2);
int t = v2.size();
//Mostrando o vetor com os valores da maior subsequencia crescente
fori(i, t)
{
printf("%d ", v2[i]);
}
printf("\n");
//Mostrando o tamanho desse vetor
printf("%d\n", v2.size());
return 0;
}
Mais informações sobre como funciona o Longest Increasing Sequence: https://en.wikipedia.org/wiki/Longest_increasing_subsequence
↧