Algorithm/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€ (BOJ) / Python] 18352๋ฒˆ: ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ

meeeeejin 2021. 3. 30. 17:24

๋ฌธ์ œ ๋งํฌ: www.acmicpc.net/problem/18352

 

18352๋ฒˆ: ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ N, ๋„๋กœ์˜ ๊ฐœ์ˆ˜ M, ๊ฑฐ๋ฆฌ ์ •๋ณด K, ์ถœ๋ฐœ ๋„์‹œ์˜ ๋ฒˆํ˜ธ X๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 300,000, 1 ≤ M ≤ 1,000,000, 1 ≤ K ≤ 300,000, 1 ≤ X ≤ N) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ๋‘ ๊ฐœ

www.acmicpc.net

 

๋ฌธ์ œ ์„ค๋ช…

  • BFS๋ฅผ ์ด์šฉํ•˜์—ฌ ๋„์‹œ๋ฅผ ๋ชจ๋‘ ๋ฐฉ๋ฌธํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ด์šฉํ•˜์˜€๋‹ค.
  • BFS๋ฅผ ํ•˜๋Š” ์ค‘ ๋งŒ์•ฝ ํ˜„์žฌ ๋„์‹œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ๊ฐ’์ด k ๋ณด๋‹ค ํด ๊ฒฝ์šฐ, ์ด ๋’ค์— ๋ฐฉ๋ฌธํ•˜๋Š” ๋„์‹œ๋“ค์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋Š” ๋ชจ๋‘ k๋ณด๋‹ค ํฌ๋ฏ€๋กœ BFS๋ฅผ ์ค‘์ง€ํ•œ๋‹ค. 

 

solution ํ•จ์ˆ˜ ์„ค๋ช…

  1. ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k์ธ ๋„์‹œ๋“ค์„ ๋‹ด์„ ๋ฆฌ์ŠคํŠธ answer ์ดˆ๊ธฐํ™”
  2. ์ถœ๋ฐœ ๋„์‹œ๋ฅผ ํ์— ์‚ฝ์ž…ํ•˜๊ณ , ์ถœ๋ฐœ ๋„์‹œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ 0์œผ๋กœ ์ฒ˜๋ฆฌ
  3. ํ์—์„œ ์›์†Œ๋ฅผ ํ•˜๋‚˜ ๊บผ๋‚ด๊ณ  ๋งŒ์•ฝ ํ•ด๋‹น ์›์†Œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k๋ผ๋ฉด answer์— ์‚ฝ์ž…
  4. ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ํ•ด๋‹น ์›์†Œ์™€ ์ธ์ ‘ํ•œ ๋„์‹œ๋“ค์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ๊ฐฑ์‹ 
  5. 3~4๋ฅผ ํ˜„์žฌ ๋ฐฉ๋ฌธ ๋„์‹œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k ์ดํ•˜์ผ ๋•Œ ๋ฐ˜๋ณต

 

 

 

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

from collections import deque
import sys
input = sys.stdin.readline
INF = int(1e9)

# ๋„์‹œ ๊ฐœ์ˆ˜, ๋„๋กœ ๊ฐœ์ˆ˜, ์ตœ๋‹จ ๊ฑฐ๋ฆฌ, ์ถœ๋ฐœ ๋„์‹œ
n, m, k, x = map(int, input().split())
# ๊ฐ ๋„์‹œ์— ์—ฐ๊ฒฐ๋œ ๋„๋กœ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ๋ฆฌ์ŠคํŠธ
graph = [[] for i in range(n + 1)]
# ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”
distance = [INF] * (n + 1)

# ๋ชจ๋“  ๋„๋กœ ์ •๋ณด ์ž…๋ ฅ ๋ฐ›๊ธฐ
for _ in range(m):
    i, j = map(int, input().split())
    graph[i].append(j)  # ๋„์‹œ i์—์„œ ๋„์‹œ j๊นŒ์ง€ ๋„๋กœ๊ฐ€ ์กด์žฌ

def solution(start):
    answer = []
    queue = deque([start])
    distance[start] = 0
    # bfs ๋ฐฉ์‹์œผ๋กœ ์ธ์ ‘ ๋„์‹œ๋“ค ๋ฐฉ๋ฌธ
    while queue:
        v = queue.popleft()
        if distance[v] == k:
            answer.append(v)
        if distance[v] > k: # ๋‚˜๋จธ์ง€ ๋„์‹œ๋“ค์€ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k ์ด์ƒ
            return answer
        for x in graph[v]:
            # ํ˜„์žฌ ๋„์‹œ v๋ฅผ ๊ฑฐ์ณ์„œ ๋„์‹œ x๊นŒ์ง€ ๊ฐ€๋Š”๊ฒŒ ๋” ์งง์€ ๊ฒฝ์šฐ
            if distance[v] + 1 < distance[x]:
                distance[x] = distance[v] + 1
                queue.append(x)
    
    return answer

answer = solution(x)
if answer:
    answer.sort()
    for x in answer: print(x)
else:
    print(-1)

 

 

 

 

728x90