mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Update Longest Increasing Subsequence (nlogn).cpp
This commit is contained in:
parent
c45683bb8c
commit
eb6db42fac
@ -3,18 +3,25 @@
|
|||||||
// tested on : https://cses.fi/problemset/task/1145/
|
// tested on : https://cses.fi/problemset/task/1145/
|
||||||
|
|
||||||
#include <bits/stdc++.h>
|
#include <bits/stdc++.h>
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
int LIS(int arr[], int n)
|
int LIS(int arr[], int n)
|
||||||
{
|
{
|
||||||
set < int > active; // The current built LIS.
|
set < int > active; // The current built LIS.
|
||||||
active.insert(arr[0]);
|
active.insert(arr[0]);
|
||||||
// Loop through every element.
|
// Loop through every element.
|
||||||
for(int i=1; i<n; ++i){
|
for (int i = 1; i < n; ++i)
|
||||||
|
{
|
||||||
auto get = active.lower_bound(arr[i]);
|
auto get = active.lower_bound(arr[i]);
|
||||||
if( get == active.end() ){ active.insert(arr[i]); } // current element is the greatest so LIS increases by 1.
|
if (get == active.end())
|
||||||
else{
|
{
|
||||||
|
active.insert(arr[i]);
|
||||||
|
} // current element is the greatest so LIS increases by 1.
|
||||||
|
else
|
||||||
|
{
|
||||||
int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing
|
int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing
|
||||||
if( val > arr[i] ){
|
if (val > arr[i])
|
||||||
|
{
|
||||||
// else we remove the bigger element and add a smaller element (which is arr[i]) and continue;
|
// else we remove the bigger element and add a smaller element (which is arr[i]) and continue;
|
||||||
active.erase(get);
|
active.erase(get);
|
||||||
active.insert(arr[i]);
|
active.insert(arr[i]);
|
||||||
|
Loading…
Reference in New Issue
Block a user