<๋ฌธ์ ๋งํฌ>
https://www.acmicpc.net/problem/17471
17471๋ฒ: ๊ฒ๋ฆฌ๋งจ๋๋ง
์ ๊ฑฐ๊ตฌ๋ฅผ [1, 4], [2, 3, 5, 6]์ผ๋ก ๋๋๋ฉด ๊ฐ ์ ๊ฑฐ๊ตฌ์ ์ธ๊ตฌ๋ 9, 8์ด ๋๋ค. ์ธ๊ตฌ ์ฐจ์ด๋ 1์ด๊ณ , ์ด ๊ฐ๋ณด๋ค ๋ ์์ ๊ฐ์ผ๋ก ์ ๊ฑฐ๊ตฌ๋ฅผ ๋๋ ์๋ ์๋ค.
www.acmicpc.net
<ํ์ด ์ ๋ต>
1. ๋ถ๋ถ์งํฉ / ์กฐํฉ์ ํตํด์ ๋ ์ ๊ฑฐ๊ตฌ๋ฅผ ๊ตฌํ ๋ค์, ํด๋น ์ ๊ฑฐ๊ตฌ ๋ด์ ์ธ๊ตฌ์์ ๊ตฌ์ญ์๋ฅผ ๊ณ์ฐํด์ ๋ชจ๋ ๊ตฌ์ญ์ด ํฌํจ๋์์ ๊ฒฝ์ฐ์๋ง ์ ๋ต์ ๊ฐฑ์ ํด์ฃผ๋ฉด ๋๋ค.
2. ์กฐํฉ์ ๊ตฌํ ๋ ์ด์ฐจํผ ์กฐํฉ์ ํฌํจ๋์ง ๋ชปํ ๊ตฌ์ญ๋ค์ด ๋ค๋ฅธ ์ ๊ฑฐ๊ตฌ์ ํฌํจ๋๊ธฐ ๋๋ฌธ์ N//2๊น์ง๋ง ์กฐํฉ์ ๊ตฌํด๋ ๋๋ค.
3. ๊ทธ๋ฌ๋ N๊น์ง ๋ชจ๋ ์กฐํฉ์ ๊ตฌํด๋ ๋ณ ๋ฌธ์ ์์ด ์๊ฐ ๋ด์ ํต๊ณผ ๋๋ค.
<์ ๋ต ์ฝ๋>
from collections import deque
from itertools import combinations
import sys, os, io, atexit
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
atexit.register(lambda: os.write(1, stdout.getvalue()))
# 221009 17471 ๊ฒ๋ฆฌ๋งจ๋๋ง
# ์ ๋ต์ฝ๋
# bfs ํ์์ ํตํด์ ์ ๊ฑฐ๊ตฌ์ ํฌํจ๋ ๊ตฌ์ญ ์๋ ์ธ๊ตฌ ์ ๊ณ์ฐ
def bfs(group):
# ์ ๊ฑฐ๊ตฌ ๋ด์ ์์์ ํ ๊ตฌ์ญ์ ์ถ๋ฐ ์ง์ ์ผ๋ก ์ง์
start = group[0]
visited[start] = 1
queue = deque()
queue.append(start)
# cnt: ์ ๊ฑฐ๊ตฌ ๋ด์ ํฌํจ๋ ๊ตฌ์ญ ๊ฐ์
cnt = 1
# group_pop: ์ ๊ฑฐ๊ตฌ์ ์ด ์ธ๊ตฌ์ ํฉ๊ณ
group_pop = population[start]
while queue:
current = queue.popleft()
# ์ธ๊ตฌ ์๋ ๊ตฌ์ญ ๊ฐ์ ์ธ์ฃผ๋ฉด์ ์ธ์ ๊ตฌ์ญ ํ์
for next in graph[current]:
if next in group and not visited[next]:
cnt += 1
group_pop += population[next]
visited[next] = 1
queue.append(next)
# ๊ตฌ์ญ ๊ฐ์, ์ธ๊ตฌ์ ๋ฐํ
return cnt, group_pop
# N: ๊ตฌ์ญ์ ๊ฐ์, poplulation: ๊ตฌ์ญ ์ธ๊ตฌ ์ ๋ณด, numbers: ๊ตฌ์ญ ๋ฒํธ
N = int(input())
population = [0] + list(map(int, input().split()))
numbers = [i for i in range(1, N + 1)]
# graph: ๊ตฌ์ญ ์ฐ๊ฒฐ ๊ด๊ณ
graph = [[] for _ in range(N + 1)]
for i in range(1, N + 1):
temp = list(map(int, input().split()))
for j in range(1, temp[0] + 1):
graph[i].append(temp[j])
# ans: ์ธ๊ตฌ ์ฐจ์ด ์ต์๊ฐ(์ถฉ๋ถํ ํฐ ๊ฐ์ผ๋ก ์ด๊ธฐํ)
ans = float('INF')
# ์กฐํฉ์ ์ ๋ฐ๊น์ง๋ง ๊ณ์ฐํ๋ค.
for i in range(1, N//2 + 1):
for comb in combinations(numbers, i):
# group_1, group_2: ์ ๊ฑฐ๊ตฌ 1, ์ ๊ฑฐ๊ตฌ 2
group_1 = comb
group_2 = list(set(numbers) - set(comb))
# visited: ๋ฐฉ๋ฌธ ์ฌ๋ถ ํ์ ๋ฐฐ์ด
visited = [0 for _ in range(N + 1)]
# bfs ํ์์ ํตํด์ ๊ฐ ์ ๊ฑฐ๊ตฌ์ ํฌํจ๋ ๊ตฌ์ญ ์๋ ์ธ๊ตฌ ์ ๊ณ์ฐ
cnt_1, group_pop_1 = bfs(group_1)
cnt_2, group_pop_2 = bfs(group_2)
# ๋ชจ๋ ๊ตฌ์ญ์ด ์ ๊ฑฐ๊ตฌ์ ํฌํจ๋์ด์์ ๊ฒฝ์ฐ
if cnt_1 + cnt_2 == N:
# ์ต์๊ฐ ๊ฐฑ์
ans = min(ans, abs(group_pop_1 - group_pop_2))
# ์ ๊ฑฐ๊ตฌ๋ฅผ ๋๋ ์ ์์ผ๋ฉด -1 ์ถ๋ ฅ
if ans == float('INf'):
print(-1)
# ์ ๋ต ์ถ๋ ฅ
else:
print(ans)
'โญ Problem_Solving > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 1368 ๋ฌผ๋๊ธฐ (Python/ํ์ด์ฌ) (0) | 2022.10.16 |
---|---|
[๋ฐฑ์ค] 2252 ์ค ์ธ์ฐ๊ธฐ (Python/ํ์ด์ฌ) (0) | 2022.10.15 |
[๋ฐฑ์ค] 16236 ์๊ธฐ์์ด (Python/ํ์ด์ฌ) (0) | 2022.10.13 |
[๋ฐฑ์ค] 12100 2048 (Easy) (Python/ํ์ด์ฌ) (1) | 2022.10.11 |
[๋ฐฑ์ค] 18405 ๊ฒฝ์์ ์ ์ผ (Python/ํ์ด์ฌ) (0) | 2022.10.10 |
๋๊ธ