/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 344.0 KiB
#3 Accepted 1ms 532.0 KiB
#4 Accepted 1ms 320.0 KiB
#5 Accepted 2ms 528.0 KiB
#6 Accepted 3ms 532.0 KiB
#7 Accepted 5ms 532.0 KiB
#8 Accepted 5ms 576.0 KiB
#9 Accepted 4ms 532.0 KiB
#10 Accepted 5ms 344.0 KiB
#11 Accepted 5ms 556.0 KiB
#12 Accepted 5ms 532.0 KiB
#13 Accepted 5ms 532.0 KiB
#14 Accepted 5ms 324.0 KiB
#15 Accepted 5ms 532.0 KiB

Code

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

#define ll long long
#define int long long
#define all(x) (x).begin(), (x).end()
#define f(i, n) for (int i = 0; i < n; i++)
#define trace(x) cerr << #x << ": " << x << '\n'
bool check(vector<int> &cnt, int rem)
{
    int mx = 0;
    for (int v : cnt)
        mx = max(mx, v);
    return mx <= (rem + 1) / 2;
}

void solve(string s)
{
    int n = s.size();
    vector<int> cnt(26, 0);
    for (char ch : s)
        cnt[ch - 'a']++;
    if (!check(cnt, n))
    {
        cout << "-1\n";
        return;
    }
    string res;
    res.reserve(n);
    int prev = -1;
    for (int pos = 0; pos < n; pos++)
    {
        bool ok = false;
        for (int c = 0; c < 26; c++)
        {
            if (cnt[c] == 0 or c == prev)
                continue;
            cnt[c]--;
            if (check(cnt, n - pos - 1))
            {
                res.push_back(char('a' + c));
                prev = c;
                ok = true;
                break;
            }
            cnt[c]++;
        }
        if (!ok)
            break;
    }
    if (res.size() < n)
        cout << "-1\n";
    else
        cout << res << '\n';
}

int32_t main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--)
    {
        string s;
        cin >> s;
        solve(s);
    }
    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:56:37
Judged At
2025-07-14 16:56:37
Judged By
Score
100
Total Time
5ms
Peak Memory
576.0 KiB