Accepted
Code
/*
* Name : Md. Fahmidur Rahman Nafi
* Date : 2025-07-14 Time : 20:46:44
*/
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define ll long long
#define ld long double
#define ull unsigned long long
#define lcm(a,b) ((a*b)/__gcd(a,b))
#define debug(x) cout << "Debug : " << x << endl;
const double PI = 2 * acos(0.0);
const int MOD = 1000000007;
void solve(){
string s, ans;
cin >> s;
int len = s.size();
map <char, int> mp;
map <int, int> mpp;
int mx = 0;
for (auto i : s) mp[i]++, mx = max(mx, mp[i]);
for (auto [x, y] : mp){
mpp[y]++;
}
if (mx <= (len + 1) / 2){
char prv = 'X';
for (int i = 1; i <= len; i++){
for (char c = 'a'; c <= 'z'; c++){
if (mp[c] > 0 && prv != c){
if (mp[c] == mx){
ans += c;
mp[c]--;
mpp[mx]--;
mpp[mx - 1]++;
if (mpp[mx] == 0){
mx--;
}
prv = c;
break;
}
else{
if (mx <= (len + 1 - i) / 2){
ans += c;
mpp[mp[c]]--;
mp[c]--;
mpp[mp[c]]++;
prv = c;
break;
}
else{
continue;
}
}
}
}
}
cout << ans << endl;
}
else{
cout << -1 << endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--){
solve();
}
}
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:30:01
- Judged At
- 2025-07-14 16:30:01
- Judged By
- Score
- 100
- Total Time
- 3ms
- Peak Memory
- 764.0 KiB