knightL

MinMaxQueue

Nov 1st, 2024 (edited)
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string>
  3. #include <cstring>
  4. #include <utility>
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <vector>
  8. #include <algorithm>
  9. #include <numeric>
  10. #include <cassert>
  11. #include <stack>
  12. using namespace std;
  13.  
  14. const int INF = 1000000010;
  15.  
  16. struct Info
  17. {
  18.     int x, minv, maxv;
  19. };
  20.  
  21. stack<Info> s1, s2;
  22.  
  23. int getMin()
  24. {
  25.     if(s1.empty())
  26.         return s2.top().minv;
  27.     else if(s2.empty())
  28.         return s1.top().minv;
  29.     else
  30.         return min(s1.top().minv, s2.top().minv);
  31. }
  32.  
  33. int getMax()
  34. {
  35.     if(s1.empty())
  36.         return s2.top().maxv;
  37.     else if(s2.empty())
  38.         return s1.top().maxv;
  39.     else
  40.         return max(s1.top().maxv, s2.top().maxv);
  41. }
  42.  
  43. void stack_push(stack<Info>& st, int x)
  44. {
  45.     if(st.empty())
  46.         st.push(Info{x,x,x});
  47.     else
  48.         st.push(Info{x, min(st.top().minv, x), max(st.top().maxv, x)});
  49. }
  50.  
  51. void push(int x)
  52. {
  53.     stack_push(s1, x);
  54. }
  55.  
  56. void pop()
  57. {
  58.     if ( s2.empty() )
  59.     {
  60.         while(!s1.empty())
  61.         {
  62.             stack_push(s2, s1.top().x);
  63.             s1.pop();
  64.         }
  65.     }
  66.     s2.pop();
  67. }
  68.  
  69. int main()
  70. {
  71.     int n,k;
  72.     scanf("%d%d", &n, &k);
  73.     vector<int> a(n);
  74.     for(int i=0;i<n;i++)
  75.         scanf("%d", &a[i]);
  76.     int l;
  77.     int res = 0;
  78.     for(int r = 0; r < n ; r++)
  79.     {
  80.         push(a[r]);
  81.         while(getMax()-getMin()>k)
  82.         {
  83.             pop();
  84.             l++;
  85.         }
  86.         res=max(res, r-l+1);
  87.     }
  88.     printf("%d\n", res);
  89.  
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment