fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int mei(int ar[], int n, int x, int vt){
  5. for(int i=vt+1; i<n; i++){
  6. if(x>ar[i])
  7. return ar[i];
  8. }
  9. return -1;
  10. }
  11.  
  12. int main(){
  13. ios_base::sync_with_stdio(0);
  14. cin.tie(0);
  15. int t;
  16. cin>>t;
  17. while(t--){
  18. int n, ar[1000], ans[1000];
  19. stack <int> st, st2;
  20. cin>>n;
  21. for(int i=0; i<n; i++){
  22. cin>>ar[i];
  23. }
  24. for(int i= n-1; i>=0; i--){
  25. while(!st.empty() && ar[i]>=st.top()){
  26. st.pop();
  27. st2.pop();
  28. }
  29. if(st.empty())
  30. ans[i]=-1;
  31. else{
  32. ans[i]=mei(ar,n,st.top(),st2.top());
  33. }
  34. st.push(ar[i]);
  35. st2.push(i);
  36. }
  37. for(int i=0; i<n; i++){
  38. cout<<ans[i]<<" ";
  39. }
  40. cout<<endl;
  41. }
  42. }
Success #stdin #stdout 0.01s 5388KB
stdin
2
7

5 1 9 2 5 1 7
8

4 8 2 1 9 5 6 3
stdout
2 2 -1 1 -1 -1 -1 
2 5 5 5 -1 3 -1 -1