Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / Python] ์ˆœ์œ„

meeeeejin 2021. 4. 5. 23:44

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/49191

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ˆœ์œ„

5 [[4, 3], [4, 2], [3, 2], [1, 2], [2, 5]] 2

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

4๋ฒˆ ์„ ์ˆ˜๊ฐ€ 2๋ฒˆ ์„ ์ˆ˜์—๊ฒŒ ์ด๊ธฐ๊ณ  2๋ฒˆ ์„ ์ˆ˜๊ฐ€ 5๋ฒˆ ์„ ์ˆ˜์—๊ฒŒ ์ด๊ธด๋‹ค๋ฉด, 4๋ฒˆ ์„ ์ˆ˜๋Š” ๊ฒฐ๊ตญ 5๋ฒˆ ์„ ์ˆ˜์—๊ฒŒ๋„ ์ด๊น๋‹ˆ๋‹ค. 

4๋ฒˆ > 2๋ฒˆ, 2๋ฒˆ > 5๋ฒˆ → 4๋ฒˆ > 5๋ฒˆ

์ด๋Ÿฐ ์‹์œผ๋กœ ๋ชจ๋“  ์„ ์ˆ˜์˜ ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ์ข…ํ•ฉํ•ด์„œ ๊ฒฐ๊ณผ์˜ ๊ฐœ์ˆ˜๊ฐ€ (n - 1)๊ฐœ๋ผ๋ฉด ์ˆœ์œ„๋ฅผ ํ™•์ • ์ง€์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

 

  1. ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  win, lose ๋”•์…”๋„ˆ๋ฆฌ ์ดˆ๊ธฐํ™”
  2. results์— ์žˆ๋Š” ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋ฅผ ์ž…๋ ฅ (์„ ์ˆ˜๊ฐ€ ๊ฒน์น˜์ง€ ์•Š๊ฒŒ set ์ž๋ฃŒํ˜• ์ด์šฉ)
  3. n๋ช…์˜ ์„ ์ˆ˜๋“ค์˜ ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ ํ•ฉ์น˜๊ธฐ
    1) ๋งŒ์•ฝ A๊ฐ€ B๋ฅผ ์ด๊ฒผ๋‹ค๋ฉด A๋Š” B๊ฐ€ ์ด๊ธด ๋ชจ๋“  ์„ ์ˆ˜๋“ค์—๊ฒŒ ์Šน๋ฆฌ
    2) ๋งŒ์•ฝ A๊ฐ€ B์—๊ฒŒ ์กŒ๋‹ค๋ฉด A๋Š” B๊ฐ€ ์ง„ ๋ชจ๋“  ์„ ์ˆ˜๋“ค์—๊ฒŒ ํŒจ๋ฐฐ
  4. ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ์˜ ๊ฐœ์ˆ˜๊ฐ€ (n - 1)๊ฐœ์ผ ๊ฒฝ์šฐ ์ˆœ์œ„๋ฅผ ์ •ํ•  ์ˆ˜ ์žˆ์Œ

 

 

 

์†Œ์Šค์ฝ”๋“œ

from collections import defaultdict

def solution(n, results):
    answer = 0
    win, lose = defaultdict(set), defaultdict(set)
    # ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ ์ž…๋ ฅ ๋ฐ›๊ธฐ
    for (winner, loser) in results:
        win[winner].add(loser)
        lose[loser].add(winner)
    # ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ ํ•ฉ์น˜๊ธฐ
    for i in range(1, n + 1):
        for winner in lose[i]: win[winner].update(win[i])
        for loser in win[i]: lose[loser].update(lose[i])
    # ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๊ฐ€ (n - 1)๊ฐœ๋ฉด ์ˆœ์œ„๋ฅผ ์ •ํ•  ์ˆ˜ ์žˆ์Œ
    for i in range(1, n + 1):
        if (len(win[i]) + len(lose[i])) == (n - 1): answer += 1

    return answer

 

728x90