[白准12851]鬼ごっこ2❗
8574 ワード
🥚質問する
https://www.acmicpc.net/problem/12851
🥚入力/出力
🍳コード#コード#
# 출처: https://jaimemin.tistory.com/582
import sys
input = sys.stdin.readline
from collections import deque
def bfs(N, K):
visited = [False]*100001
visited[N] = True
q = deque([(N, 0)])
# 찾을 수 있는 가장 빠른 시간
min_time = float('inf')
# 가장 빠른 시간으로 찾는 방법
min_time_ways = 0
while q:
# q에서 꺼낼 때! 방문 표시를 해주는 것이 핵심이다
x, time = q.popleft()
visited[x] = True
if x == K:
if time < min_time:
min_time = time
min_time_ways = 1
elif time == min_time:
min_time_ways += 1
continue
if 0 <= x - 1 < 100001 and not visited[x-1]:
q.append((x-1, time + 1))
if 0 <= x + 1 < 100001 and not visited[x+1]:
q.append((x+1, time + 1))
if 0 <= x * 2 < 100001 and not visited[x*2]:
q.append((x*2, time + 1))
return min_time, min_time_ways
N, K = map(int, input().split())
min_time, min_time_ways = bfs(N, K)
print(min_time)
print(min_time_ways)
🧂アイデア
BFS
注意:https://jaimemin.tistory.com/582
# 출처: https://jaimemin.tistory.com/582
import sys
input = sys.stdin.readline
from collections import deque
def bfs(N, K):
visited = [False]*100001
visited[N] = True
q = deque([(N, 0)])
# 찾을 수 있는 가장 빠른 시간
min_time = float('inf')
# 가장 빠른 시간으로 찾는 방법
min_time_ways = 0
while q:
# q에서 꺼낼 때! 방문 표시를 해주는 것이 핵심이다
x, time = q.popleft()
visited[x] = True
if x == K:
if time < min_time:
min_time = time
min_time_ways = 1
elif time == min_time:
min_time_ways += 1
continue
if 0 <= x - 1 < 100001 and not visited[x-1]:
q.append((x-1, time + 1))
if 0 <= x + 1 < 100001 and not visited[x+1]:
q.append((x+1, time + 1))
if 0 <= x * 2 < 100001 and not visited[x*2]:
q.append((x*2, time + 1))
return min_time, min_time_ways
N, K = map(int, input().split())
min_time, min_time_ways = bfs(N, K)
print(min_time)
print(min_time_ways)
🧂アイデア
BFS
注意:https://jaimemin.tistory.com/582
他の鬼ごっこ問題とは異なり、最速の時間と最速の時間に何種類の探し方があるのか、一緒に出力する問題もあります.
代表的な反例は以下の通りである.
N=1,K=4の場合,最も速い時間は2,最も速い時間は2種類の検索方法である.
+
1 -> (1 +
1) *
2 *
2 -> (1 *
2) *
2 visited[nr][nc] = True
、q.append((nr, nc))
等の方法でアクセスタグ+キューを挿入する.Reference
この問題について([白准12851]鬼ごっこ2❗), 我々は、より多くの情報をここで見つけました https://velog.io/@eastgloss0330/백준-12851-숨바꼭질-2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol