ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] ๋ฐฑ์ค€ 11725 ํŠธ๋ฆฌ์˜ ๋ถ€๋ชจ ์ฐพ๊ธฐ (DFS)
    ๐Ÿ’ป Algorithm/Python 2022. 7. 2. 15:29

     

    ๐Ÿ“Œ ๋ฌธ์ œ

    ๋ฃจํŠธ ์—†๋Š” ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ด๋•Œ, ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋ฅผ 1์ด๋ผ๊ณ  ์ •ํ–ˆ์„ ๋•Œ, ๊ฐ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

    ์ž…๋ ฅ

    ์ฒซ์งธ ์ค„์— ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ N (2 ≤ N ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N-1๊ฐœ์˜ ์ค„์— ํŠธ๋ฆฌ ์ƒ์—์„œ ์—ฐ๊ฒฐ๋œ ๋‘ ์ •์ ์ด ์ฃผ์–ด์ง„๋‹ค.

    ์ถœ๋ ฅ

    ์ฒซ์งธ ์ค„๋ถ€ํ„ฐ N-1๊ฐœ์˜ ์ค„์— ๊ฐ ๋…ธ๋“œ์˜ ๋ถ€๋ชจ ๋…ธ๋“œ ๋ฒˆํ˜ธ๋ฅผ 2๋ฒˆ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

    ์˜ˆ์ œ ์ž…๋ ฅ 1

    7
    1 6
    6 3
    3 5
    4 1
    2 4
    4 7

    ์˜ˆ์ œ ์ถœ๋ ฅ 1

    4
    6
    1
    3
    1
    4

    ์˜ˆ์ œ ์ž…๋ ฅ 2

    12
    1 2
    1 3
    2 4
    3 5
    3 6
    4 7
    4 8
    5 9
    5 10
    6 11
    6 12

    ์˜ˆ์ œ ์ถœ๋ ฅ 2

    1
    1
    2
    3
    3
    4
    4
    5
    5
    6
    6

     


     

    ๐Ÿ“Œ ํ’€์ด

    import sys
    sys.setrecursionlimit(10**6)
    input = sys.stdin.readline
    
    
    def dfs(node):
        visited[node] = 1
        for i in graph[node]:
            if not visited[i]:
                parent[i] = node
                dfs(i)
    
    
    if __name__ == '__main__':
        n = int(input())
    
        graph = [[] for _ in range(n+1)]
        visited = [0] * (n+1)
        parent = [0] * (n+1)
    
        while True:
            try:
                a, b = map(int, input().split())
                graph[a].append(b)
                graph[b].append(a)
            except:
                break
    
        for i in range(n+1):
            graph[i].sort()
    
        dfs(1)
    
        print(*parent[2:], sep='\n')

    visited[i] == 1์ด๋ฉด ๋…ธ๋“œ i์— ์ด๋ฏธ ๋ฐฉ๋ฌธํ–ˆ๊ณ  ๋ถ€๋ชจ ์ฒดํฌ๋„ ๋๋‚ธ ๊ฒƒ
    visited[i] == 0์ด๋ฉด ๋…ธ๋“œ i์— ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•„์„œ ๋ถ€๋ชจ ์ฒดํฌ๋„ ํ•ด์•ผํ•˜๋Š” ๊ฒƒ

     

    sys.setrecursionlimit()

    Python์ด ์ •ํ•œ ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด๋Š” sys.getrecursionlimit()์„ ์ด์šฉํ•ด ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. BOJ์˜ ์ฑ„์  ์„œ๋ฒ„์—์„œ ์ด ๊ฐ’์€ 1,000์œผ๋กœ ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์žฌ๊ท€ ํ˜ธ์ถœ ํšŸ์ˆ˜๊ฐ€ ์ด ๊ฐ’์„ ๋„˜์œผ๋ฉด ReferenceError๊ฐ€ ๋œน๋‹ˆ๋‹ค.

     

    sys.setrecursionlimit()์„ ์‚ฌ์šฉํ•˜๋ฉด Python์ด ์ •ํ•œ ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด๋ฅผ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฌธ์ œ์˜ ์ž…๋ ฅ๊ฐ’์„ ๋ณด๊ณ  ์žฌ๊ท€๊ฐ€ ์–ผ๋งˆ๋‚˜ ์ผ์–ด๋‚ ์ง€ ๊ฐ€๋Š ํ•˜์—ฌ ๊นŠ์ด๋ฅผ ๋ณ€๊ฒฝํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค. ์ด ๋ฌธ์ œ์—์„œ๋Š” n์ด ์ตœ๋Œ€ 100,000์ด๋ฏ€๋กœ ๋„‰๋„‰ํžˆ sys.setrecursionlimit(10**6)์œผ๋กœ ์„ค์ •ํ•˜๋‹ˆ ์ •๋‹ต ํŒ์ •์„ ๋ฐ›์„ ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.

     

    sys.setrecursionlimit()๋กœ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ“๊ฐ’์„ ํฌ๊ฒŒ ๋ณ€๊ฒฝํ–ˆ๋‹ค๊ณ  ํ•˜๋”๋ผ๋„, ์žฌ๊ท€์˜ ๊นŠ์ด๊ฐ€ ์ฑ„์  ์„œ๋ฒ„๊ฐ€ ๊ฐ๋‹นํ•  ์ˆ˜ ์—†๋Š” ์ •๋„๋กœ ๊นŠ์–ด์ง€๋ฉด, Segmentation fault๊ฐ€ ๋ฐœ์ƒํ•ด ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ ์ด์œ ๋กœ SegFault๋ฅผ ๋ฐ›๊ฒŒ ๋˜๋‹ˆ ์ฃผ์˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

    ๋Œ“๊ธ€

Designed by Tistory.