[BOJ] #2252 ์ค„ ์„ธ์šฐ๊ธฐ (Python)

    ๋ฐ˜์‘ํ˜•

    ๐ŸŒฑ ๋ฌธ์ œ

     

    2252๋ฒˆ: ์ค„ ์„ธ์šฐ๊ธฐ

    ์ฒซ์งธ ์ค„์— N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. M์€ ํ‚ค๋ฅผ ๋น„๊ตํ•œ ํšŒ์ˆ˜์ด๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ํ‚ค๋ฅผ ๋น„๊ตํ•œ ๋‘ ํ•™์ƒ์˜ ๋ฒˆํ˜ธ A, B๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋Š” ํ•™์ƒ A๊ฐ€ ํ•™์ƒ B์˜ ์•ž์— ์„œ์•ผ ํ•œ๋‹ค๋Š” ์˜

    www.acmicpc.net

     

    ๐ŸŒฑ ํ’€์ด

    0. ์ž…๋ ฅ ๋ฐ›๊ธฐ

    n, m = map(int, input().split())
    graph = [[] for _ in range(n + 1)]
    in_degree = defaultdict(int)
    
    for i in range(m):
        small, big = map(int, input().split())
        graph[small].append(big)
        in_degree[big] += 1
    • ํ•™์ƒ์ˆ˜(n)๊ณผ ํ‚ค๋ฅผ ๋น„๊ตํ•œ ํšŸ์ˆ˜(m)์„ ์ž…๋ ฅ๋ฐ›์Šต๋‹ˆ๋‹ค.
    • graph์— ์—ฐ๊ฒฐ ์ •๋ณด๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. (ํ‚ค๊ฐ€ ์ž‘์€ ํ•™์ƒ ๋ฒˆํ˜ธ์— ํ‚ค๊ฐ€ ํฐ ํ•™์ƒ ๋ฒˆํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.)
    • ์œ„์ƒ ์ •๋ ฌ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ง„์ž… ์ฐจ์ˆ˜๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ in_degree ๋ฆฌ์ŠคํŠธ์— ์—ฐ๊ฒฐ๋œ ํ‚ค๊ฐ€ ํฐ ํ•™์ƒ์˜ ๋ฒˆํ˜ธ์˜ ์ง„์ž…์ฐจ์ˆ˜๋ฅผ 1 ์ฆ๊ฐ€ ์‹œํ‚ต๋‹ˆ๋‹ค.

    ์œ„์ƒ์ •๋ ฌ

    1. ์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ๋…ธ๋“œ ๊บผ๋‚ด๊ธฐ

    queue = deque()
    for i in range(1, len(graph)):
        if in_degree[i] == 0:
            queue.append(i)
    
    while queue:
        v = queue.popleft()
        print(v, end = ' ')
        for i in graph[v]:
            in_degree[i] -= 1
            if in_degree[i] == 0:
                queue.append(i)
    • queue๋ฅผ ๋งŒ๋“ค๊ณ , ์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ํ•™์ƒ ๋ฒˆํ˜ธ๋ฅผ queue์— ๋„ฃ์Šต๋‹ˆ๋‹ค.
    • queue์—์„œ ํ•™์ƒ์„ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด๋ฉด์„œ ๊บผ๋‚ธ ํ•™์ƒ๊ณผ ์—ฐ๊ฒฐ๋œ ํ•™์ƒ์˜ ์ง„์ž… ์ฐจ์ˆ˜๋ฅผ 1์”ฉ ๊ฐ์†Œ์‹œํ‚ต๋‹ˆ๋‹ค.
    • ๊ฐ์†Œ์‹œํ‚จ ์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ด ๋˜๋ฉด queue์— ๋„ฃ์Šต๋‹ˆ๋‹ค.
    • queue์— ๋‚จ์€ ํ•™์ƒ์ด ์—†์„ ๋•Œ๊นŒ์ง€ ๋„ฃ๊ณ  ๊บผ๋‚ด๊ธฐ๋ฅผ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

     

    ๐ŸŒฑ ์ฝ”๋“œ

    import sys
    from collections import deque
    from collections import defaultdict
    
    input = sys.stdin.readline
    
    n, m = map(int, input().split())
    graph = [[] for _ in range(n + 1)]
    in_degree = defaultdict(int)
    
    for i in range(m):
        small, big = map(int, input().split())
        graph[small].append(big)
        in_degree[big] += 1
    
    queue = deque()
    for i in range(1, len(graph)):
        if in_degree[i] == 0:
            queue.append(i)
    
    while queue:
        v = queue.popleft()
        print(v, end = ' ')
        for i in graph[v]:
            in_degree[i] -= 1
            if in_degree[i] == 0:
                queue.append(i)

     

     

    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€