반응형
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


Brute Force + DFS 문제처럼 보이지만, Python은 조합 경우의 수를 itertools의 내장함수 combinations을 사용할 수 있어 쉽게 풀 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import math | |
from itertools import combinations | |
n = int(sys.stdin.readline()) | |
maps = [] | |
for _ in range(n): | |
maps.append(list(map(int, sys.stdin.readline().split()))) | |
# 두 개의 그룹으로 나눌 사람의 리스트 | |
people = list(range(n)) | |
# 두 개의 그룹으로 나눈다. n명 중 n//2명을 선택하는 경우의 수 | |
candidate = list(combinations(people, n // 2)) | |
answer = math.inf | |
for group in candidate: | |
# 해당 그룹에 속하지 않은 나머지 사람들의 리스트 | |
rest = list(set(people) - set(group)) | |
group_sum, rest_sum = 0, 0 | |
# 두 명씩 짝지어 시너지를 확인해야 하므로, 다시 두 명씩 짝지어준다 | |
group_combination = list(combinations(list(group), 2)) | |
rest_combination = list(combinations(rest, 2)) | |
for y, x in group_combination: | |
group_sum += (maps[y][x] + maps[x][y]) | |
for y, x in rest_combination: | |
rest_sum += (maps[y][x] + maps[x][y]) | |
# 두 그룹의 합계 차이가 최소가 되도록 구한다 | |
if answer > abs(group_sum - rest_sum): | |
answer = abs(group_sum - rest_sum) | |
print(answer) | |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 디스크 컨트롤러 (Level 3) (0) | 2019.11.13 |
---|---|
[Python] 백준 10775. 공항 (0) | 2019.11.12 |
[Python] 프로그래머스. 2020 카카오 recruit - 가사 검색 (Level 4) (1) | 2019.11.10 |
[Python] 프로그래머스. 2018 카카오 recruit - 자동완성 (Level 4) (0) | 2019.11.09 |
[Python] 백준 14503. 로봇 청소기 (0) | 2019.11.08 |