목차

소수 경로

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()