ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 1963 |
문제명 | 소수 경로 |
레벨 | 골드 4 |
분류 |
BFS |
시간복잡도 | O(T) |
인풋사이즈 | T<=? |
사용한 언어 | Python |
제출기록 | 36240KB / 164ms |
최고기록 | 68ms |
해결날짜 | 2022/01/21 |
"""Solution code for "BOJ 1963. 소수 경로".
- Problem link: https://www.acmicpc.net/problem/1963
- Solution link: http://www.teferi.net/ps/problems/boj/1963
Tags: [Prime Number], [BFS]
"""
import itertools
from teflib import numtheory
from teflib import tgraph
INF = float('inf')
def main():
primes = set(numtheory.prime_list(1000, 9999))
graph = [[] for _ in range(10000)]
for num in primes:
for nk, k in itertools.pairwise([10000, 1000, 100, 10, 1]):
beg = num // nk * nk + num % k
graph[num].extend(x for x in range(beg, beg + nk, k) if x in primes)
T = int(input())
for _ in range(T):
source, dest = [int(x) for x in input().split()]
answer = tgraph.min_distance_to_dest(graph, source, dest)
print('Impossible' if answer == INF else answer)
if __name__ == '__main__':
main()