/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 43ms 18.102 MiB
#2 Accepted 64ms 19.184 MiB
#3 Accepted 75ms 18.887 MiB
#4 Accepted 64ms 19.16 MiB
#5 Accepted 64ms 19.059 MiB
#6 Accepted 64ms 19.121 MiB
#7 Accepted 65ms 19.176 MiB
#8 Accepted 69ms 19.371 MiB
#9 Accepted 48ms 18.656 MiB
#10 Accepted 68ms 19.242 MiB
#11 Accepted 71ms 19.055 MiB
#12 Accepted 69ms 18.836 MiB
#13 Accepted 77ms 19.078 MiB
#14 Accepted 70ms 18.902 MiB
#15 Accepted 69ms 19.102 MiB

Code

import collections
import sys

def solve():
    s = sys.stdin.readline().strip()
    n = len(s)
    counts = collections.Counter(s)

    max_freq = 0
    if n > 0:
        max_freq = max(counts.values())
    
    if 2 * max_freq > n + 1:
        print(-1)
        return

    res = []
    last_char = ''

    for i in range(n):
        for char_code in range(ord('a'), ord('z') + 1):
            char = chr(char_code)

            if counts[char] == 0:
                continue
            
            if char == last_char:
                continue

            counts[char] -= 1
            
            max_rem_freq = max(list(counts.values()) + [0])
            
            if 2 * max_rem_freq <= n - i:
                res.append(char)
                last_char = char
                break 
            else:
                counts[char] += 1
    
    print("".join(res))

def main():
    try:
        t_str = sys.stdin.readline()
        if t_str:
            t = int(t_str)
            for _ in range(t):
                solve()
    except (IOError, EOFError, ValueError):
        pass

if __name__ == "__main__":
    main()

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Contest
Educational Round 1
Language
PyPy 3 (Python 3.9.18 PyPy 7.3.15)
Submit At
2025-07-14 17:58:17
Judged At
2025-07-14 17:58:17
Judged By
Score
100
Total Time
77ms
Peak Memory
19.371 MiB