fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int t;
  6. cin>>t;
  7. while(t--)
  8. {
  9. int n;
  10. cin>>n;
  11. char s[n],b[n];
  12. int asc[26]={0},temp,i,k=0,anomalypos=0;
  13. cin>>s;
  14. for(i=0;i<n;i++)
  15. {
  16. temp=s[i]-65;
  17. asc[temp]++;
  18. }
  19. for(i=0;i<26;i++)
  20. {
  21. while(asc[i]--)
  22. {
  23. b[k++]=i+65;
  24. }
  25. }
  26. for(i=0;i<n;i++)
  27. {
  28. if(s[i]!=b[i])
  29. {
  30. anomalypos=i;break;
  31. }
  32. }
  33. char min='Z';int reppos=0;
  34. for(i=anomalypos;i<n;i++)
  35. {
  36. if(s[i]<s[anomalypos])
  37. {
  38. if(s[i]<=min)
  39. {
  40. min=s[i];reppos=i;
  41. }
  42. }
  43. }
  44. temp=s[reppos];
  45. for(i=reppos;i>anomalypos;i--)
  46. {
  47. s[i]=s[i-1];
  48. }
  49. s[anomalypos]=temp;
  50. //cout<<"Anoma: "<<anomalypos<<" i: "<<reppos<<endl;
  51. cout<<s<<endl;
  52. }
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 2732KB
stdin
6
5
AABAA
6
ZAZAZA
6
ABCDE
3
BAA
5
ADBCA
5
ADBCD
stdout
AAABA
AZAZAZ
ABCDEA
ABA
AADBC
ABDCD