|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +from typing import IO |
| 6 | + |
| 7 | + |
| 8 | +def switchAbove(word: list[int]) -> bool: |
| 9 | + for i in range(len(word) - 2, -1, -1): |
| 10 | + for j in range(len(word) - 1, i, -1): |
| 11 | + if word[i] < word[j]: |
| 12 | + w = word[i] |
| 13 | + word[i] = word[j] |
| 14 | + word[j] = w |
| 15 | + return True |
| 16 | + return False |
| 17 | + |
| 18 | + |
| 19 | +def switchBelow(word: list[int], best: list[int]) -> list[int]: |
| 20 | + previous_equal = True |
| 21 | + for i in range(0, len(word) - 1): |
| 22 | + if previous_equal and word[i] == best[i]: |
| 23 | + continue |
| 24 | + previous_equal = False |
| 25 | + for j in range(i + 1, len(word)): |
| 26 | + if best[j] < best[i]: |
| 27 | + candidate = best.copy() |
| 28 | + candidate[i] = candidate[j] |
| 29 | + candidate[j] = best[i] |
| 30 | + if word < candidate < best: |
| 31 | + best = candidate |
| 32 | + return best |
| 33 | + |
| 34 | + |
| 35 | +def biggerIsGreater(word: str) -> str: |
| 36 | + reference = [ord(c) for c in word] |
| 37 | + best = reference.copy() |
| 38 | + if not switchAbove(best): |
| 39 | + return "no answer" |
| 40 | + |
| 41 | + while True: |
| 42 | + candidate = switchBelow(reference, best) |
| 43 | + if best != candidate: |
| 44 | + best = candidate |
| 45 | + else: |
| 46 | + break |
| 47 | + |
| 48 | + return "".join(chr(i) for i in best) |
| 49 | + |
| 50 | + |
| 51 | +def main(fptr: IO) -> None: |
| 52 | + T = int(input().strip()) |
| 53 | + for _itr in range(T): |
| 54 | + w = input() |
| 55 | + result = biggerIsGreater(w) |
| 56 | + fptr.write(result + "\n") |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + if "OUTPUT_PATH" in os.environ: |
| 61 | + fptr = open(os.environ["OUTPUT_PATH"], "wt") |
| 62 | + else: |
| 63 | + fptr = sys.stdout |
| 64 | + |
| 65 | + main(fptr) |
| 66 | + |
| 67 | + fptr.close() |
0 commit comments