/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 54ms 29.898 MiB
#2 Accepted 370ms 48.184 MiB
#3 Accepted 414ms 51.125 MiB
#4 Accepted 111ms 37.219 MiB
#5 Accepted 115ms 37.23 MiB
#6 Accepted 116ms 38.348 MiB
#7 Accepted 106ms 37.848 MiB
#8 Accepted 626ms 62.93 MiB
#9 Accepted 680ms 64.82 MiB
#10 Accepted 868ms 80.645 MiB
#11 Accepted 1221ms 106.855 MiB
#12 Accepted 1223ms 106.566 MiB
#13 Accepted 1217ms 106.445 MiB
#14 Accepted 1221ms 106.648 MiB
#15 Accepted 1102ms 96.5 MiB
#16 Accepted 1101ms 96.469 MiB
#17 Accepted 938ms 84.008 MiB
#18 Accepted 402ms 52.312 MiB
#19 Accepted 192ms 39.555 MiB

Code

import sys
import threading
from math import gcd

def find_beautiful_permutation(N):
    # build adjacency list: edge u–v if gcd(u,v)==1 and |u−v|>1
    adj = [[] for _ in range(N+1)]
    for u in range(1, N+1):
        for v in range(u+1, N+1):
            if abs(u - v) > 1 and gcd(u, v) == 1:
                adj[u].append(v)
                adj[v].append(u)

    # sort neighbors by ascending degree to help prune early
    deg = [len(adj[u]) for u in range(N+1)]
    for u in range(1, N+1):
        adj[u].sort(key=lambda x: deg[x])

    visited = [False] * (N+1)
    path = [0] * N

    sys.setrecursionlimit(10**7)
    def dfs(pos):
        if pos == N:
            return True
        last = path[pos-1]
        for v in adj[last]:
            if not visited[v]:
                visited[v] = True
                path[pos] = v
                if dfs(pos+1):
                    return True
                visited[v] = False
        return False

    # try every possible start
    for start in range(1, N+1):
        visited[start] = True
        path[0] = start
        if dfs(1):
            return path[:]
        visited[start] = False

    return []  # no solution

def main():
    data = sys.stdin.read().split()
    T = int(data[0])
    idx = 1
    out = []
    for _ in range(T):
        N = int(data[idx]); idx += 1

        # impossible small cases
        if N in (2, 3, 4, 6):
            out.append("-1")
            continue

        sol = find_beautiful_permutation(N)
        if not sol:
            out.append("-1")
        else:
            out.append(" ".join(map(str, sol)))

    sys.stdout.write("\n".join(out))

if __name__ == "__main__":
    # run in a separate thread to allow deep recursion
    threading.Thread(target=main).start()

Information

Submit By
Type
Submission
Problem
P1203 D. Roy Loves Permutation
Language
PyPy 3 (Python 3.9.18 PyPy 7.3.15)
Submit At
2025-06-08 14:31:29
Judged At
2025-06-08 14:32:19
Judged By
Score
100
Total Time
1223ms
Peak Memory
106.855 MiB