C. Turtle and Good Pairs
贪心地想:要尽可能地减少连续相同字符,所以我们需要尽可能地将字符均匀排列
code
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
string reorderString(int n, string s) {
unordered_map<char, int> freq;
for (char c : s) {
freq[c]++;
}
vector<pair<char, int>> charFreqPairs;
for (auto& p : freq) {
charFreqPairs.push_back(p);
}
// 按照频率从高到低排序
sort(charFreqPairs.begin(), charFreqPairs.end(), [](const pair<char, int>& a, const pair<char, int>& b) {
return a.second > b.second;
});
string result;
result.reserve(n);
// 尝试均匀分布字符
while (!charFreqPairs.empty()) {
auto& top = charFreqPairs[0];
result.push_back(top.first);
top.second--;
if (top.second == 0) {
charFreqPairs.erase(charFreqPairs.begin());
}
if (charFreqPairs.size() > 1) {
auto& second = charFreqPairs[1];
result.push_back(second.first);
second.second--;
if (second.second == 0) {
charFreqPairs.erase(charFreqPairs.begin() + 1);
}
}
}
return result;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
string s;
cin >> n >> s;
cout << reorderString(n, s) << endl;
}
return 0;
}