fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to print Next Greater Element for each element of the array
  5. void nextGreater(int a[], int n)
  6. {
  7. stack<int> s;
  8. int i=0,j=1;
  9. for(;i<n;i++){
  10. // int j=i+1;
  11. while(a[j]<=a[i]){
  12. if(j==n){
  13. break;
  14. }
  15. j++;
  16. }
  17. if(j>=n){
  18. s.push(-1);
  19. continue;
  20. }
  21. s.push(a[j]);
  22. // cout<<"pushing "<<a[j]<<" for "<<a[i]<<endl;
  23. }
  24.  
  25. stack<int> x;
  26. while(!s.empty()){
  27. x.push(s.top());
  28. s.pop();
  29. }
  30. s=x;
  31.  
  32. for(int i=0;i<n;i++){
  33. cout<<a[i]<<','<<s.top()<<endl;
  34. s.pop();
  35. }
  36. }
  37.  
  38. // The Main Function
  39. int main()
  40. {
  41. int t;
  42. cin>>t;
  43. while(t--){
  44. int n;
  45. cin>>n;
  46. int arr[n];
  47. for(int i=0; i<n; i++){
  48. cin>>arr[i];
  49. }
  50. nextGreater(arr, n);
  51. }
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 5332KB
stdin
2
4
11 13 21 3
5
11 9 13 21 3
stdout
11,13
13,21
21,-1
3,-1
11,13
9,13
13,21
21,-1
3,-1