/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 532.0 KiB
#3 Accepted 2ms 544.0 KiB
#4 Accepted 3ms 532.0 KiB
#5 Accepted 5ms 440.0 KiB
#6 Accepted 5ms 532.0 KiB
#7 Accepted 5ms 532.0 KiB
#8 Accepted 5ms 532.0 KiB
#9 Accepted 5ms 336.0 KiB
#10 Accepted 5ms 348.0 KiB
#11 Accepted 5ms 324.0 KiB
#12 Accepted 5ms 532.0 KiB
#13 Accepted 6ms 532.0 KiB
#14 Accepted 5ms 532.0 KiB
#15 Accepted 5ms 532.0 KiB

Code

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

int main() {
    int T;
    cin >> T;

    while (T--) 
    {
        string s;
        cin >> s;

        int freq[26] = {0};
        for (char ch : s) freq[ch - 'a']++;

        string ans = "";
        int prev = -1; 

        int n = (int)s.size();

        for (int i = 0; i < n; i++) 
        {
            bool found = false;

            for (int c = 0; c < 26; c++) 
            {
                if (freq[c] > 0 && c != prev) 
                {
                    freq[c]--;
                    
                    int maxf = 0;
                    int rem = n - i - 1;

                    
                    for (int x = 0; x < 26; x++) 
                    {
                        maxf = max(maxf, freq[x]);
                    }
                    if (maxf <= (rem + 1) / 2) 
                    {
                        ans += (char)(c + 'a');
                        prev = c;
                        found = true;
                        break;
                    }
                    freq[c]++;
                }
            }

            if (!found) 
            {
                ans = "-1";
                break;
            }
        }

        cout << ans << "\n";
    }

    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:53:17
Judged At
2025-07-14 16:53:17
Judged By
Score
100
Total Time
6ms
Peak Memory
544.0 KiB