/ SeriousOJ /

Record Detail

Accepted


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

Code

#pragma GCC optimize("O3", "inline")
#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef long double ld;
#define pb push_back
#define ub upper_bound
#define INF 1e18 + 100

const int asz = 26;

string solve()
{
    string s;
    cin >> s;
    int n = s.size();
    vector<int> fa(26, 0);
    for (int i = 0; i < n; i++)
        fa[s[i] - 'a']++;
    char last = '\0';
    for (int i = 0; i < n; i++)
    {
        int fc = 0, mc = 0;
        int fg = 0;
        for (int i = 25; i >= 0; i--)
        {
            if((char)(i + 'a') == last) continue;
            if (fa[i])
            {
                fg = 1;
                if (fa[i] > fa[mc])
                    mc = i;
                fc = i;
            }
        }
        if(!fg) return "-1";
        if (mc != fc)
        {
            if ((n - i) / 2 >= fa[mc])
            {
                s[i] = (char)('a' + fc);
                fa[fc]--;
            }
            else if ((n - i) / 2 >= fa[mc] - 1)
            {
                s[i] = (char)('a' + mc);
                fa[mc]--;
            }
            else
                return "-1";
        }
        else
        {
            if ((n - i) / 2 >= fa[mc] - 1)
            {
                s[i] = (char)('a' + mc);
                fa[mc]--;
            }
            else
                return "-1";
        }
        last = s[i];
    }
    return s;
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t;
    while (t--)
    {
        string x = solve();
        cout << x << "\n";
    }
    return 0;
}

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-15 05:04:46
Judged At
2025-07-15 05:04:46
Judged By
Score
100
Total Time
3ms
Peak Memory
568.0 KiB