/ SeriousOJ /

Record Detail

Accepted


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

Code

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

#define int long long
#define pb push_back
#define all(x) x.begin(), x.end()

void solve() {
    int t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        int n = s.size();
        map<char, int> f;
        for (char c : s) f[c]++;
        
        int mx = 0;
        for (auto &[c, cnt] : f) mx = max(mx, cnt);
        if (mx > (n + 1) / 2) {
            cout << "-1\n";
            continue;
        }

        string ans = "";
        char pre = 0;

       
        /*
        priority_queue<pair<int, char>> pq;
        for (auto &[c, cnt] : f) pq.push({cnt, c});
        while (!pq.empty()) {
            auto [cnt, c] = pq.top(); pq.pop();
            if (!ans.empty() && ans.back() == c) {
                cout << "Wrong placement\n";
                break;
            }
            ans += c;
            if (--cnt > 0) pq.push({cnt, c});
        }
        */

        
        // for (auto &[c, cnt] : f) cout << c << ":" << cnt << " "; cout << endl;

        for (int i = 0; i < n; i++) {
            bool ok = false;
            for (auto &[c, cnt] : f) {
                if (cnt == 0 || c == pre) continue;

                f[c]--;
                int tmpmx = 0, rem = 0;
                for (auto &[x, k] : f) {
                    tmpmx = max(tmpmx, k);
                    rem += k;
                }

                if (tmpmx <= (rem + 1) / 2) {
                    ans += c;
                    pre = c;
                    ok = true;
                    break;
                }
                f[c]++;
            }

            if (!ok) {
                ans = "-1";
                break;
            }
        }

        cout << ans << "\n";
    }
}

int32_t main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    solve();
    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 17:01:43
Judged At
2025-07-14 17:01:43
Judged By
Score
100
Total Time
9ms
Peak Memory
580.0 KiB