C. Turtle and Good Pairs
time limit per test: 2 seconds
memory limit per test: 256 megabytes
Turtle gives you a string s, consisting of lowercase Latin letters.
Turtle considers a pair of integers (i,j) (1≤i<j≤n) to be a pleasant pair if and only if there exists an integer k such that i≤k<j and both of the following two conditions hold:
sk≠sk+1;
sk≠si or sk+1≠sj.
Besides, Turtle considers a pair of integers (i,j) (1≤i<j≤n) to be a good pair if and only if si=sj or (i,j) is a pleasant pair.
Turtle wants to reorder the string s so that the number of good pairs is maximized. Please help him!
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤). The description of the test cases follows.
The first line of each test case contains a single integer n (2≤n≤2⋅) — the length of the string.
The second line of each test case contains a string s of length n, consisting of lowercase Latin letters.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅.
Output
For each test case, output the string s after reordering so that the number of good pairs is maximized. If there are multiple answers, print any of them.
Example
Input
5
3
abc
5
edddf
6
turtle
8
pppppppp
10
codeforces
Output
acb
ddedf
urtlet
pppppppp
codeforces
Note
In the first test case, (1,3) is a good pair in the reordered string. It can be seen that we can't reorder the string so that the number of good pairs is greater than 1. bac and cab can also be the answer.
In the second test case, (1,2), (1,4), (1,5), (2,4), (2,5), (3,5) are good pairs in the reordered string. efddd can also be the answer.
【思路分析】
思维。对于子串,需要尽可能满足ABA的形式,我们只需要对原字符串中相同字符计数并分隔插入该字符即可。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <cmath>
#include <algorithm>
#include <climits>
#include <stack>
#include <cstring>
#include <iomanip>
#include <set>
#include <queue>
#define i64 long long
using namespace std;
typedef pair<i64, i64> pii;
vector<pii> v;
i64 isExisted(char c){
for (int i = 0; i < v.size(); ++i) {
if (v[i].first == c) return i;
}
return -1;
}
void solve() {
v.clear();
i64 n;
cin>>n;
string s;
cin>>s;
for (int i = 0; i < n; ++i) {
i64 idx;
if (v.empty()) v.emplace_back(s[i],1);
else if ((idx = isExisted(s[i])) == -1) v.emplace_back(s[i],1);
else v[idx].second++;
}
sort(v.begin(), v.end(),cmp);
i64 cnt = 0;
for (auto &item: v) {
while (item.second!=0) {
s[cnt] = item.first;
cnt += 2;
if (cnt >= n) cnt = 1;
item.second--;
}
}
cout<<s<<endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}