/ SeriousOJ /

Record Detail

Accepted


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

Code

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

bool check(vector<ll> cnt, ll remaining) {
    ll mx = *max_element(cnt.begin(), cnt.end());
    return mx <= (remaining+1) / 2;
}

signed main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    ll tc; cin >> tc;

    test:
    while (tc--) {
        string s; cin >> s;
        ll n = s.size();

        vector<ll> cnt(26);
        for (char &u : s) cnt[u-'a']++;
    
        if (!check(cnt, n)){
            cout << "-1\n";
            goto test;
        }
        
        string ans;
        ll last = -1;
        for (ll i = 0; i < n; i++) {
            bool ok = false;
            for (ll j = 0; j < 26; j++) {
                if (cnt[j] == 0) continue;
                if (j == last) continue;
                cnt[j]--;
                if (check(cnt, n-i-1)) {
                    ans.push_back(char('a'+j));
                    last = j;
                    ok = true;
                    break;
                }
                cnt[j]++;
            }
            if (!ok) break;
        }
        if (ans.size() != n) cout << "-1\n";
        else cout << ans << "\n";
    }
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-14 18:18:29
Judged At
2025-07-14 18:18:29
Judged By
Score
100
Total Time
2ms
Peak Memory
560.0 KiB