Advertisement
omar-alhelo

LIS (nlogn)

Jan 3rd, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #define MAX_N 100100
  2. int A[MAX_N], LIS[MAX_N];
  3. int get_LIS(int A[], int n, int LIS[]){
  4.   int L_idx[MAX_N], L_pre[MAX_N];
  5.   int len = 0;
  6.   int last = 0;
  7.   for(int i = 0 ; i<n ; i++){
  8.     // use upper_bound for longest non-decreasing sequence
  9.     int pos = lower_bound(LIS, LIS+len, A[i]) - LIS; //first element greater or equal to A[i], or the end if there's none.
  10.     LIS[pos] = A[i]; //LIS storest an increasing list with the same lenght of the actual LIS, but no necessarly the correct one.
  11.     L_idx[pos] = i;  //L_idx stores the index in the orginal array A of the element in LIS[k].
  12.     L_pre[i] = pos ? L_idx[pos -1] : -1; //L_pre[i] stores the index of the first previous element that is stricly smaller that A[i]
  13.     if(pos==len) len++, last=i;
  14.   }
  15.  
  16.   stack<int> s;
  17.   for( ; last!=-1 ; last=L_pre[last]) s.push(A[last]); //Tracing back LIS elements
  18.   for(int i=0 ; !s.empty() ; i++) LIS[i]=s.top(), s.pop(); //re-constructing LIS
  19.   return len;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement