From eb6db42fac506c1a7597e5256c43301ebb55a8ab Mon Sep 17 00:00:00 2001 From: John Law Date: Tue, 8 Oct 2019 23:58:49 +0800 Subject: [PATCH] Update Longest Increasing Subsequence (nlogn).cpp --- ...Longest Increasing Subsequence (nlogn).cpp | 65 ++++++++++--------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp index eaf28ff8c..56dcca969 100644 --- a/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp +++ b/Dynamic Programming/Longest Increasing Subsequence (nlogn).cpp @@ -3,37 +3,44 @@ // tested on : https://cses.fi/problemset/task/1145/ #include + using namespace std; int LIS(int arr[], int n) { - set active; // The current built LIS. - active.insert(arr[0]); - // Loop through every element. - for(int i=1; i arr[i] ){ - // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; - active.erase(get); - active.insert(arr[i]); - } - } - } - return active.size(); // size of the LIS. -} -int main(int argc, char const *argv[]) -{ - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) + set < int > active; // The current built LIS. + active.insert(arr[0]); + // Loop through every element. + for (int i = 1; i < n; ++i) + { + auto get = active.lower_bound(arr[i]); + if (get == active.end()) { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; + 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 + if (val > arr[i]) + { + // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + active.erase(get); + active.insert(arr[i]); + } + } + } + return active.size(); // size of the LIS. +} +int main(int argc, char const * argv[]) +{ + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; }