Advertisement
El_GEMMY

Playing with sequences

May 18th, 2022
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5. #define nl '\n'
  6.  
  7. void solve(){
  8.     int n; cin >> n;
  9.     vector<int> v(n);
  10.     for(auto& i : v)
  11.         cin >> i;
  12.  
  13.     vector<vector<int>> dp(n + 1, vector<int>(2, 1));
  14.  
  15.     // dp[i][0] -> longest sequence ending here with a bigger previous
  16.     // dp[i][1] -> //       //        //   //   //     smaller //
  17.  
  18.     vector<vector<int>> prev(n + 1, vector<int>(2, -1));
  19.  
  20.     for(int i = 1; i <= n; i++){
  21.         for(int j = i - 1; j >= 1; j--){
  22.             if(v[j - 1] < v[i - 1] and dp[j][0] + 1 > dp[i][1]){
  23.                 dp[i][1] = dp[j][0] + 1;
  24.                 prev[i][1] = j;
  25.             }
  26.  
  27.             if(v[j - 1] > v[i - 1] and dp[j][1] + 1 > dp[i][0]){
  28.                 dp[i][0] = dp[j][1] + 1;
  29.                 prev[i][0] = j;
  30.             }
  31.         }
  32.     }
  33.  
  34.     int ans = 0;
  35.     for(auto& i : dp){
  36.         ans = max(ans, *max_element(i.begin(), i.end()));
  37.     }
  38.  
  39.     int st = -1;
  40.     bool dir;
  41.     for(int i = n; i >= 0; i--){
  42.         if(dp[i][0] == ans){
  43.             st = i;
  44.             dir = false;
  45.             break;
  46.         }
  47.         if(dp[i][1] == ans){
  48.             st = i;
  49.             dir = true;
  50.             break;
  51.         }
  52.     }
  53.  
  54.  
  55.     stack<int> path;
  56.     path.push(v[st - 1]);
  57.  
  58.     while(prev[st][dir] != -1){
  59.         path.push(v[prev[st][dir] - 1]);
  60.         st = prev[st][dir];
  61.         dir = not dir;
  62.     }
  63.  
  64.     cout << ans << nl;
  65.     while(not path.empty()){
  66.         cout << path.top() << ' ';
  67.         path.pop();
  68.     }
  69. }
  70.  
  71. int main(){
  72. //    freopen("collector.in", "r", stdin);
  73. //    freopen("input.txt", "r", stdin);
  74. //    freopen("output.txt", "w", stdout);
  75.  
  76.     int t = 1;
  77. //    cin >> t;
  78.     while(t--){
  79.  
  80.         solve();
  81.         if(t)
  82.             cout << nl;
  83.     }
  84.  
  85.     return 0;
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement