/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 324.0 KiB
#3 Accepted 2ms 532.0 KiB
#4 Accepted 2ms 532.0 KiB
#5 Accepted 1ms 532.0 KiB
#6 Accepted 1ms 532.0 KiB
#7 Accepted 1ms 532.0 KiB
#8 Accepted 2ms 580.0 KiB
#9 Accepted 1ms 560.0 KiB
#10 Accepted 2ms 364.0 KiB
#11 Accepted 2ms 476.0 KiB
#12 Accepted 2ms 532.0 KiB
#13 Accepted 2ms 336.0 KiB
#14 Accepted 2ms 484.0 KiB
#15 Accepted 2ms 536.0 KiB

Code

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

int find_max_freq(vector<int> cnt) {
    int max_f = 0;
    for (int count : cnt) {
        if (count > max_f) {
            max_f = count;
        }
    }
    return max_f;
}

int solve(){
    string s;
    cin>>s;
    if(s.size() == 1){
        cout<<s<<endl;
        return 0;
    }
    int mxcnt = 0;
    vector<int> cnt(26, 0);
    for(int i = 0; i < s.size(); i++){
        cnt[s[i] - 'a']++;
        mxcnt = max(mxcnt, cnt[s[i] - 'a']);
    }
    if(mxcnt > (s.size() + 1) / 2){
        cout<<-1<<endl;
        return 0;
    }
    string ans = "";
    vector<pair<int, char>> compress;
    for(int i = 0; i < 26; i++){
        if(cnt[i] > 0){
            compress.push_back({cnt[i], i + 'a'});
        }
    }
    string result = "";
    int last_char_idx = -1;
    int n = s.size();
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < 26; ++j) {
            if (cnt[j] > 0 && j != last_char_idx) {
                cnt[j]--;
                int rem_len = n - 1 - i;
                if (rem_len == 0 || find_max_freq(cnt) <= (rem_len + 1) / 2) {
                    result += (char)('a' + j);
                    last_char_idx = j;
                    break;
                } else {
                    cnt[j]++;
                }
            }
        }
    }

    cout << result << endl;
    return 0;
}
int32_t main(){
    ios::sync_with_stdio(false); 
    cin.tie(0); cout.tie(0);
 
    // #ifndef ONLINE_JUDGE
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    // #endif
    

    int t;
    t = 1;
    cin>>t;
    while(t--){
        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 16:12:41
Judged At
2025-07-14 16:12:41
Judged By
Score
100
Total Time
2ms
Peak Memory
580.0 KiB