fork(2) download
  1. #include <iostream>
  2. #include<stack>
  3. using namespace std;
  4. void sort_t(stack<int> &s);
  5. int main() {
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10. stack<int> s; int n, x; cin>>n;
  11. while(n--)
  12. {
  13. cin>>x;s.push(x);
  14. }
  15. int prev,curr;
  16. prev=s.top();
  17. s.pop();
  18. stack<int> temp;
  19. bool status=0;
  20. //temp.push(prev);
  21. while(!s.empty())
  22. {
  23. curr=s.top(); s.pop();
  24. if(prev>curr)
  25. {
  26. s.push(prev);
  27. temp.push(curr);status=1;
  28. break;
  29. }
  30. temp.push(prev);
  31. prev=curr;
  32. }
  33. stack<int> temp2;
  34. while(!s.empty())
  35. {
  36. temp2.push(s.top()); s.pop();
  37. }
  38. sort_t(temp);
  39. if(status){
  40. while(!temp2.empty())
  41. {
  42. cout<<temp2.top(); temp2.pop();
  43. }
  44. while(!temp.empty())
  45. {
  46. cout<<temp.top();temp.pop();
  47. }
  48. }
  49. else cout<<"-1";
  50. cout<<endl;
  51. }
  52. return 0;
  53. }
  54.  
  55. void sort_t(stack<int> &s)
  56. {
  57. /* while(!s.empty())
  58.   {
  59.   cout<<s.top()<<' ';s.pop();
  60.   }*/
  61.  
  62. stack<int> tempst;
  63. int temp;
  64. while(!s.empty())
  65. {
  66. temp=s.top();
  67. s.pop();
  68. while(!tempst.empty() && tempst.top()>temp)
  69. {
  70. s.push(tempst.top());
  71. tempst.pop();
  72. }
  73. tempst.push(temp);
  74. }
  75. while(!tempst.empty())
  76. {
  77. s.push(tempst.top());tempst.pop();
  78. }
  79. }
  80.  
Success #stdin #stdout 0s 4428KB
stdin
2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6
stdout
15834
1474584162