NP-Nidzo

Longest Increasing Subsequence - O( n*log(n) )

Aug 14th, 2020
1,633
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1.  
  2. /**------------------------
  3.     Author : NikolaP
  4.     Compiler : C++
  5. -------------------------*/
  6.  
  7. //{         Setup
  8.  
  9.     #include <bits/stdc++.h>
  10.     using namespace std;
  11.  
  12.     typedef long long int ll;
  13.     typedef long double ld;
  14.     typedef vector<int> vi;
  15.  
  16.     const int inf = INT_MAX;
  17.     const bool debug = 0;
  18.  
  19. //}
  20.  
  21.  
  22. int lis(vi& v){
  23.     int n = v.size();
  24.     vi dp(n+1,inf);
  25.  
  26.     dp[0] = -inf;
  27.  
  28.     for(int i=0; i < n; ++i){
  29.         int idx = upper_bound(dp.begin(), dp.end(),v[i]) - dp.begin();
  30.        
  31.         if(dp[idx-1] < v[i] and v[i] < dp[idx])
  32.             dp[idx] = v[i];
  33.     }
  34.  
  35.     int ans = 0;
  36.     for(int i = 0; i <= n; ++i){
  37.         if(dp[i] < inf) ans = i;
  38.     }
  39.  
  40.     return ans;
  41. }
  42.  
  43. int main()
  44. {
  45.     ios::sync_with_stdio(false);
  46.     cin.tie(0);
  47.     cout.precision(8);
  48.     //cout << fixed;
  49.  
  50.     vi v = {1,2,3,4,5};
  51.     cout << lis(v);
  52.     return 0;
  53. }
  54.  
  55.  
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment