https://www.acmicpc.net/problem/14889
14889번: 스타트와 링크
예제 2의 경우에 (1, 3, 6), (2, 4, 5)로 팀을 나누면 되고, 예제 3의 경우에는 (1, 2, 4, 5), (3, 6, 7, 8)로 팀을 나누면 된다.
www.acmicpc.net
https://github.com/stellaluminary/Baekjoon
GitHub - stellaluminary/Baekjoon
Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.
github.com
백트래킹으로 방문되는 index에 대하여 dfs 재귀를 처리하고 방문한 곳들이 한팀 그렇지 않은 곳이 한팀을 이뤄 그에 따른 차이가 최소가 되는 값을 찾는 문제이다.
def dfs(depth, idx):
global n, res
if depth == n//2:
p1, p2 = 0, 0
for i in range(n):
for j in range(n):
if visit[i] and visit[j]:
p1 += s[i][j]
elif not visit[i] and not visit[j]:
p2 += s[i][j]
res = min(res, abs(p1-p2))
return
for i in range(idx, n):
if not visit[i]:
visit[i] = 1
dfs(depth+1, i+1)
visit[i] = 0
import sys
input = sys.stdin.readline
n = int(input())
s = [list(map(int, input().split())) for _ in range(n)]
visit = [0] * n
res = 1e3
dfs(0, 0)
print(res)