입력
출력
접근방법
ex) 6명이 있을 때 [0,1,2]로 팀을 구성하는 것과 [3,4,5]로 팀을 구성하는 것은 동일하다. 왜냐하면 한 팀이 결정되며 또 다른 팀은 자동으로 결정 되기 때문이다.
1. 팀을 나누는 경우의 수를 구하고 팀이 다 맞춰졌다면, 팀 능력 차이를 저장하는 함수(DFS)
def dfs(team_list):
'''
사전순으로 증가하는 수열을 구할 때 사용되는 dfs 사용하였다.
'''
if len(team_list) == N/2:
cal_diff(team_list) # 사람들의 idx로 팀간 능력의 차이를 구하고 정답 리스트에 저장
return None
for i in range(team_list[-1]+1 if team_list else 0, N):
if team_list and team_list[0] != 0:
return None
# if i not in team_list:
team_list.append(i)
dfs(team_list)
team_list.pop()
range(team_list[-1]+1 if team_list else 0, N)
을 통해 사전순으로 증가하는 경우로 N/2개의 인덱스(사람들의 번호)를 순차적으로 뽑으면 팀을 나누는 모든 경우의 수를 구할 수 있다.팀을 구성할 때 뽑히는 순서가 상관없기 때문에 사전순으로 증가하는 방법을 통해 팀을 구성한다면 맨 뒤에 인덱스 다음 사람부터 고려하면 된다.
if team_list and team_list[0] != 0:
return
team_list
에 index가 존재하는 경우에 무조건 첫번째 element는 0인 경우의 수만 구하면 된다! 그 외에는 return None
을 통해 dfs의 재귀를 종료한다.# if i not in team_list:
<< 사전순으로 증가하는 경우로 팀을 구성한다면 i가 리스트에 있는지 없는지 판단할 필요가 없다! 2. 주어진 인덱스 리스트로 두 팀간의 능력차이를 구하는 함수
def cal_diff(team_list: list) -> None:
another_team_list = list(set(range(N)) - set(team_list))
team_sum = 0
for i, v in enumerate(team_list[:-1]):
for v2 in team_list[i+1:]:
team_sum += ability[v][v2] + ability[v2][v] # S_ij + S_ji
another_team_sum = 0
for i, v in enumerate(another_team_list[:-1]):
for v2 in another_team_list[i+1:]:
another_team_sum += ability[v][v2] + ability[v2][v]
ans.append(abs(team_sum - another_team_sum))
return None
ans
두 팀간의 능력 차이를 저장하는 리스트(global)from sys import stdin
def cal_diff(team_list: list) -> None:
another_team_list = list(set(range(N)) - set(team_list))
team_sum = 0
for i, v in enumerate(team_list[:-1]):
for v2 in team_list[i+1:]:
team_sum += ability[v][v2] + ability[v2][v]
another_team_sum = 0
for i, v in enumerate(another_team_list[:-1]):
for v2 in another_team_list[i+1:]:
another_team_sum += ability[v][v2] + ability[v2][v]
ans.append(abs(team_sum - another_team_sum))
return None
def dfs(team_list: list) -> None:
if len(team_list) == N/2:
cal_diff(team_list)
return None
for i in range(team_list[-1] if team_list else 0, N):
if team_list and team_list[0] != 0:
return None
if i not in team_list:
team_list.append(i)
dfs(team_list)
team_list.pop()
N = int(stdin.readline())
ability = [list(map(int, stdin.readline().split())) for _ in range(N)]
ans = []
dfs([])
print(min(ans))
결과