๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/์•Œ๊ณ ๋ฆฌ์ฆ˜

[๋ฐฑ์ค€] 14889๋ฒˆ ์Šคํƒ€ํŠธ์™€ ๋งํฌ

by rindev 2021. 1. 7.

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

์ด๋Ÿด์ˆ˜๊ฐ€.. ํžŒํŠธ๊ฐ€ ์žˆ์—ˆ๋‹ค๋‹ˆ..

 

๋ฌธ์ œ๊ฐ€ ๊ธธ๋ฉด ๊ฒ๋ถ€ํ„ฐ ๋จน๊ณ ๋ณด๋Š” ์‚ฌ๋žŒ์ด์ง€๋งŒ ์ด๋ฌธ์ œ๋Š” ๊ณจ๋“œ๊ฐ€ ์•„๋‹ˆ๋‹ˆ๊นŒ ๋‡Œ์— ํž˜์ฃผ๊ณ  ํ’€์—ˆ๋‹ค๐Ÿ˜ค

์•„๋‹ˆ ๊ทธ๋ฆฌ๊ณ  ๋‚˜ ์ด๊ฑฐ ์“ธ๋•Œ "ํžŒํŠธ"๋ผ๋Š”๊ฒŒ ์กด์žฌํ•˜๋Š”์ง€ ์ฒจ์•Œ์•˜๋‹ค ์ด๋Ÿด์ˆ˜๊ฐ€;ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹

 

 

๋ฌธ์ œ๊ฐ€ ๋จผ์†Œ๋ฆฐ๊ฐ€ ์‹ถ์–ด์„œ ๋˜ ์ ์–ด๋ดค์—ˆ์ง€.

ํ•œ ํŒ€์ด ๋œ ์นœ๊ตฌ๋“ค์˜ ๋Šฅ๋ ฅ์น˜๋ฅผ ๋ชจ๋‘ ๋”ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

 

๊ทธ๋Ÿผ ๋ญ˜ ํ•ด์•ผํ•˜๋Š”๊ฐ€!

 

1. ์‚ฌ๋žŒ์ด ๋ช‡ ๋ช…์ธ์ง€ 

    → int(input()) ์œผ๋กœ ๋ฐ›์Œ. ๋งŒ์•ฝ 6๋ช…์ด๋ผ๊ณ  ํ•œ๋‹ค๋ฉด..

    → people = [0,1,2,3,4,5] ์ด๋ ‡๊ฒŒ ์‚ฌ๋žŒ์„ ๋ฆฌ์ŠคํŠธ์— ๋„ฃ๋Š”๋‹ค

 

2. ์Šคํƒ€ํŠธํŒ€ / ๋งํฌํŒ€์œผ๋กœ ์–ด๋–ป๊ฒŒ ๋‚˜๋ˆŒ ๊ฒƒ์ธ์ง€

    → itertools.combinations ์‚ฌ์šฉํ•˜์—ฌ ์กฐํ•ฉ์„ ๊ตฌํ•จ = startํŒ€ (0,1,2)

    → startํŒ€์— ๋“ค์–ด์žˆ์ง€ ์•Š์€ ์‚ฌ๋žŒ = linkํŒ€ (3,4,5) ์ด๋Ÿฐ ์‹์œผ๋กœ.

       ์ด๊ฑด link = [p for p in people if not in start] ๋กœ ํ–ˆ์Œ! people์— ์žˆ๋Š” ์‚ฌ๋žŒ ์ค‘, start์— ์—†๋Š” ์‚ฌ๋žŒ์„ link์— ๋„ฃ์Œ

 

3. ๊ฐ ํŒ€์˜ ๋Šฅ๋ ฅ์น˜ ํ•ฉ์„ ๊ตฌํ•˜๊ธฐ

    → ๊ฐ ํŒ€์— ํฌํ•จ๋œ ์‚ฌ๋žŒ์€ ์ˆซ์ž๋กœ ํ‘œํ˜„๋ผ์žˆ์œผ๋ฏ€๋กœ ๊ทธ๋ƒฅ ๊ทธ๋Œ€๋กœ table[i][j]๋กœ ์‚ฌ์šฉํ•˜๋ฉด ๋จ!

    → i == j ์˜ ๊ฒฝ์šฐ์—๋Š” table์— 0์ด๋ผ๊ณ  ๋ผ์žˆ์œผ๋ฏ€๋กœ ๊ตณ์ด if๋กœ ์ฒ˜๋ฆฌํ•ด์ฃผ์ง€ ์•Š์•„๋„ ๋œ๋‹ค! (๋”ํ•ด๋„ 0์ด๋‹ˆ๊นŒ..)

 

 

๐Ÿ™‹‍โ™€๏ธ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

๋”๋ณด๊ธฐ

 

# 14889 ๋ฒˆ : ์Šคํƒ€ํŠธ์™€ ๋งํฌ
import itertools
def backtracking_14889():
  n = int(input()) #์‚ฌ๋žŒ ๋ช… ์ˆ˜
  table = [] 
  for _ in range(n):
    table.append(list(map(int, input().split())))

  people = [i for i in range(n)] #์‚ฌ๋žŒ ๋ชฉ๋ก
  stats = [] #๋Šฅ๋ ฅ์น˜์˜ ์ฐจ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฆฌ์ŠคํŠธ

  #ํŒ€์„ ๋‚˜๋ˆ„๋Š” ๊ณผ์ •
  tmp_team = list(itertools.combinations(range(n), n//2))
  for team in tmp_team:
	
    start = team
    link = [p for p in people if p not in start]

    hap_start = 0 #์Šคํƒ€ํŠธ์˜ ํ•ฉ
    hap_link = 0 #๋งํฌ์˜ ํ•ฉ
    for i in start:
      for j in start:
        hap_start += table[i][j]

    for i in link:
      for j in link:
        hap_link += table[i][j]
    
    if abs(hap_start - hap_link) == 0: #์ฐจ๊ฐ€ 0์ด๋ฉด ๋”์ด์ƒ ๊ณ„์‚ฐ ์•ˆํ•ด๋„ ๋จ
      print(0) #0 ์ถœ๋ ฅํ•˜๊ณ  ๋๋ƒ„
      return 
    else: 
      stats.append(abs(hap_start - hap_link)) #0์ด ์•„๋‹ˆ๋ฉด ๋ฆฌ์ŠคํŠธ์— ๋„ฃ์Œ
    
  print(min(stats)) #์ตœ์†Œ๊ฐ’์„ ์ถœ๋ ฅ

backtracking_14889()

 

๋Œ“๊ธ€