Accepted
Code
#include<bits/stdc++.h>
using namespace std;
int main() {
int T;
cin >> T;
while (T--)
{
string s;
cin >> s;
int freq[26] = {0};
for (char ch : s) freq[ch - 'a']++;
string ans = "";
int prev = -1;
int n = (int)s.size();
for (int i = 0; i < n; i++)
{
bool found = false;
for (int c = 0; c < 26; c++)
{
if (freq[c] > 0 && c != prev)
{
freq[c]--;
int maxf = 0;
int rem = n - i - 1;
for (int x = 0; x < 26; x++)
{
maxf = max(maxf, freq[x]);
}
if (maxf <= (rem + 1) / 2)
{
ans += (char)(c + 'a');
prev = c;
found = true;
break;
}
freq[c]++;
}
}
if (!found)
{
ans = "-1";
break;
}
}
cout << ans << "\n";
}
return 0;
}
Information
- Submit By
- Type
- Submission
- Problem
- P1209 B. Rearrange the String
- Contest
- Educational Round 1
- Language
- C++17 (G++ 13.2.0)
- Submit At
- 2025-07-14 16:53:17
- Judged At
- 2025-07-14 16:53:17
- Judged By
- Score
- 100
- Total Time
- 6ms
- Peak Memory
- 544.0 KiB