Skip to content

Commit 93b063c

Browse files
committed
solve problem
1 parent 6cc40cc commit 93b063c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import heapq
2+
3+
4+
def reconstruct(seq, n):
5+
adj: dict[int, set[int]] = {}
6+
indeg: dict[int, int] = {}
7+
keys = [x for x in seq if x >= 0]
8+
9+
# build graph
10+
for pos, x in enumerate(seq):
11+
if x < 0:
12+
continue
13+
h = x % n
14+
j = h
15+
while j != pos:
16+
y = seq[j]
17+
if y >= 0 and y != x:
18+
adj.setdefault(y, set()).add(x) # y -> x
19+
indeg[x] = indeg.get(x, 0) + 1
20+
j = (j + 1) % n
21+
indeg.setdefault(x, 0) # ensure present even if 0
22+
23+
# topo sort, smallest first
24+
heap = [k for k in keys if indeg.get(k, 0) == 0]
25+
heapq.heapify(heap)
26+
result = []
27+
28+
while heap:
29+
k = heapq.heappop(heap)
30+
result.append(k)
31+
for nxt in adj.get(k, []):
32+
indeg[nxt] -= 1
33+
if indeg[nxt] == 0:
34+
heapq.heappush(heap, nxt)
35+
return result
36+
37+
38+
n = int(input())
39+
table = list(map(int, input().split()))
40+
print(" ".join(map(str, reconstruct(table, n))))
41+
42+
"""
43+
adj: {
44+
12: {1, 13},
45+
34: {1, 12, 13},
46+
27: {38},
47+
22: {33, 34, 1, 38, 12, 13, 27},
48+
32: {33, 1, 34, 38, 12, 13, 21, 22, 27}
49+
}
50+
indeg: {33: 0, 1: 0, 13: 0, 12: 2, 34: 3, 38: 0, 27: 1, 22: 7, 32: 9, 21: 0}
51+
"""

0 commit comments

Comments
 (0)