You are given a string ss of length nn consisting of characters a and/or b.
Let AB(s)AB(s) be the number of occurrences of string ab in ss as a substring. Analogically, BA(s)BA(s) is the number of occurrences of ba in ss as a substring.
In one step, you can choose any index ii and replace sisi with character a or b.
What is the minimum number of steps you need to make to achieve AB(s)=BA(s)AB(s)=BA(s)?
Reminder:
The number of occurrences of string dd in ss as substring is the number of indices ii (1≤i≤|s|−|d|+11≤i≤|s|−|d|+1) such that substring sisi+1…si+|d|−1sisi+1…si+|d|−1 is equal to dd. For example, AB(AB(aabbbabaa)=2)=2 since there are two indices ii: i=2i=2 where aabbbabaa and i=6i=6 where aabbbabaa.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000). Description of the test cases follows.
The first and only line of each test case contains a single string ss (1≤|s|≤1001≤|s|≤100, where |s||s| is the length of the string ss), consisting only of characters a and/or b.
Output
For each test case, print the resulting string ss with AB(s)=BA(s)AB(s)=BA(s) you'll get making the minimum number of steps.
If there are multiple answers, print any of them.
Example
input
Copy
4 b aabbbabaa abbb abbaab
output
Copy
b aabbbabaa bbbb abbaaa
Note
In the first test case, both AB(s)=0AB(s)=0 and BA(s)=0BA(s)=0 (there are no occurrences of ab (ba) in b), so can leave ss untouched.
In the second test case, AB(s)=2AB(s)=2 and BA(s)=2BA(s)=2, so you can leave ss untouched.
In the third test case, AB(s)=1AB(s)=1 and BA(s)=0BA(s)=0. For example, we can change s1s1 to b and make both values zero.
In the fourth test case, AB(s)=2AB(s)=2 and BA(s)=1BA(s)=1. For example, we can change s6s6 to a and make both values equal to 11.
题意: 给出一个字符串,只由字符'a'和'b'组成,每次操作可以更改一个字符,要使字符串中子串"ab"和子串"ba"出现次数相同,输出更改次数最小时更改完的字符串。
分析: 典型的思维题,例如字符串aabaababaaab,它的贡献只在ab交界处,因此可以把字符串简化为abababab,即删去没用的连续字符,这样每个字符串都可以类似地转化为abab...aba或abab..ab的形式,区别仅在首尾两个字符上,当是第一种形式时ab的数量等于ba的数量,原样输出就行,第二种形式时ab多于ba的数量,只需要首尾更改掉一个字符即可。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
//可以将连续的aaaa缩为一个a,同理连续的b也可以缩为一个b
//这样就十分简单了,任何一个字符串都可以转换为abab...aba或abab...ab的形式,分情况讨论即可
signed main()
{
int T;
cin >> T;
while(T--)
{
string str;
cin >> str;
if(str[0] == str[str.length()-1])
cout << str << endl;
else
{
str[0] = str[str.length()-1];
cout << str << endl;
}
}
return 0;
}