/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 5ms 532.0 KiB
#3 Accepted 5ms 532.0 KiB
#4 Accepted 5ms 532.0 KiB
#5 Accepted 5ms 532.0 KiB
#6 Accepted 5ms 532.0 KiB
#7 Accepted 5ms 324.0 KiB
#8 Accepted 5ms 344.0 KiB
#9 Accepted 4ms 532.0 KiB
#10 Accepted 5ms 532.0 KiB
#11 Accepted 5ms 532.0 KiB
#12 Accepted 5ms 532.0 KiB
#13 Accepted 6ms 504.0 KiB
#14 Accepted 5ms 324.0 KiB
#15 Accepted 5ms 532.0 KiB

Code

#include <bits/stdc++.h>
using namespace std;

void solve() {
    string s; cin >> s;
    int n = s.size();
    int frq[26]{};
    for (int i = 0; i < n; i++) {
        frq[s[i] - 'a']++;
    }
    int prev = -1;
    for (int len = n; len >= 1; len--) {
        int mx = *max_element(frq, frq + 26);
        if (2*mx - 1 > len) {
            cout << "-1\n";
            return;
        }
        if (2*mx - 1 == len) {
            char c = max_element(frq, frq + 26) - frq;
            cout << char('a' + c);
            frq[c]--;
            prev = c;
        } else {
            int i = 0;
            while (frq[i] == 0 || i == prev)
                i++;
            cout << char('a' + i);
            frq[i]--;
            prev = i;
        }
    }
    cout << "\n";
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    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 17:11:06
Judged At
2025-07-14 17:11:06
Judged By
Score
100
Total Time
6ms
Peak Memory
532.0 KiB