/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 564.0 KiB
#3 Accepted 2ms 508.0 KiB
#4 Accepted 5ms 536.0 KiB
#5 Accepted 5ms 532.0 KiB
#6 Accepted 5ms 532.0 KiB
#7 Accepted 5ms 580.0 KiB
#8 Accepted 5ms 532.0 KiB
#9 Accepted 5ms 532.0 KiB
#10 Accepted 5ms 532.0 KiB
#11 Accepted 5ms 536.0 KiB
#12 Accepted 1ms 532.0 KiB
#13 Accepted 2ms 764.0 KiB
#14 Accepted 1ms 536.0 KiB
#15 Accepted 2ms 532.0 KiB

Code

/*
    JAI JAGANNATH!
*/
//@Author : zanj0

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

template <class T>
using ordered_set = __gnu_pbds::tree<T, __gnu_pbds::null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>;


#define ff first
#define ss second
#define pb push_back
#define MOD 1000000007
#define inf 1e18
#define ps(x, y) fixed << setprecision(y) << x
#define w(x)  \
    int x;    \
    cin >> x; \
    while (x--)
#define endl "\n"
#define timetaken cerr << "Time : " << 1000 * (long double)clock() / (long double)CLOCKS_PER_SEC << "ms\n"

typedef long long int lli;

void zanj0()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif
}
void Solve()
{
    string s;
    cin >> s;
    int n = s.size();
    vector<int> cnt(26);
    for (auto &it : s)
    {
        cnt[it - 'a']++;
        if (cnt[it - 'a'] > (n + 1) / 2)
        {
            cout << -1 << endl;
            return;
        }
    }
    string ret = "";
    char last = '*';
    for (int i = 0; i < n; i++)
    {
        int left = n - i;
        int max_val = (left + 1) / 2;
        char add = (char)('z' + 1);
        for (int j = 0; j < 26; j++)
        {
            if (!cnt[j])
                continue;
            char now = (char)('a' + j);
            int next_max_val = ((left - 1) + 1) / 2;
            if (cnt[j] == max_val && max_val > next_max_val)
            {
                if (last != now)
                {
                    add = now;
                    break;
                }
                else
                {
                    cout << -1 << endl;
                    return;
                }
            }
            else if (last != now && now < add)
                add = now;
        }
        ret += add;
        cnt[add - 'a']--;
        last = add;
    }
    cout << ret << endl;
}
int32_t main()
{
    zanj0();
    w(t) Solve();
    timetaken;
    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 15:51:38
Judged At
2025-07-14 15:51:38
Judged By
Score
100
Total Time
5ms
Peak Memory
764.0 KiB