Advertisement
Oibek

LIS O(nlogn)

Nov 28th, 2018
1,170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5.  
  6. ll n;
  7. ll arr[100005], L[100005];
  8. ll I[100005]; // last elements of sequence of i-th length
  9.  
  10. const ll inf = 10000000000;
  11.  
  12. int main()
  13. {
  14.     cin >> n;
  15.     for (int i = 0; i<n; i++)
  16.         cin >> arr[i];
  17.  
  18.     I[0] = -inf;
  19.     for (int i = 1; i<=n; i++)
  20.         I[i] = inf;
  21.  
  22.     ll maxLength = 0, pos = -1;
  23.  
  24.     for (int i = 0; i<n; i++)
  25.     {
  26.         ll l = 0, r = maxLength;
  27.         while (l <= r)
  28.         {
  29.             ll mid = (l+r)/2;
  30.             if (I[mid] < arr[i])
  31.                 l = mid+1;
  32.             else r = mid-1;
  33.         }
  34.  
  35.         I[l] = arr[i];
  36.         L[i] = l;
  37.         if (l > maxLength)
  38.         {
  39.             maxLength = l;
  40.             pos = i;
  41.         }
  42.     }
  43.  
  44.     cout << maxLength << endl;
  45.     deque <ll> ans;   // reconstructing results
  46.     ans.push_front(arr[pos]);
  47.  
  48.     for (int j = pos-1; j>=0; j--)
  49.     {
  50.         if (arr[j] < arr[pos] and L[j] == L[pos]-1)
  51.         {
  52.             ans.push_front(arr[j]);
  53.             pos = j;
  54.         }
  55.     }
  56.    
  57.     for (int i = 0; i<ans.size(); i++)
  58.         cout << ans[i] << " ";
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement