/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 552.0 KiB
#3 Accepted 2ms 764.0 KiB
#4 Accepted 1ms 532.0 KiB
#5 Accepted 1ms 480.0 KiB
#6 Accepted 1ms 532.0 KiB
#7 Accepted 1ms 536.0 KiB
#8 Accepted 1ms 496.0 KiB
#9 Accepted 1ms 536.0 KiB
#10 Accepted 2ms 488.0 KiB
#11 Accepted 1ms 764.0 KiB
#12 Accepted 1ms 508.0 KiB
#13 Accepted 2ms 484.0 KiB
#14 Accepted 1ms 516.0 KiB
#15 Accepted 1ms 532.0 KiB

Code

/* GREEN UNIVERSITY OF BANGLADESH
    Md DinIslam, Batch-221 (CSE)
*/
#include <bits/stdc++.h>
using namespace std;

// Debug..
#ifdef LOCAL
#include "debug.h"
#else
#define dg(x...)
#endif

#define ll long long
#define all(x) x.begin(), x.end()
#define pb push_back
#define sz(x) int(x.size())
#define arr array

void Din() {
    string s;
    cin >> s;

    int n = s.size();
    vector<int> cnt(26, 0);

    for (auto &x : s) {
        cnt[x - 'a'] += 1;
    }

    for (int i = 0; i < 26; ++i) {
        if (cnt[i] > (n + 1) / 2) {
            cout << "-1\n";
            return;
        }
    }

    // dg(cnt);

    string ans = "";
    
    for (int i = 0; i < n; ++i) {
        bool ok = 0;
        for (int k = 0; k < 26; ++k) {
            if (cnt[k]) {
                char ch = char('a' + k);
                if (ch != ans.back() || ans.size() == 0) {
                    cnt[k] -= 1;
                    int curr_max = *max_element(all(cnt));
                    if ((n - i) / 2 >= curr_max) {
                        ans.push_back(ch);
                        ok = 1;
                        break;
                    }
                    else {
                        // if not place, increament this....
                        cnt[k] += 1;
                    }
                }
            }
        }

        if (!ok) {
            cout << "-1\n";
            return;
        }
    }


    cout << ans << '\n';
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    cin >> t;
    for (int i = 1; i <= t; ++i) {
        // cout << "Case " << i << ": ";
        Din();
    }
    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:25:21
Judged At
2025-07-14 16:25:21
Judged By
Score
100
Total Time
2ms
Peak Memory
764.0 KiB