ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 24480 ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ 2 with Python
    PS 2023. 4. 10. 17:23
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 24480 ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ˆ˜์—… - ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ 2

    ๐Ÿ’ก ์กฐ๊ฑด

    1. N๊ฐœ์˜ ์ •์ ๊ณผ M๊ฐœ์˜ ๊ฐ„์„ ์œผ๋กœ ๊ตฌ์„ฑ๋œ ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„(undirected graph)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

    2. ์ •์  ๋ฒˆํ˜ธ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ์ด๊ณ  ๋ชจ๋“  ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜๋Š” 1์ด๋‹ค.

    3. ์ •์  R์—์„œ ์‹œ์ž‘ํ•˜์—ฌ ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰์œผ๋กœ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•  ๊ฒฝ์šฐ ๋…ธ๋“œ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋ฅผ ์ถœ๋ ฅํ•˜์ž.

    4. ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ ์˜์‚ฌ ์ฝ”๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. ์ธ์ ‘ ์ •์ ์€ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•œ๋‹ค.

    5. ์ฒซ์งธ ์ค„์— ์ •์ ์˜ ์ˆ˜ N (5 โ‰ค N โ‰ค 100,000), ๊ฐ„์„ ์˜ ์ˆ˜ M (1 โ‰ค M โ‰ค 200,000), ์‹œ์ž‘ ์ •์  R (1 โ‰ค R โ‰ค N)์ด ์ฃผ์–ด์ง„๋‹ค.

    6. ๋‹ค์Œ M๊ฐœ ์ค„์— ๊ฐ„์„  ์ •๋ณด u v๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ ์ •์  u์™€ ์ •์  v์˜ ๊ฐ€์ค‘์น˜ 1์ธ ์–‘๋ฐฉํ–ฅ ๊ฐ„์„ ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.
      (1 โ‰ค u < v โ‰ค N, u โ‰  v) ๋ชจ๋“  ๊ฐ„์„ ์˜ (u, v) ์Œ์˜ ๊ฐ’์€ ์„œ๋กœ ๋‹ค๋ฅด๋‹ค.

    7. ์ฒซ์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์ •์ˆ˜๋ฅผ ํ•œ ๊ฐœ์”ฉ ์ถœ๋ ฅํ•œ๋‹ค. i๋ฒˆ์งธ ์ค„์—๋Š” ์ •์  i์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
      ์‹œ์ž‘ ์ •์ ์˜ ๋ฐฉ๋ฌธ ์ˆœ์„œ๋Š” 1์ด๋‹ค. ์‹œ์ž‘ ์ •์ ์—์„œ ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ 0์„ ์ถœ๋ ฅํ•œ๋‹ค.

    8. DFS, ์ •๋ ฌ ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ 1

    5 5 1
    1 4
    1 2
    2 3
    2 4
    3 4

    ์‹คํ–‰๊ฒฐ๊ณผ 1

    1
    4
    3
    2
    0

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ๋ฌธ์ œ์˜ ์ง€๋ฌธ์„ ๋จผ์ € ์ž˜ ์‚ดํŽด๋ณด์ž.
      ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„(undirected graph), ์ธ์ ‘ ์ •์ ์€ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธ,

    2. ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋Š” ์–‘๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ„์„  ์ •๋ณด๋ฅผ ๊ทธ๋ž˜ํ”„์— ์ €์žฅํ•  ๋•Œ a์—์„œ b, b์—์„œ a๋ฅผ ์ €์žฅํ•ด์ค˜์•ผ ํ•œ๋‹ค.

    3. ์ธ์ ‘ ์ •์ ์€ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋ฐฉ๋ฌธํ•œ๋‹ค๊ณ  ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋ฐฉ๋ฌธ์ด ๊ฐ€๋Šฅํ•œ ๋‹ค์Œ ๋…ธ๋“œ๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์„ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

    4. (3), (4)๋ฒˆ์„ ์œ ์˜ํ•ด์•ผํ•˜๋ฉฐ, ํŒŒ์ด์ฌ์˜ ๊ฒฝ์šฐ setrecursionlimit์„ ํ•˜๋Š”๊ฒŒ ์•ˆ์ „ํ•˜๋‹ค.

    5. ๋ฐฉ๋ฌธ์„ ํ•˜๋ฉด์„œ ๋ฐฉ๋ฌธํ•œ ์ˆœ์„œ๋ฅผ visited(๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๋ฐฐ์—ด)์— ์ ์–ด ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin, setrecursionlimit
    
    setrecursionlimit(10 ** 7)
    
    n, m, r = map(int, stdin.readline().split())
    graph = [[] for _ in range(n + 1)]
    visited = [0 for _ in range(n + 1)]
    cnt = 1
    
    for _ in range(m):
        a, b = map(int, stdin.readline().split())
        graph[a].append(b)
        graph[b].append(a)
    
    
    def dfs(r):
        global cnt
        visited[r] = cnt
        graph[r].sort(reverse=True)
        for node in graph[r]:
            if visited[node] == 0:
                cnt += 1
                dfs(node)
    
    
    dfs(r)
    for i in visited[1:]:
        print(i)
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.