Problem:


Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0



Sample input:
3 2 5
1 2 3
2 3 3
2
3 2
1 3


Sample output:
0
1

Submission status: Accepted

Solution code:
import sys
imput = sys.stdin.readline
def func(d):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d
N,M,L = map(int,input().split())
road = [[10**10]*N for i in range(N)]
for i in range(N):
    road[i][i] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    road[a-1][b-1] = c
    road[b-1][a-1] = c
road = func(road)
ans = [[10**5]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        if road[i][j] <= L:
            ans[i][j] = 1
ans = func(ans)
for i in range(int(input())):
    a,b = map(int,input().split())
    o = ans[a-1][b-1]
    if o == 10**5:
        print(-1)
    else:
        print(o-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
INF = float('inf')

N, M, L = map(int, input().split())
ABC = [tuple(map(int, input().split())) for _ in range(M)]
Q = int(input())
ST = [tuple(map(int, input().split())) for _ in range(Q)]

dist = [[INF] * N for _ in range(N)]
fuel = [[INF] * N for _ in range(N)]

for i in range(N):
    dist[i][i] = 0
    fuel[i][i] = 0

for fr, to, cost in ABC:
    if cost > L:
        continue
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

for k in range(N):
    for i in range(N):
        for j in range(N):
            d = dist[i][k] + dist[k][j]
            if dist[i][j] > d:
                dist[i][j] = d
            if d <= L:
                fuel[i][j] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            d = fuel[i][k] + fuel[k][j]
            if fuel[i][j] > d:
                fuel[i][j] = d

for start, end in ST:
    print(fuel[start - 1][end - 1] - 1 if fuel[start - 1][end - 1] != INF else -1)

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import floyd_warshall


def main():
    n, m, le = map(int, input().split())
    g1 = (le + 1) * np.zeros((n, n))
    for _ in range(m):
        a, b, c = map(int, input().split())
        if c <= le:
            g1[a - 1, b - 1] = c
            g1[b - 1, a - 1] = c

    fw1 = floyd_warshall(g1, directed=False)

    g2 = 1000 * np.zeros((n, n))
    g2[fw1 <= le] = 1

    fw2 = floyd_warshall(g2, directed=False)

    q = int(input())
    res_list = [-1] * q
    for i in range(q):
        s, t = map(int, input().split())
        res = fw2[s - 1, t - 1]
        if res <= n:
            res_list[i] = int(res - 1)

    for r in res_list:
        print(r)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]
for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))


def warshall_floid(graph):
    """warshall-floid法: 各頂点から各頂点への最短距離を求める
    重み付きグラフgraphは隣接リストで与えられる
    計算量: O(|N|^3)
    """
    n = len(graph)
    INF = 10**18
    dp = [[INF]*n for i in range(n)]
    for i in range(n):
        dp[i][i] = 0

    for i in range(n):
        for j, cost in graph[i]:
            dp[i][j] = cost
            dp[j][i] = cost

    for k in range(n):
        for i in range(n):
            for j in range(n):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

    return dp

def warshall_floid_matrix(matrix):
    """warshall-floid法: 各頂点から各頂点への最短距離を求める
    matrix[i][j] := 頂点iから頂点jへの距離（頂点iから頂点jへ到達できないときはINFを代入しておく）
    計算量: O(|N|^3)
    """
    n = len(matrix)
    dp = matrix
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
    return dp

dp1 = warshall_floid(graph)
INF = 10**18
dp2 = [[INF]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        if dp1[i][j] <= l:
            dp2[i][j] = 1
ans = warshall_floid_matrix(dp2)         

q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    if ans[a][b] == 10**18:
        print(-1)
    else:
        print(ans[a][b] - 1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]
 
for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))


def warshall_floid(graph):
    n = len(graph)
    INF = 10**18
    dp = [[INF]*n for i in range(n)]
    for i in range(n):
        dp[i][i] = 0

    for i in range(n):
        for j, cost in graph[i]:
            dp[i][j] = cost
            dp[j][i] = cost

    for k in range(n):
        for i in range(n):
            for j in range(n):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

    return dp

def warshall_floid2(matrix):
    n = len(matrix)
    dp = matrix
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
    return dp

dp1 = warshall_floid(graph)
INF = 10**18
dp2 = [[INF]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        if dp1[i][j] <= l:
            dp2[i][j] = 1
ans = warshall_floid2(dp2)         

q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    if ans[a][b] == 10**18:
        print(-1)
    else:
        print(ans[a][b] - 1)

Submission status: Accepted

Solution code:
def wf(l, n):
    for i in range(n):
        for j in range(n):
            for k in range(n):
                l[j][k] = min(l[j][k], l[j][i] + l[i][k])
    return l


def main():
    n, m, l = map(int, input().split())

    l1 = [[10 ** 15 for i in range(n)] for i in range(n)]

    for _ in range(m):
        a, b, c = map(int, input().split())
        l1[a - 1][b - 1] = c
        l1[b - 1][a - 1] = c

    l1 = wf(l1, n)

    l2 = [[10 ** 4 for i in range(n)] for i in range(n)]

    for i in range(n):
        for j in range(n):
            if l1[i][j] <= l:
                l2[i][j] = 1

    l2 = wf(l2, n)

    q = int(input())
    lq = []
    for _ in range(q):
        lq.append(list(map(int, input().split())))

    for sq in lq:
        res = l2[sq[0] - 1][sq[1] - 1]
        if res == 10 ** 4:
            print(-1)
        else:
            print(res - 1)


main()

Submission status: Accepted

Solution code:
import sys

N, M, L = list(map(int, input().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
Q = int(input())
st = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

inf = 10 ** 10
D = [[inf] * N for _ in range(N)]
R = {}

for a, b, c in ABC:
  a -= 1
  b -= 1
  D[a][b] = c
  D[b][a] = c
  if a not in R:
    R[a] = [[b, c]]
  else:
    R[a].append([b, c])
  if b not in R:
    R[b] = [[a, c]]
  else:
    R[b].append([a, c])

for i in range(N):
  D[i][i] = 0

for k in range(N):
  for i in range(N):
    for j in range(N):
      D[i][j] = min(D[i][j], D[i][k] + D[k][j])


for i in range(N):
  for j in range(N):
    if i == j:
      D[i][j] = 0
      continue
    if D[i][j] <= L:
      D[i][j] = 1
    else:
      D[i][j] = inf

for k in range(N):
  for i in range(N):
    for j in range(N):
      D[i][j] = min(D[i][j], D[i][k] + D[k][j])

for s, t in st:
  s -= 1
  t -= 1
  if D[s][t] == inf:
    print(-1)
  else:
    print(D[s][t] - 1)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    n,m,l = map(int,input().split())
    d = [[10**12]*n for _ in [0]*n]
    for i in range(m):
        a,b,c = map(int,input().split())
        if l >= c:
            d[a-1][b-1] = d[b-1][a-1] = c
    for i in range(n):
        d[i][i] = 0

    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])

    edge = [[10**12]*n for _ in [0]*n]
    for i in range(n):
        for j in range(n):
            if d[i][j] <= l:
                edge[i][j] = 1

    for k in range(n):
        for i in range(n):
            for j in range(n):
                edge[i][j] = min(edge[i][j],edge[i][k] + edge[k][j])

    q = int(input())
    for _ in [0]*q:
        s,t = map(int,input().split())
        if edge[s-1][t-1] >= 10**12:
            print(-1)
        else:
            print(edge[s-1][t-1]-1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
from bisect import bisect_left, bisect_right
import random
from itertools import permutations, accumulate, combinations
import sys
import string



INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


def warshall_floyd(graph):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                graph[i][j] = min(graph[i][j],graph[i][k] + graph[k][j])
    return graph



n, m, l = LI()
graph = [[INF] * n for _ in range(n)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(m):
    a, b, c = LI()
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c
for i in range(n):
    graph[i][i] = 0


supply_num_graph = [[INF] * n for _ in range(n)]
min_dist = warshall_floyd(graph)
for j in range(n):
    for k in range(j + 1, n):
        if min_dist[j][k] <= l:
            supply_num_graph[j][k] = 1
            supply_num_graph[k][j] = 1

supply_num_graph = warshall_floyd(supply_num_graph)
q = I()
for i in range(q):
    s, t = LI()
    if supply_num_graph[s - 1][t - 1] == INF:
        print(-1)
    else:
        print(supply_num_graph[s - 1][t - 1] - 1)

Submission status: Accepted

Solution code:
n, m, l = map(int, input().split())

l1 = [[10 ** 15 for i in range(n)] for i in range(n)]
for i in range(n):
    l1[i][i] = 0

for _ in range(m):
    a, b, c = map(int, input().split())
    l1[a - 1][b - 1] = c
    l1[b - 1][a - 1] = c

for i in range(n):
    for j in range(n):
        for k in range(n):
            l1[j][k] = min(l1[j][k], l1[j][i] + l1[i][k])

l2 = [[10 ** 4 for i in range(n)] for i in range(n)]
for i in range(n):
    l2[i][i] = 0

for i in range(n):
    for j in range(n):
        if l1[i][j] <= l:
            l2[i][j] = 1

for i in range(n):
    for j in range(n):
        for k in range(n):
            l2[j][k] = min(l2[j][k], l2[j][i] + l2[i][k])

q = int(input())
lq = []
for _ in range(q):
    lq.append(list(map(int, input().split())))

for sq in lq:
    res = l2[sq[0] - 1][sq[1] - 1]
    if res == 10 ** 4:
        print(-1)
    else:
        print(res - 1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, M, L = map(int, input().split())
INF = float('inf')
VD = [[INF] * N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    VD[a][b] = c
    VD[b][a] = c
for i in range(N):
    VD[i][i] = 0

for k in range(N):
    for i in range(N):
        for j in range(N):
            if VD[i][j] > VD[i][k] + VD[k][j]:
                VD[i][j] = VD[i][k] + VD[k][j]

WD = [[INF] * N for _ in range(N)]
for i in range(N):
    WD[i][i] = 0
    for j in range(i+1,N):
        d = VD[i][j]
        if d <= L:
            WD[i][j] = 1
            WD[j][i] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            if WD[i][j] > WD[i][k] + WD[k][j]:
                WD[i][j] = WD[i][k] + WD[k][j]

Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    print(WD[s-1][t-1]-1 if WD[s-1][t-1] < INF else -1)

Submission status: Accepted

Solution code:
inf = 10**10


def resolve():
    n, m, gas = map(int, input().split())

    costs = [[inf for i in range(n)] for i in range(n)]

    for i in range(len(costs)):
        costs[i][i] = 0
    for i in range(m):
        v1, v2, cost = map(int, input().split())
        costs[v1 - 1][v2 - 1] = cost
        costs[v2 - 1][v1 - 1] = cost

    for k in range(n):
        for i in range(n):
            for j in range(n):
                costs[i][j] = min(costs[i][j], costs[i][k]+costs[k][j])

    cost_with_gas = [[inf for i in range(n)] for i in range(n)]

    for i in range(len(cost_with_gas)):
        cost_with_gas[i][i] = 0
    for i in range(len(cost_with_gas)):
        for j in range(i+1, len(cost_with_gas)):
            if gas - costs[i][j] >= 0:
                cost_with_gas[i][j] = 1
                cost_with_gas[j][i] = 1

    for k in range(n):
        for i in range(n):
            for j in range(n):
                cost_with_gas[i][j] = min(cost_with_gas[i][j], cost_with_gas[i][k]+cost_with_gas[k][j])

    q = int(input())

    for i in range(q):
        from_city, destination = map(int, input().split())
        ans = cost_with_gas[from_city-1][destination-1] -1 if cost_with_gas[from_city-1][destination-1] != inf else -1
        print(ans)

resolve()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc143/submissions/8043786

from heapq import heappush, heappop
import sys

input = sys.stdin.readline

n, m, max_tank = map(int, input().split())

g = tuple(set() for _ in range(n))
for _ in range(m):
    a, b, c = map(int, input().split())
    if c > max_tank:
        continue
    # 燃料不足で通過できない

    a -= 1
    b -= 1
    g[a].add((b, c))
    g[b].add((a, c))
    # 隣接リスト、(行き先、コスト)

inf = n + 10

e = [None] * n
for s in range(n):
    d = [inf] * n
    remains = [0] * n

    d[s] = 0
    remains[s] = max_tank

    h = [(0, -max_tank, s)]
    # (補給回数, タンク残量, 現在位置)

    while h:
        take, tank, v = heappop(h)
        tank *= -1
        if (d[v] < take) or (d[v] == take and remains[v] > tank):
            continue

        for u, c in g[v]:
            if c > tank:
                if (d[u] > take + 1) or (d[u] == take + 1 and remains[u] < max_tank - c):
                    d[u] = take + 1
                    remains[u] = max_tank - c
                    heappush(h, (take + 1, c - max_tank, u))  # -(max_tank - c)
            else:
                if (d[u] > take) or (d[u] == take and remains[u] < tank - c):
                    d[u] = take
                    remains[u] = tank - c
                    heappush(h, (take, c - tank, u))  # -(tank - c)
    e[s] = d

q = int(input())

ans = []
for _ in range(q):
    s, t = map(int, input().split())
    ans.append(e[s - 1][t - 1])

print(*map(lambda x: -1 if x == inf else x, ans), sep='\n')

Submission status: Accepted

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(E):
    N = len(E)
    dist = [[INF for _ in range(N)] for _ in range(N)]
    for v in range(N):
        dist[v][v] = 0
        for u, c in E[v]: dist[v][u] = c
    for k in range(N):        
        for i, j in product(range(N), repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

N, M, L = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((b-1, c))
    E[b-1].append((a-1, c))
dist = floyd_warshall(E)

E_charge = [[] for _ in range(N)]
for u, v in combinations(range(N), 2):
    if dist[u][v] <= L:
        E_charge[u].append((v, 1))
        E_charge[v].append((u, 1))
charge = floyd_warshall(E_charge)

Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    n = charge[s-1][t-1]
    print(n - 1 if n != INF else -1)

Submission status: Accepted

Solution code:
import sys

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()
INF = 10 ** 18

dists = [[INF] * n for _ in range(n)]

for i in range(n):
    dists[i][i] = 0

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if c > l:
        continue
    dists[a][b] = c
    dists[b][a] = c

dists = floyd_warshall(csr_matrix(dists))
refuels = np.ones((n, n), dtype=np.int64)
refuels[dists > l] = INF
refuels = floyd_warshall(csr_matrix(refuels)).astype(np.int64)
refuels[refuels == INF] = 0
refuels -= 1

buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(refuels[s - 1][t - 1])

print('\n'.join(map(str, buf)))

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

N, M, L = map(int, input().split())
G = np.zeros((N, N))
for i in range(M):
    a, b, c = map(int, input().split())
    G[a-1, b-1] = c
    G[b-1, a-1] = c
Q = int(input())    
queries = [ list(map(int, input().split())) for _ in range(Q)]
    
G1 = floyd_warshall(G)
G2 = np.where((G1 <= L) & (G1 > 0), 1, 0)
G3 = floyd_warshall(G2) - np.ones((N, N))

for q in queries:
    ans = G3[q[0]-1, q[1]-1]
    if ans == float('inf'):
        print(-1)
    else:
        print(int(ans))

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
n,m,l = list(map(lambda x:int(x),input().split()))
d = [[float('inf') for i in range(n)] for j in range(n)]
for i in range(n):
    d[i][i] = 0
for i in range(m):
    a,b,c = list(map(lambda x:int(x),input().split()))
    if c <= l:
        d[a-1][b-1] = c
        d[b-1][a-1] = c

d = floyd_warshall(d)

dd = [[float('inf') for i in range(n)] for j in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            dd[i][j] = 1

dd = floyd_warshall(dd)
q = int(input())
for i in range(q):
    s,t = input().split()
    s = int(s)-1
    t = int(t)-1
    if dd[s][t] == float('inf'):
        print(-1)
    else:
        print(int(dd[s][t]-1))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,M,L=map(int,input().split())

A=[[10**12 for i in range(N+1)]for j in range(N+1)]
B=[[10**12 for i in range(N+1)]for j in range(N+1)]
for i in range(M):
    a,b,c=map(int,input().split())
    if c<=L:
        A[a][b]=c
        A[b][a]=c
        B[a][b]=1
        B[b][a]=1
for i in range(N+1):
    A[i][i]=0
    B[i][i]=0   
#print(A)

for c in range(1,N+1):
    for a in range(1,N+1):
        for b in range(1,N+1):
            A[a][b]=min(A[a][b],A[a][c]+A[c][b])
            if A[a][b]<=L:
                B[a][b]=1
#print(A)
for c in range(1,N+1):
    for a in range(1,N+1):
        for b in range(1,N+1):
            B[a][b]=min(B[a][b],B[a][c]+B[c][b])

#print(B)
Q=int(input())
for i in range(Q):
    s,t=map(int,input().split())
    if B[s][t]==10**12:
        print(-1)
    else:
        print(B[s][t]-1)

Submission status: Accepted

Solution code:
def e():
    n, m, l = map(int, input().split())
    dist = [[float('inf') if i != j else 0 for j in range(n)] for i in range(n)]
    fuel = [[float('inf') if i != j else 0 for j in range(n)] for i in range(n)]

    for i in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        dist[a][b] = c
        dist[b][a] = c

    q = int(input())
    li_st = []
    for i in range(q):
        s, t = map(int, input().split())
        li_st.append([s, t])

    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            if dist[i][j] <= l:
                fuel[i][j] = min(1, fuel[i][j])

    for k in range(n):
        for i in range(n):
            for j in range(n):
                fuel[i][j] = min(fuel[i][j], fuel[i][k] + fuel[k][j])

    for s, t in li_st:
        s -= 1
        t -= 1
        if fuel[s][t] == float('inf'):
            print(-1)
        else:
            print(fuel[s][t] - 1)


if __name__ == '__main__':
    e()

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

inf = 300 * (10 ** 9) + 10

n, m, max_tank = map(int, input().split())

dist = [[inf] * n for _ in range(n)]
for i in range(n):
    dist[i][i] = 0

for _ in range(m):
    a, b, c = map(int, input().split())
    if c > max_tank:
        continue
    # 燃料不足で通過できない

    a -= 1
    b -= 1

    dist[a][b] = c
    dist[b][a] = c

for k in range(n):
    for i in range(n):
        for j in range(n):
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

g = [[inf] * n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if dist[i][j] <= max_tank:
            g[i][j] = 0

for i in range(n):
    g[i][i] = 0

for k in range(n):
    for i in range(n):
        for j in range(n):
            g[i][j] = min(g[i][j], g[i][k] + g[k][j] + 1)

q = int(input())
for _ in range(q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    print(-1 if g[s][t] == inf else g[s][t])

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import numpy as np

N, M, L = map(int, input().split())
graph = np.zeros((N, N))
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1][t-1] = graph[t-1][s-1] = w
floyd_warshall(graph, directed=False, overwrite=True)
graph = np.where((graph == 0) | (graph > L), 0.0, 1.0)
floyd_warshall(graph, directed=False, overwrite=True)

Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    ans = graph[s-1][t-1]
    if ans == float("inf"):
        print(-1)
    else:
        print(int(ans - 1))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
# debug = True

debug = False

def dprint(*objects):
    if debug == True:
        print(*objects)

def matdprint(mat):
    if debug == True:
        for i in range(len(mat)):
            for j in range(len(mat[i])):
                print(mat[i][j], end=', ')
            print()

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()

INF = 10 ** 18
MOD = 10 ** 9 + 7
def conv(s):
    cnt = 0
    for n in s:
        cnt += 2**n
    return cnt

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    n = len(d)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d


def nr_warshall_floyd(nr, d, L):
    #nr[i][j]: (iからjへの最短補給回数, iからjへ最短補給回数でやった時の残り燃料)
    n = len(d)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                # そもそもkルートが可能か判断
                if d[i][k] == INF:
                    continue
                if d[k][j] == INF:
                    continue

                # kで補給がいるかの判断
                num_at_k = nr[i][k][0]
                res_at_k = nr[i][k][1]

                num_at_j = num_at_k + nr[k][j][0]
                res_at_j = res_at_k - d[k][j]
                if d[k][j] > res_at_k:
                    # 補給が必要。補給してすすむ
                    num_at_j += 1
                    res_at_j = L - d[k][j]
                else:
                    # 補給がいらない
                    pass

                if num_at_j < nr[i][j][0]:
                    # 採用
                    nr[i][j] = (num_at_j, res_at_j)
                elif num_at_j > nr[i][j][0]:
                    # 不採用
                    pass
                else:
                    # 等しいときは残り燃料で比べる
                    nr[i][j] = (num_at_j, min(nr[i][j][1], res_at_j))
    return nr

def main():

    N, M, L = LI()
    abc_list = []
    for i in range(M):
        a, b, c = LI()
        abc_list.append((a-1,b-1,c)) # 0 origin

    q_list = []
    Q = II()
    for i in range(Q):
        s, t = LI()
        q_list.append((s-1, t-1)) # 0 origin

    # ワーシャルフロイドもどきをやる
    dmx = INF
    nmx = N+1
    d = [[dmx for i in range(N)] for i in range(N)]
    nr = [[(nmx, 0) for i in range(N)] for i in range(N)]

    # 初期化
    for i in range(N):
        d[i][i] = 0
        nr[i][i] = (0, L)

    for a, b, c in abc_list:
        if c > L:
            # そもそも燃料が足りず通れないことがある
            pass
        else:
            d[a][b] = c
            d[b][a] = c

            nr[a][b] = (0, L-c)
            nr[b][a] = (0, L-c)

    # 最短経路
    d = warshall_floyd(d)
    # 回数
    # nr = nr_warshall_floyd(nr, d, L)
    # dprint(d)
    # dprint(nr)
    # for s, t in q_list:
    #     ans = nr[s][t][0]
    #     if ans == nmx:
    #         print(-1)
    #     else:
    #         print(ans)

    n = [[nmx for i in range(N)] for i in range(N)]
    for i in range(N):
        for j in range(N):
            if d[i][j] <= L:
                n[i][j] = 1

    n = warshall_floyd(n)

    for s, t in q_list:
        ans = n[s][t]
        if ans == nmx:
            print(-1)
        else:
            print(ans - 1)


main()

Submission status: Accepted

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#ライブラリインポート
from collections import defaultdict

INF = float("inf")

def getlist():
	return list(map(int, input().split()))

def warshall_floyd(d, n):
	for k in range(n):
		for i in range(n):
			for j in range(n):
				d[i][j] = min(d[i][j],d[i][k] + d[k][j])
	return d


#処理内容
def main():
	N, M, L = getlist()
	d = [[float("inf") for i in range(N)] for i in range(N)]
	for i in range(M):
		a, b, w = getlist()
		d[a - 1][b - 1] = w
		d[b - 1][a - 1] = w

	for i in range(N):
		d[i][i] = 0

	d = warshall_floyd(d, N)
	d2 = [[float("inf") for i in range(N)] for i in range(N)]
	for i in range(N):
		for j in range(N):
			if d[i][j] <= L:
				d2[i][j] = 1
	for i in range(N):
		d2[i][i] = 0

	d2 = warshall_floyd(d2, N)

	Q = int(input())
	for i in range(Q):
		s, t = getlist()
		if d2[s - 1][t - 1] == INF:
			print(-1)
		else:
			print(d2[s - 1][t - 1] - 1)



if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, m, l = [ int(v) for v in input().split() ]
distance_list = [ [ 10**15 for i in range(n) ] for j in range(n) ]


for i in range(m): 
    a, b, d = [ int(v) for v in input().split() ]
    a, b = a-1, b-1
    if d <= l:
        distance_list[a][b] = d
        distance_list[b][a] = d

for k in range(n):
    for i in range(n):
        for j in range(n):
            if distance_list[i][j] > distance_list[i][k] + distance_list[k][j]:
                distance_list[i][j] = distance_list[i][k] + distance_list[k][j]


distance_list_2 = [ [ 1 if distance_list[i][j] <= l else 10**4 for i in range(n) ] for j in range(n) ]



for k in range(n):
    for i in range(n):
        for j in range(n):
            if distance_list_２[i][j] > distance_list_２[i][k] + distance_list_２[k][j]:
                distance_list_２[i][j] = distance_list_２[i][k] + distance_list_２[k][j]

q = int(input())
for i in range(q):
    s, t = [ int(v) for v in input().split() ]
    ans = distance_list_２[s-1][t-1]
    if ans == 10000:
        print(-1)
    else:
        print(distance_list_２[s-1][t-1]-1)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for _ in range(m)]
q=int(input())
st=[list(map(int,input().split())) for _ in range(q)]


d = [[float("inf") for i in range(n)] for i in range(n)]

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

for i in range(m):
    a,b,c=abc[i]
    d[a-1][b-1]=c
    d[b-1][a-1]=c

warshall_floyd(d)

dd=[[float("inf") for _ in range(n)] for _ in range(n)]

for i in range(n):
    for j in range(n):
        if i==j:
            dd[i][j]=0
        if d[i][j]<=l:
            dd[i][j]=1
            dd[j][i]=1

warshall_floyd(dd)

for i in range(q):
    s,t=st[i]
    s-=1
    t-=1
    if dd[s][t]==float("inf"):
        print(-1)
    else:
        print(dd[s][t]-1)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import dijkstra as di

inf = float('INF')
n,m,l = map(int,input().split())

route = [[0 for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    route[a-1][b-1] = route[b-1][a-1] = c

p_route = di(route)
p_route[p_route == 0] = inf
p_route[l >= p_route] = 1
p_route[l < p_route] = 0
p_route = di(p_route)

# print(p_route)
query = []
q = int(input())
ans = []
for _ in range(q):
    s,t = map(int, input().split())
    print(-1 if p_route[s-1][t-1] == inf else int(p_route[s-1][t-1]) - 1)