/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Wrong Answer 1ms 532.0 KiB
#3 Wrong Answer 2ms 560.0 KiB

Code

#include <bits/stdc++.h>     //   All praise is due to Allah alone, and peace and blessings be
using namespace std;         //         upon him, after whom there is no other Prophet.

int32_t main() {
    cin.tie(0)->sync_with_stdio(false);

    function<void()> Test_Case = [&]() {
        string s; cin >> s;
        int n = s.size();
        map<char, int> m;
        for(const char c : s) {
            m[c]++;
        }
        vector<pair<int, char>> ar;
        for(auto [a, b] : m) {
            ar.emplace_back(b, a);
        }
        sort(ar.begin(), ar.end());
        if(ar.back().first > (n + 1) / 2) {
            cout << "-1\n"; return;
        }
        for(int i = 0; i < n; i++) {
            s[i] = '*';
        }
        if(n & 1 and ar.back().first == n / 2 + 1) {
            for(int i = 0; i < n; i += 2) {
                s[i] = ar.back().second;
            }
            ar.pop_back();
        }
        sort(ar.begin(), ar.end(), [](auto a, auto b) {
            return a.second > b.second;
        });
        map<char, int> ind;
        for(int i = 0, k = ar.size() - 1; i < n and k >= 0; i++) {
            if(s[i] == '*') {
                int j = i;
                while(ar[k].first > 0 and j < n) {
                    if(s[j] == '*') {
                        s[j] = ar[k].second;
                        if(ind[s[j]] == 0) {
                            ind[s[j]] = j + 1;
                        }
                        if(ar[k].first == 1) j++;
                        else j += 2;
                        ar[k].first--;
                    }
                }
                if(ar[k].first == 0) k--;
            }
        }
        // cout << s << '\n';
        for(int i = 0, j, cnt; i < n; i = j, n = s.size()) {
            for(j = i + 1, cnt = 0; j < n; j++) {
                if(s[i] == s[j]) {
                    cnt++;
                }
                else break;
            }
            if(cnt > 0) {
                char ok = s[i];
                for(int k = 0; k < cnt; k++) {
                    s.erase(s.begin() + i);
                }
                // cout << s << '\n';
                int k = ind[s[i]] - 2;
                for( ; k >= 0 and cnt; ) {
                    cnt--;
                    s.insert(s.begin() + k, ok);
                    if(cnt == 0) {} else k -= 2;
                }
                ind[s[i]] = k;
            }
        }
        cout << s << '\n';
    };

    int32_t Case = 1;    cin >> Case;
    for (int T = 1; T <= Case; T++) {
        Test_Case();
    }
    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:51:44
Judged At
2025-07-14 16:51:44
Judged By
Score
0
Total Time
2ms
Peak Memory
560.0 KiB