/ SeriousOJ /

Record Detail

Accepted


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

Code

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

void solve();

int main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    int tc; cin >> tc;
    for (int tt = 0; tt < tc; tt++) solve();
    return 0;
}

void solve() {
    string s; cin >> s;
    vector<int> freq(26, 0);
    for (char c : s) freq[c - 'a']++;
    int n = s.size();
    if (*max_element(freq.begin(), freq.end()) > (n + 1) / 2) {
        cout << -1 << "\n";
        return;
    }
    string ret;
    for (int i = 0, prev = -1; i < n; i++) {
        int idx = max_element(freq.begin(), freq.end()) - freq.begin();
        if (freq[idx] * 2 - 1 == n - i) {
            ret += 'a' + idx;
            freq[idx]--;
            prev = idx;
        } else {
            for (int j = 0; j < 26; j++) {
                if (freq[j] > 0 && prev != j) {
                    ret += 'a' + j;
                    freq[j]--;
                    prev = j;
                    break;
                }
            }
        }
    }
    cout << ret << "\n";
}

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 15:57:04
Judged At
2025-07-14 15:57:04
Judged By
Score
100
Total Time
5ms
Peak Memory
532.0 KiB