Advertisement
tungSfer

Untitled

Jul 18th, 2021
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define ll long long
  4. #define el endl
  5. #define umi unordered_map<int, int>
  6. #define umll unordered_map<ll, ll>
  7. #define all(vect) vect.begin(), vect.end()
  8. #define reset(A) memset(A, 0, sizeof(A))
  9. #define approx(n) fixed << setprecision(n)
  10.  
  11. const int mod = 1e9 + 7;
  12.  
  13. using namespace std;
  14.  
  15. void solve()
  16. {
  17.     int n;
  18.     cin >> n;
  19.     int a[n];
  20.     umi mp;
  21.     for(int i = 0; i < n; i++)
  22.     {
  23.         cin >> a[i];
  24.         mp[a[i]] = i;
  25.     }
  26.        
  27.     stack<int> st, s1;
  28.     int b[n], c[n];
  29.     for(int i = n - 1; i >= 0; i--)
  30.     {
  31.         if(st.empty())
  32.         {
  33.             st.push(a[i]);
  34.             b[i] = -1;
  35.         }
  36.         else
  37.         {
  38.             while(!st.empty() && st.top() <= a[i])
  39.                 st.pop();
  40.             if(st.empty())
  41.             {  
  42.                 b[i] = -1;
  43.             }
  44.             else
  45.             {
  46.                 b[i] = st.top();
  47.             }
  48.             st.push(a[i]);
  49.         }
  50.     }
  51. //  for(int i = 0; i < n; i++)
  52. //      cout << b[i] << " ";
  53. //  cout << el << el;
  54. //  for(int i = 0; i < n; i++)
  55. //  {
  56. //      5 1  9 2 5 1  7
  57. //      9 9 -1 5 7 7 -1
  58. //  }
  59.  
  60.     for(int i = n - 1; i >= 0; i--)
  61.     {
  62.         if(s1.empty())
  63.         {
  64.             s1.push(a[i]);
  65.             c[i] = -1;
  66.         }
  67.         else
  68.         {
  69.             while(!s1.empty() && s1.top() >= a[i])
  70.                 s1.pop();
  71.             if(s1.empty())
  72.             {  
  73.                 c[i] = -1;
  74.             }
  75.             else
  76.             {
  77.                 c[i] = s1.top();
  78.             }
  79.             s1.push(a[i]);
  80.         }
  81.     }
  82.     for(int i = 0; i < n; i++)
  83.     {
  84.         if(b[i] != -1)
  85.         {
  86.             cout << c[mp[b[i]]] << " ";
  87.         }
  88.         else
  89.             cout << -1 << " ";
  90.     }
  91.        
  92.     cout << el;
  93.    
  94. }
  95. int main()
  96. {
  97.     int t = 1;
  98.     cin >> t;
  99. //  cin.ignore();
  100.     while(t--)
  101.     {
  102.         solve();
  103.     }
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement