|
| 1 | +/* |
| 2 | +Longest Increasing Subsequence |
| 3 | +Complexity for LIS Algo -> O(NlogN) |
| 4 | +N-number of elements |
| 5 | +*/ |
| 6 | + |
| 7 | +#include<bits/stdc++.h> |
| 8 | +using namespace std; |
| 9 | + |
| 10 | +// NOTE : aux is not necesserily the LIS but its length is same as LIS |
| 11 | +int length_LIS(int arr[], int n) |
| 12 | +{ |
| 13 | + vector<int> aux; //auxiliary vector stores the array elements likely to be LIS |
| 14 | + for(int i = 0; i < n; i++) |
| 15 | + { |
| 16 | + // Change lower_bound to upper_bound for non-decreasing subsequence |
| 17 | + auto itr = lower_bound(aux.begin(), aux.end(), arr[i]); |
| 18 | + if (itr == aux.end()) |
| 19 | + aux.push_back(arr[i]); // No element is larger than arr[i] |
| 20 | + else |
| 21 | + *itr = arr[i]; // replace the element in aux with elemwnt just smaller than it. |
| 22 | + } |
| 23 | + return aux.size(); |
| 24 | + |
| 25 | +} |
| 26 | + |
| 27 | +void find_LIS(int arr[],int n) |
| 28 | +{ |
| 29 | + vector<int> aux(n, 0); |
| 30 | + vector<vector<int>> parent(n); |
| 31 | + |
| 32 | + aux[0] = arr[0]; |
| 33 | + |
| 34 | + parent[0].push_back(arr[0]); |
| 35 | + int aux_size = 1; |
| 36 | + for (int i = 1; i < n; i++) |
| 37 | + { |
| 38 | + |
| 39 | + auto it =lower_bound(aux.begin(), aux.begin() + aux_size, arr[i]); |
| 40 | + |
| 41 | + if (it == aux.begin() + aux_size) |
| 42 | + { |
| 43 | + aux[aux_size] = arr[i]; |
| 44 | + |
| 45 | + parent[aux_size] = parent[aux_size - 1]; |
| 46 | + parent[aux_size].push_back(arr[i]); |
| 47 | + aux_size++; |
| 48 | + } |
| 49 | + else |
| 50 | + { |
| 51 | + if (*it != arr[i]) { |
| 52 | + aux[it- aux.begin()] = arr[i]; |
| 53 | + |
| 54 | + parent[it - aux.begin()][parent[it - aux.begin()].size() - 1] = arr[i]; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + cout << "length " << aux_size << endl; |
| 61 | + |
| 62 | + for (auto x : parent[aux_size - 1]) { |
| 63 | + cout << x << " "; |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +int main() |
| 68 | +{ |
| 69 | + int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 }; |
| 70 | + int n= sizeof(arr)/sizeof(int); |
| 71 | + |
| 72 | + // Strictly increasing sub sequence |
| 73 | + cout << "Length of LIS is :" << length_LIS(arr,n) << endl; |
| 74 | + |
| 75 | + // Print the LIS |
| 76 | + find_LIS(arr,n); |
| 77 | +} |
| 78 | + |
| 79 | +// Intersting question : |
| 80 | +// Given arr1[N], arr2[M] 1<M<N<10^5 |
| 81 | +// Find minimum elements you need to add in arr1 such that arr2 is a subsequence of arr1? |
| 82 | +// Soln: Codenation 1 april 2020 : hint(use maps, LIS) |
0 commit comments