fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. void solve(ll int,ll int*);
  5. ll int min(ll int*,ll int,int);
  6.  
  7. ll int min(ll int*x,ll int l,ll int m){ //finding minimum from the index i passed towards right
  8. //eg 12531 index passed is 1 ie elemt no 2 now checking minimum among 531 but greater than 2 ie that
  9.  
  10. ll int k=x[l]; //mini has 1
  11. ll int mini=x[l+1]; //mini has 3
  12. for(++l;l<m;l++){ //starting from 4,8
  13. if(x[l]<mini && x[l]>k){ //4<8 8>4 , 8<4! 8>4
  14. mini=x[l]; //mini=4
  15. }
  16. }return mini;
  17. }//min end
  18. void solve(ll int n,ll int*a){
  19.  
  20. ll int i,j,mi=0,pos=0,temp,flag=0;
  21. for(i=(n-1);i>0;i--){
  22. if(a[i]>a[i-1]){
  23. mi=min(a,(i-1),n); //in 671 sending from 671
  24. for(j=n-1;j>=i;j--){
  25. if(mi==a[j]){pos=j;break;}
  26. }
  27. //now mi holds the minimum number from the decreasing list on right and pos stores the index
  28. //we need to swap now the no. and the mi and reverse the rest on the right of swapped
  29. temp=a[pos];
  30. a[pos]=a[i-1];
  31. a[i-1]=temp;
  32. flag=1; //swapped
  33. goto x;
  34. }
  35. }
  36. x:if(flag){
  37. for(j=(n-1);i<=j;i++,j--){ //reversing the rest from the swapped towards right
  38. temp=a[i];
  39. a[i]=a[j];
  40. a[j]=temp;
  41. }
  42. }if(flag){ //an operation has occured
  43. for(i=0;i<n;i++)cout<<a[i];
  44. cout<<endl;
  45. return;
  46. }
  47. else cout<<-1<<endl; //no operation
  48. return;
  49. } //solve end
  50. int main() {
  51. ll int t;
  52. cin>>t;
  53. while(t--){
  54. ll int n,f=0,f1=0;cin>>n;
  55. if(n==1){cout<<-1<<endl;continue;} //for all 1 digit nos
  56. ll int i,a[n]; //declared array and index
  57. for(i=0;i<n;i++){
  58. cin>>a[i];
  59. if(a[i]!=0)f++;
  60. if(i>0 && (a[i-1]==a[i]))f1++;
  61. }if(f==1 || f1==n-1){cout<<-1<<endl;continue;}//f=1 for cases like 0001 and f1 for cases like 1111
  62. solve(n,a);
  63. }return 0;}
  64.  
Success #stdin #stdout 0s 4244KB
stdin
8
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6
7
2 7 9 9 8 7 3
3
3 1 2
3
1 3 2
4
2 9 9 2
3
1 2 3
5
1 1 1 1 1
stdout
15834
1474584162
2837799
321
213
9229
132
-1