-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaekJoon17471.py
44 lines (36 loc) · 1.16 KB
/
BaekJoon17471.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# BaekJoon17471.py
from collections import deque
from itertools import combinations
def bfs(arr):
global people, link
start = arr[0]
queue = deque([start])
visited = set([start])
num = 0
while queue:
value = queue.popleft()
num += people[value]
for i in link[value]:
if i not in visited and i in arr:
queue.append(i)
visited.add(i)
return num, len(visited)
N = int(input()) # 구역 개수
people = [0] + list(map(int, input().split())) # 인구수 배열
link = [0 for _ in range(N + 1)] # 연결된 구역들 리스트
result = float('inf')
for i in range(1, N + 1):
link[i] = list(map(int, input().split()))
link[i] = link[i][1:]
for i in range(1, N // 2 + 1):
combis = list(combinations(range(1, N + 1), i))
for combi in combis:
sum1, node1 = bfs(combi)
sum2, node2 = bfs([i for i in range(1, N + 1) if i not in combi])
# 두 선거구의 모든 노드가 연결되어 있는지 확인
if node1 + node2 == N:
result = min(result, abs(sum1 - sum2))
if result != float('inf'):
print(result)
else:
print(-1)