Skip to content

Commit 6cf4cd6

Browse files
authored
Create 5.py
1 parent f1cd271 commit 6cf4cd6

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

18/5.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
from collections import deque
2+
3+
# 테스트 케이스(Test Case)만큼 반복
4+
for tc in range(int(input())):
5+
# 노드의 개수 입력 받기
6+
n = int(input())
7+
# 모든 노드에 대한 진입차수는 0으로 초기화
8+
indegree = [0] * (n + 1)
9+
# 각 노드에 연결된 간선 정보를 담기 위한 인접 행렬 초기화
10+
graph = [[False] * (n + 1) for i in range(n + 1)]
11+
12+
# 작년 순위 정보 입력
13+
data = list(map(int, input().split()))
14+
# 방향 그래프의 간선 정보 초기화
15+
for i in range(n):
16+
for j in range(i + 1, n):
17+
graph[data[i]][data[j]] = True
18+
indegree[data[j]] += 1
19+
20+
# 올해 변경된 순위 정보 입력
21+
m = int(input())
22+
for i in range(m):
23+
a, b = map(int, input().split())
24+
# 간선의 방향 뒤집기
25+
if graph[a][b]:
26+
graph[a][b] = False
27+
graph[b][a] = True
28+
indegree[a] += 1
29+
indegree[b] -= 1
30+
else:
31+
graph[a][b] = True
32+
graph[b][a] = False
33+
indegree[a] -= 1
34+
indegree[b] += 1
35+
36+
# 위상 정렬(Topology Sort) 시작
37+
result = [] # 알고리즘 수행 결과를 담을 리스트
38+
q = deque() # 큐 기능을 위한 deque 라이브러리 사용
39+
40+
# 처음 시작할 때는 진입차수가 0인 노드를 큐에 삽입
41+
for i in range(1, n + 1):
42+
if indegree[i] == 0:
43+
q.append(i)
44+
45+
certain = True # 위상 정렬 결과가 오직 하나인지의 여부
46+
cycle = False # 그래프 내 사이클이 존재하는지 여부
47+
48+
# 정확히 노드의 개수만큼 반복
49+
for i in range(n):
50+
# 큐가 비어 있다면 사이클이 발생했다는 의미
51+
if len(q) == 0:
52+
cycle = True
53+
break
54+
# 큐의 원소가 2개 이상이라면 가능한 정렬 결과가 여러 개라는 의미
55+
if len(q) >= 2:
56+
certain = False
57+
break
58+
# 큐에서 원소 꺼내기
59+
now = q.popleft()
60+
result.append(now)
61+
# 해당 원소와 연결된 노드들의 진입차수에서 1 빼기
62+
for i in range(1, n + 1):
63+
if graph[now][i]:
64+
indegree[i] -= 1
65+
# 새롭게 진입차수가 0이 되는 노드를 큐에 삽입
66+
if indegree[i] == 0:
67+
q.append(i)
68+
69+
# 사이클이 발생하는 경우 (일관성이 없는 경우)
70+
if cycle:
71+
print("IMPOSSIBLE")
72+
# 위상 정렬 결과가 여러 개인 경우
73+
elif not certain:
74+
print("?")
75+
# 위상 정렬을 수행한 결과 출력
76+
else:
77+
for i in result:
78+
print(i, end=' ')
79+
print()

0 commit comments

Comments
 (0)