fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. ios_base::sync_with_stdio(false);
  6. cin.tie(0); cout.tie(0);
  7. int t, n, i;
  8. cin>>t;
  9. while(t--)
  10. {
  11. cin>>n;
  12. vector<int> ar(n);
  13. for (i=0;i<n;i++) cin>>ar[i];
  14. stack<int> st1, st2;
  15. bool flag=false;
  16. for (i=n-1;i>0;i--)
  17. {
  18. if (ar[i-1]>=ar[i])
  19. st1.push(ar[i]);
  20. else
  21. {
  22. st1.push(ar[i]);
  23. flag=true;
  24. break;
  25. }
  26. }
  27. if (!flag)
  28. cout<<-1<<"\n";
  29. else
  30. {
  31. while(!st1.empty() and ar[i-1]<st1.top())
  32. {
  33. st2.push(st1.top());
  34. st1.pop();
  35. }
  36. int tmp=ar[i-1];
  37. ar[i-1]=st2.top();
  38. st2.pop();
  39. while(!st1.empty() and i<n)
  40. {
  41. ar[i]=st1.top();
  42. st1.pop();
  43. i++;
  44. }
  45. if (i<n)
  46. ar[i]=tmp, i++;
  47. while(!st2.empty() and i<n)
  48. {
  49. ar[i]=st2.top();
  50. st2.pop();
  51. i++;
  52. }
  53. for (i=0;i<n;i++) cout<<ar[i];
  54. cout<<"\n";
  55. }
  56. }
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 4264KB
stdin
2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6
stdout
15834
1474584162