/ SeriousOJ /

Record Detail

Accepted


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

Code

#ifndef LOCAL
#include <bits/stdc++.h>
#define debug(...)
#endif

using namespace std;
#define int long long
#define cinv(v) for (auto &it:v) cin>>it;
#define coutv(v) for (auto &it:v) cout<< it<<' '; cout<<'\n';

void shelby() {
    string s;
    cin >> s;
    int n = s.size();
    map<char,int> freq;
    map<int, set<char>, greater<> > mp;
    for (auto &it: s) freq[it]++;
    for (auto &[u,v]: freq) mp[v].insert(u);
    debug(mp, n);
    if (mp.begin()->first * 2 - (n % 2) > n) return void(cout << "-1\n");
    string t;
    while (!mp.empty()) {
        int rem = n - t.size() - 1;
        int slot = (rem + 1) / 2;
        if (slot < mp.begin()->first) {
            char c = *mp.begin()->second.begin();
            t += c;
            freq[c]--;
            mp.begin()->second.erase(c);
            if (mp.begin()->second.empty()) mp.erase(mp.begin());
            if (freq[c]) mp[freq[c]].insert(c);
            else freq.erase(c);
        }
        else {
            auto it = freq.begin();
            if (!t.empty() && t.back() == it->first) ++it;
            t += it->first;
            // if (it == freq.end()) {
            //     debug(t);
            //     return;
            // }
            assert(it!=freq.end());
            int cnt = it->second;
            mp[cnt].erase(it->first);
            if (mp[cnt].empty()) mp.erase(cnt);
            if (cnt - 1) mp[cnt - 1].insert(it->first);
            it->second--;
            if (it->second == 0) freq.erase(it);
        }
    }
    cout << t << '\n';
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    cin >> t;
    for (int _ = 1; _ <= t; ++_) {
        // cout << "Case " << _ << ": ";
        shelby();
    }
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-26 08:42:23
Judged At
2025-07-26 08:42:23
Judged By
Score
100
Total Time
7ms
Peak Memory
572.0 KiB