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

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().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 = LI()
    mem = [[INF for _ in range(n)] for _ in range(n)]
    for i in range(m):
        a, b, c = LI()
        mem[a-1][b-1] = c
        mem[b-1][a-1] = c
    for i in range(n):
        mem[i][i] = 0
    mem = warshall_floyd(mem, n)
    new_mem = [[INF for _ in range(n)] for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if mem[i][j] <= l:
                new_mem[i][j] = 1

    new_mem = warshall_floyd(new_mem, n)
    q = II()
    for i in range(q):
        s, t = LI()
        print(new_mem[s-1][t-1] - 1 if new_mem[s-1][t-1] < INF else -1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,m,l=map(int,input().split())
G=[[] for i in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split())
    if c>l:
        pass
    else:
        G[a-1].append((b-1,c))
        G[b-1].append((a-1,c))
INF=10**9
ans=[]
for i in range(n):
    d=[(INF,INF)]*n
    used=[False]*n
    d[i]=(0,l)
    while True:
        v=-1
        for j in range(n):
            if not used[j]:
                if v==-1:
                    v=j
                else:
                    if d[j][0]<d[v][0]:
                        v=j
                    elif d[j][0]==d[v][0]:
                        if d[j][1]>d[v][1]:
                            v=j
        if v==-1:
            break
        used[v]=True
        for j in G[v]:
            if d[v][1]<j[1]:
                x=d[v][0]+1
                y=l-j[1]
            else:
                x=d[v][0]
                y=d[v][1]-j[1]
            if x<d[j[0]][0]:
                d[j[0]]=(x,y)
            elif x==d[j[0]][0]:
                if y>d[j[0]][1]:
                    d[j[0]]=(x,y)
    ans.append(d)
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    if ans[s-1][t-1]==(INF,INF):
        print(-1)
    else:
        print(ans[s-1][t-1][0])

Submission status: Accepted

Solution code:
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

################################

n,m,l = map(int,input().split()) #n:頂点数　w:辺の数

cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(m):
    x,y,z = map(int,input().split())
    cost[x-1][y-1] = z
    cost[y-1][x-1] = z

kyolist=[]
for i in range(n):
    kyolist.append(dijkstra(i,n,m,cost))
zerolist=[]

for i in range(n):
    nowzero=[]
    for j in range(n):
        if i!=j and kyolist[i][j]<=l:
            nowzero.append(j)
    zerolist.append(nowzero)


llist=[]
for i in range(n):
    nowlist=[1000]*n
    nowlist[i]=0
    next=[i]
    now=0
    while next!=[]:
        newnext=[]
        for nx in next:
            for ima in zerolist[nx]:
                if nowlist[ima]==1000:
                    nowlist[ima]=now
                    newnext.append(ima)
        next=newnext
        now+=1
    llist.append(nowlist)

q=int(input())
for i in range(q):
    s, t = (int(i) for i in input().split())
    kotae=llist[s-1][t-1]
    if kotae==1000:
        print(-1)
    else:
        print(kotae)

Submission status: Accepted

Solution code:
inf = 10**10
def warshall_floyd(d):#d[u][v]:辺uvのコスト.存在しなければinf.d[i][i]は0
    for i in range(N):#0~iとa, bのみを使う最短経路を考える
        for a in range(N):
            for b in range(N):
                d[a][b] = min(d[a][b], d[a][i]+ d[i][b])#頂点iを使う場合と使わない場合
    return d
N, M, L = map(int, input().split())
G = [[inf]*N for _ in range(N)]
for i in range(N):
    G[i][i] = 0
for _ in range(M):
    a, b, c = map(int, input().split())
    G[a-1][b-1] = c
    G[b-1][a-1] = c
G = warshall_floyd(G)
G2 = [[0]*N for _ in range(N)]
for i in range(N):
    for j in range(N):
        if i == j:
            G2[i][j] = 0
        elif G[i][j]<=L:
            G2[i][j] = 1
        else:
            G2[i][j] = inf
d = warshall_floyd(G2)
Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    ans = d[s-1][t-1]-1
    print(ans if ans < 10**9 else -1)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import numpy as np
n,m,l,*L=map(int,open(0).read().split())
abc=L[:3*m];st=L[3*m+1:]
town=[[float("inf")]*n for _ in range(n)]
for a,b,c in zip(*[iter(abc)]*3):
	if c<=l:
		town[a-1][b-1]=c
fw=floyd_warshall(town,0)
ti=floyd_warshall(np.where(fw<=l,1,fw),0)
for s,t in zip(*[iter(st)]*2):
	if ti[s-1,t-1]==float("inf"):
		print(-1)
	else:
		print(int(ti[s-1,t-1]-1))

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
import sys
input = sys.stdin.readline

def main():
    INF = float("Inf")
    n,m,l = map(int, input().split())
    G = [[INF]*n for i in range(n)]
    for i in range(n):
        G[i][i] = 0
    for i in range(m):
        a,b,c = map(int, input().split())
        a,b = a-1,b-1
        if c <= l:
            G[a][b] = G[b][a] = c
    G = floyd_warshall(G, directed=False)
    G = np.where(G <=l, 1, INF)
    for i in range(n):
        G[i][i] = 0
    GG = floyd_warshall(G, directed=False)

    q = int(input())
    ans = []
    for i in range(q):
        s,t = map(int, input().split())
        a = GG[s-1][t-1]
        if a == INF:
            a = 0
        else:
            a = int(a)
        ans.append(a-1)
    print(*ans, sep="\n")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
INF = 10**12

n, m, l = [int(item) for item in input().split()]
dist = [[INF] * n for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1
    dist[a][b] = c
    dist[b][a] = c

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

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:
            dist[i][j] = 0
        elif dist[i][j] <= l:
            dist[i][j] = 1
        else:
            dist[i][j] = INF

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

q = int(input())
for i in range(q):
    s, t = [int(item) - 1 for item in input().split()]
    if dist[s][t] == INF:
        print(-1)
    else:
        print(dist[s][t] - 1)

Submission status: Accepted

Solution code:
import sys

def solve():
	input=sys.stdin.readline
	n, m, l = map(int, input().split())
	edge = [[] for _ in range(n)]
	for _ in range(m):
		a, b, c = map(int, input().split())
		if c <= l:
			edge[a-1].append((c, b-1))
			edge[b-1].append((c, a-1))
	inf = 10 ** 20
	dist = [[inf for _ in range(n)]for i in range(n)]
	for i in range(n):
		dist[i][i]=0
		for c, b in edge[i]:
			dist[i][b]=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])
				
	dist2 = [[n+50 for j in range(n)] for i in range(n)]
	for i in range(n):
		dist2[i][i] = 0
		for j in range(i+1, n):
			if dist[i][j] <= l:
				dist2[i][j] = 1
				dist2[j][i] = 1
	for k in range(n):
		for i in range(n):
			for j in range(n):
				dist2[i][j] = min(dist2[i][k] + dist2[k][j], dist2[i][j])
	q = int(input())		
	for i in range(q):
		s, t = map(int, input().split())
		print(dist2[s-1][t-1] - 1 if dist2[s-1][t-1] < n+50 else -1)
	return 0
	
if __name__ == '__main__':
	solve()

Submission status: Accepted

Solution code:
def main():

    import sys
    input = sys.stdin.readline

    n,m,l = map(int,input().split())
    Edge = [list(map(int,input().split())) for i in range(m)]
    q = int(input())
    Query = [list(map(int,input().split())) for i in range(q)]

    D2 = [[float("inf") for i in range(n)] for i in range(n)]
    for i in range(m):
        D2[Edge[i][0]-1][Edge[i][1]-1] = Edge[i][2]
        D2[Edge[i][1]-1][Edge[i][0]-1] = Edge[i][2]
    for i in range(n):
        D2[i][i] = 0

    def warshall_floyd(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

    D2 = warshall_floyd(D2)

    D = [[float("inf") for i in range(n)] for i in range(n)]
    for i in range(m):
        if Edge[i][2] <= l:
            D[Edge[i][0]-1][Edge[i][1]-1] = 1
            D[Edge[i][1]-1][Edge[i][0]-1] = 1
    for i in range(n):
        D[i][i] = 0
    for i in range(n):
        for j in range(n):
            if D2[i][j] <= l:
                D[i][j] = 1

    D = warshall_floyd(D)

    for query in Query:
        if D[query[0]-1][query[1]-1] != float('inf'):
            print(D[query[0]-1][query[1]-1]-1)
        else:
            print(-1)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
sys.setrecursionlimit(10 ** 9)
import math
import heapq
from itertools import product, permutations,combinations
import fractions
from operator import itemgetter

import sys
def input():
	return sys.stdin.readline().strip()

N, M, L = list(map(int, input().split()))

graph = [[] for _ in range(N)]

for i in range(M):
	A, B, C = list(map(int, input().split()))
	if C <= L:
		graph[A - 1].append((B - 1, C))
		graph[B - 1].append((A - 1, C))

num_matrix = [[0]*N for i in range(N)]


for start in range(N):
	dist = [(1000000, 0)]*N
	que = []
	heapq.heappush(que, (0, 0, start))
	dist[start] = (0, 0)
	while len(que) > 0:

		node = heapq.heappop(que)
		#print(start, que, node)
		if node[0] == dist[node[2]][0] and node[1] == dist[node[2]][1]:
			#print(1)
			for edge in graph[node[2]]:
				#print(edge)
				#print(edge[1] + dist[node[2]][1] )
				if edge[1] + dist[node[2]][1] > L:
					next_dist = (dist[node[2]][0] + 1, edge[1], edge[0])
				else:
					next_dist = (dist[node[2]][0], dist[node[2]][1] + edge[1], edge[0])
				if dist[edge[0]][0] > next_dist[0]:
					dist[next_dist[2]] = (next_dist[0], next_dist[1])
					heapq.heappush(que, next_dist)
				elif dist[edge[0]][0] == next_dist[0] and dist[edge[0]][1] > next_dist[1]:
					heapq.heappush(que, next_dist)
					dist[next_dist[2]] = (next_dist[0], next_dist[1])
	for i in range(N):
		num_matrix[start][i] = dist[i][0]

#print(num_matrix)

Q = int(input())
for q in range(Q):
	s, t = list(map(int, input().split()))
	if num_matrix[t - 1][s - 1] < 1000:
		print(num_matrix[t - 1][s - 1])
	else:
		print(-1)

Submission status: Accepted

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


def main():
    N, M, L = map(int, input().split())
    INF = 10**13
    dis = [[INF for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        dis[a-1][b-1] = c
        dis[b-1][a-1] = c
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    for k in range(N):
        for i in range(N):
            for j in range(N):
                dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j])
    
    movable = [[] for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if i != j and dis[i][j] <= L:
                movable[i].append(j)
    

    for s, t in Query:
        s, t = s-1, t-1
        q = movable[s]
        checked = [False]*N
        ok = False
        for p in q:
            if p == t:
                ok = True
                break
            checked[p] = True
        checked[s] = True
        
        if ok:
            print(0)
            continue
        c = 0
        while q:
            c += 1
            qq = []
            for p in q:
                for np in movable[p]:
                    if np == t:
                        ok = True
                        break
                    if not checked[np]:
                        qq.append(np)
                        checked[np] = True
            if ok: break
            q = qq
        if ok:
            print(c)
        else:
            print(-1)



            



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
INF = float('inf')
N, M, L = 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())
  dist[a-1][b-1] = dist[b-1][a-1] = c

# ワーシャルフロイド
for k in range(N):
  for i in range(N-1):
    for j in range(i+1, N):
      t = dist[i][k] + dist[k][j]
      if dist[i][j] > t:
        dist[i][j] = dist[j][i] = t

# 満タンから補給なしで行けるところに辺を張る
dist2 = [[INF]*N for _ in range(N)]
for i in range(N-1):
  for j in range(i, N):
    if dist[i][j] <= L:
      dist2[i][j] = dist2[j][i] = 1

# ワーシャルフロイド
for k in range(N):
  for i in range(N-1):
    for j in range(i+1, N):
      t = dist2[i][k] + dist2[k][j]
      if dist2[i][j] > t:
        dist2[i][j] = dist2[j][i] = t

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

Submission status: Accepted

Solution code:
n,m,l=map(int,input().split())
s=[[float("INF")for i in range(n)]for i in range(n)]
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall as fw
for i in range(m):
    a,b,c=map(int,input().split())
    s[a-1][b-1]=c
    s[b-1][a-1]=c
s=fw(s)
t=[[float("INF")for i in range(n)]for i in range(n)]
for i in range(n):
    for j in range(n):
        if s[i][j]<=l:
            t[i][j]=1
t=fw(t)
for i in range(int(input())):
    a,b=map(int,input().split())
    if t[a-1][b-1]!=float("INF"):
        print(int(t[a-1][b-1])-1)
    else:
        print(-1)

Submission status: Accepted

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

N, M, L = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
Q = int(input())
ST = [[int(_) for _ in input().split()] for _ in range(Q)]
edge = np.full((N, N), 10**10, dtype=int)
for a, b, c in ABC:
    if c <= L:
        edge[a - 1][b - 1] = edge[b - 1][a - 1] = c
G = csgraph_from_dense(edge, null_value=10**10)
D = floyd_warshall(G)
D = D <= L
E = floyd_warshall(D)
INF = float('inf')
for s, t in ST:
    d = E[s - 1][t - 1]
    if d == INF:
        d = 0
    print(int(d) - 1)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


from heapq import heappush, heappop


def dijkstra(graph: list, start, INF=float('inf')) -> list:
    n = len(graph)
    dist = [INF] * n
    visited = [False] * n

    dist[start] = 0
    que = [(0, start)]

    while que:
        cost, cur = heappop(que)

        if visited[cur]:
            continue

        visited[cur] = True

        for nextnode, edgecost in graph[cur]:
            nextcost = cost + edgecost
            if nextcost < dist[nextnode]:
                dist[nextnode] = nextcost
                heappush(que, (nextcost, nextnode))

    return dist

n, m, l = li()
graph = [[] for _ in range(n)]
costgraph = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = li()
    a -= 1
    b -= 1
    graph[a].append((b, c))
    graph[b].append((a, c))

for st in range(n):
    dist = dijkstra(graph, st)
    for ds in range(n):
        if st == ds:
            continue

        if dist[ds] <= l:
            costgraph[st].append((ds, 1))

q = ni()
INF = float("inf")

dist = [[INF]*n for _ in range(n)]
for i in range(n):
    dist[i] = dijkstra(costgraph, i, INF)

for _ in range(q):
    st, ds = li_()
    if dist[st][ds] == INF:
        print(-1)
    else:
        print(dist[st][ds] - 1)

Submission status: Accepted

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

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

INF = float("INF")

d = [[INF] * n for _ in range(n)]
for i in range(n):
    d[i][i] = 0

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

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

# print()
# print(*d, sep='\n')

for i in range(n):
    for j in range(n):
        if i == j:
            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):
            if d[i][j] > d[i][k] + d[k][j]:
                d[i][j] = d[i][k] + d[k][j]

# print()
# print(*d, sep='\n')

q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1

    if d[s][t] == INF:
        print(-1)
    else:
        print(d[s][t]-1)

Submission status: Runtime Error

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

N,M,L=map(int,input().split())
INF = 1 << 31
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

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

dist = floyd_warshall(dist)

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

dist = floyd_warshall(dist)
#dist[dist==INF]=0
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

print(*ans,sep='\n')

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from scipy.sparse.csgraph import floyd_warshall

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

graph = defaultdict(list)

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


def dfs(u):
    dist = [-1] * (n + 1)
    stack = [u]
    dist[u] = 0
    while stack:
        u = stack.pop()
        for v, d in graph[u]:
            nxt = dist[u] + d
            if dist[v] == -1 or dist[v] > nxt:
                dist[v] = nxt
                stack.append(v)
    return dist


dist = [[0] * n for _ in range(n)]
for i in range(1, n + 1):
    dist[i - 1] = dfs(i)[1:]

dist = np.array(dist)

graph2 = np.full((n, n), np.inf)
graph2[dist <= l] = 1
dist = floyd_warshall(graph2, directed=False)
dist = dist.astype(int)

q = int(input())

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

print(*ans, sep="\n")

Submission status: Runtime Error

Solution code:
from collections import defaultdict
sys.setrecursionlimit(10**7)

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

graph = defaultdict(list)

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


def dfs(u, l, rest):
    dist = [-1] * (n + 1)
    stack = [u]
    dist[u] = 0
    while stack:
        u = stack.pop()
        tmp_rest = rest
        for v, d in graph[u]:
            rest = tmp_rest
            rest -= d
            if rest < 0:
                nxt = dist[u] + 1
                rest = l
            else:
                nxt = dist[u]
            if dist[v] == -1 or dist[v] > nxt:
                dist[v] = nxt
                stack.append(v)
    return dist


q = int(input())

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

print(ans, sep="\n")

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    def dfs(start, v, p, tot_d):
        for d, u in edge[v]:
            if u == p:
                continue
            if tot_d + d > l:
                dp[start][u] = min(dp[start][u], dp[start][v] + 1)
                tot_d = d
            else:
                dp[start][u] = min(dp[start][u], dp[start][v])
                tot_d += d
            dfs(start, u, v, tot_d)

    n, m, l = map(int, input().split())
    edge = [[] for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        if c > l:
            continue
        edge[a - 1].append([c, b - 1])
        edge[b - 1].append([c, a - 1])

    # dp[i][j]:iからスタートしてjに行くまでに補給する最小回数
    dp = [[f_inf] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = 0
        dfs(i, i, - 1, 0)

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

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
N,M,L=map(int,input().split())
A=[[] for i in range(N)]
for i in range(M):
    a,b,c=map(int,input().split())
    A[a-1].append((b-1,c))
    A[b-1].append((a-1,c))
d=[[100000000001]*N for i in range(N)]
for i in range(N):
    d[i][i]=0
for i in range(N):
    for to,cost in A[i]:
        d[i][to] = cost
for k in range(N):
    for i in range(N):
        for j in range(N):
            if d[i][k] != 100000000001 and d[k][j] != 100000000001:
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
B=[[] for i in range(N)]
for i in range(N):
    for j in range(N):
        if d[i][j]<=L:
            B[i].append((j,1))
times=[[100000000001]*N for i in range(N)]
for i in range(N):
    times[i][i]=0
for i in range(N):
    for to,cost in B[i]:
        times[i][to] = cost
for k in range(N):
    for i in range(N):
        for j in range(N):
            if times[i][k] != 100000000001 and times[k][j] != 100000000001:
                times[i][j] = min(times[i][j], times[i][k] + times[k][j])
Q=int(input())
for i in range(Q):
    s,t=map(int,input().split())
    if times[s-1][t-1]!=100000000001
    	print(times[s-1][t-1]-1)
    else:
      	print(-1)