Pagini recente » Cod sursa (job #1229690) | Cod sursa (job #1229291) | Cod sursa (job #2138259) | Cod sursa (job #3128420) | Cod sursa (job #2135495)
// C++ implementation to find longest increasing subsequence
// in O(n Log n) time.
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream in("scmax.in");
ofstream out("scmax.out");
// Binary search
int GetCeilIndex(int arr[], vector<int> &T, int l, int r,
int key)
{
while (r - l > 1)
{
int m = l + (r - l)/2;
if (arr[T[m]] >= key)
r = m;
else
l = m;
}
return r;
}
void lis(int arr[], int n)
{
vector<int> tailIndices(n, 0); // Initialized with 0
vector<int> prevIndices(n, -1); // initialized with -1
int len = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] < arr[tailIndices[0]])
tailIndices[0] = i;
else if (arr[i] > arr[tailIndices[len-1]])
{
prevIndices[i] = tailIndices[len-1];
tailIndices[len++] = i;
}
else
{
int pos = GetCeilIndex(arr, tailIndices, -1,
len-1, arr[i]);
prevIndices[i] = tailIndices[pos-1];
tailIndices[pos] = i;
}
}
out << len<<"\n";
for (int i = tailIndices[len-1]; i >= 0; i = prevIndices[i])
out << arr[i] << " ";
}
int main()
{
int *arr;;
int n ;
in >> n;
arr = new int[n+1];
for(int i = 0 ; i < n ; i++)
in>>arr[i];
lis(arr, n);
return 0;
}