Accepted
Code
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
string s;
cin >> s;
int f = 0;
int n = s.size();
vector<int> freq(26);
for (char c: s)
{
freq[c - 'a']++;
if (freq[c - 'a'] > (n + 1) / 2)
f = -1;
}
if (f)
{
cout << f << "\n";
continue;
}
string res;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 26; j++)
if (freq[j] && (res.empty() || j != res.back() - 'a'))
{
freq[j]--;
int f = 0, rem = n - i - 1;
for (int k = 0; k < 26; k++)
if (freq[k] > (rem - (k == j) + 1) / 2)
f = -1;
if (f == 0)
{
res += (char)(j + 'a');
break;
}
freq[j]++;
}
}
cout << res << "\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:07:50
- Judged At
- 2025-07-14 16:07:50
- Judged By
- Score
- 100
- Total Time
- 2ms
- Peak Memory
- 764.0 KiB