bhupixb

Printing the longest Increasing Subsequence

Jan 14th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4.  
  5. using namespace std;
  6.  
  7. #define int long long
  8. #define F first
  9. #define S second
  10. #define rep(i,a,n) for (int i = a; i <= n; ++i)
  11. #define fo(i, n) for (int i = 1; i <= n; ++i)
  12. #define all(v) v.begin(), v.end()
  13. #define pb push_back
  14. #define P pair < int, int >
  15. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
  16. #define reno(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
  17. void err(istream_iterator<string> it) {}
  18.  
  19. template<typename T, typename... Args>
  20. void err(istream_iterator<string> it, T a, Args... args) {
  21. cout << *it << " = " << a << ' ';
  22. err(++it, args...);
  23. }
  24.  
  25. const int N = 1e3 + 5;
  26. int v[N], pre[N];
  27. vector < int > let;
  28. void fun(int x) {
  29. if(x == -1)
  30. return;
  31. fun(pre[x]);
  32. cout << v[x] << ' ';
  33. }
  34. signed main(){
  35. fast;
  36. int n;
  37. cin >> n;
  38. fo(i, n)
  39. cin >> v[i];
  40.  
  41. fo(i, n) {
  42. if(let.empty()) {
  43. let.pb(i);
  44. pre[i] = -1;
  45. }
  46. else if(v[i] < v[let[0]]){
  47. let[0] = i;
  48. pre[i] = -1;
  49. }
  50. else if(v[i] > v[let.back()]) {
  51. pre[i] = let.back();
  52. let.pb(i);
  53. }
  54. else {
  55. int lo = 0, hi = let.size(), mid;
  56. while(lo <= hi) {
  57. mid = lo + hi >> 1;
  58. if(v[let[mid]] >= v[i])
  59. hi = mid - 1;
  60. else
  61. lo = mid + 1;
  62. }
  63. let[hi + 1] = i;
  64. if(hi + 1)
  65. pre[let[hi+1]] = let[hi];
  66. }
  67.  
  68. }
  69. fun(let.back());
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93. return 0;
  94. }
Add Comment
Please, Sign In to add comment