4eyes4u

LIS | LNDS

Mar 29th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. /*
  2. Name: Longest increasing/non-decreasing subsequence + reconstruction
  3. Complexity: O(NlogN)
  4. */
  5.  
  6. #include <bits/stdc++.h>
  7. using namespace std;
  8.  
  9. const int N=1e5+10;
  10.  
  11. int n, x, f[N];
  12. vector<int> v, sol;
  13.  
  14. void add (int x)
  15. {
  16.     int w=lower_bound(v.begin(), v.end(), x)-v.begin(); //lower <==> LIS; upper <==> LNDS
  17.  
  18.     if (w==0) v.push_back(x);
  19.     else if (w<v.size())
  20.     {
  21.         if (x<v[w])
  22.         {
  23.             v[w]=x;
  24.             f[x]=v[w-1];
  25.         }
  26.     }
  27.     else
  28.     {
  29.         v.push_back(x);
  30.         f[x]=v[w-1];
  31.     }
  32. }
  33.  
  34. void LIS (int x) //reconstruction
  35. {
  36.     sol.push_back(x);
  37.     if (f[x]) LIS (f[x]);
  38. }
  39.  
  40. int main()
  41. {
  42.     scanf ("%d", &n);
  43.     for (int i=0; i<n; i++)
  44.     {
  45.         scanf ("%d", &x);
  46.         add (x);
  47.     }
  48.  
  49.     LIS (v.back());
  50.     printf ("%d\n", v.size());
  51.     for (int i=sol.size()-1; i>=0; i--) printf ("%d ", sol[i]);
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment