fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. #define int long long
  5. #define yes cout << "YES\n";
  6. #define no cout << "NO\n";
  7.  
  8.  
  9. void FastIO(){
  10. ios_base::sync_with_stdio(false);
  11. cin.tie(nullptr);
  12. cout.tie(nullptr);
  13. }
  14.  
  15. void solve(){
  16. string str;
  17. cin >> str;
  18.  
  19. int ab = 0, ba = 0;
  20.  
  21. for(int i = 0; i < str.size() - 1; i++){
  22. if(str[i] == 'a' && str[i+1] == 'b')
  23. ++ab;
  24.  
  25. else if(str[i] == 'b' && str[i+1] == 'a')
  26. ++ba;
  27. }
  28.  
  29. if(ab == ba)
  30. cout << str << '\n';
  31.  
  32. else if (ab > ba){
  33. int i = 0;
  34.  
  35. while(ab > ba){
  36. if((i == 0 || str[i-1] != 'b') && str[i] == 'a' && str[i+1] == 'a'){
  37. str[i] = 'b';
  38. ++ba;
  39. }
  40.  
  41. else if((i == 0 || str[i-1] != 'a') && str[i] == 'a' && str[i+1] == 'b'){
  42. str[i] = 'b';
  43. --ab;
  44. }
  45. ++i;
  46. }
  47. cout << str << '\n';
  48. }
  49.  
  50. else{
  51. int i = 0;
  52.  
  53. while(ba > ab){
  54. if((i == 0 || str[i-1] != 'a') && str[i] == 'b' && str[i+1] == 'b'){
  55. str[i] = 'a';
  56. ++ab;
  57. }
  58.  
  59. else if((i == 0 || str[i-1] != 'b') && str[i] == 'b' && str[i+1] == 'a'){
  60. str[i] = 'a';
  61. --ba;
  62. }
  63. ++i;
  64. }
  65. cout << str << '\n';
  66. }
  67. }
  68.  
  69.  
  70.  
  71. signed main(){
  72. FastIO();
  73.  
  74. int t = 1;
  75. cin >> t;
  76.  
  77. while (t--){
  78. solve();
  79. }
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0.01s 5316KB
stdin
4
b
aabbbabaa
abbb
abbaab
stdout
b
aabbbabaa
bbbb
bbbaab