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

Solution (Python):
def io_tmp():
    global input
    import io, sys
    
    f = io.BytesIO(sys.stdin.buffer.read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = [[float("inf")] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0


Q = int(input())
ans = []
for _ in range(Q):
    s, t = map(int, input().split())
    ans.append(int(dist[s-1][t-1]) - 1)
print(*ans, sep='\n')

Solution (Python):
def io_tmp():
    global input
    import io, sys
    
    f = io.BytesIO(sys.stdin.buffer.read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = [[float("inf")] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
from scipy.sparse import*
f=csgraph.floyd_warshall
I=9e9
i=lambda:map(int,input().split())
n,m,l=i()
d=eval('[I]*-~n,'*-~n)
while m:a,b,c=i();d[a][b]=c;m-=1
d=f(d,0)
d[d>l]=I
d[d<I]=1
d=f(d)
q,=i()
d[d>I]=I
while q:s,t=i();print(int(d[s,t]%I)-1);q-=1

Solution (Python):
def io_tmp():
    global input
    import io, sys
    
    f = io.BytesIO(sys.stdin.buffer.read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[dist == np.inf] = 0.0
dist = dist.astype(np.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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
from scipy.sparse import*
f=csgraph.floyd_warshall
I=9e9
n,m,l,*t=map(int,open(0).read().split())
d=eval('[I]*-~n,'*-~n)
for a,b,c in zip(*[iter(t[:m*3])]*3):d[a][b]=c
d=f(d,0)
d[d>l]=I
d[d<I]=1
d=f(d)
for i in zip(*[iter(t[m*3+1:])]*2):print((I>d[i])*int(d[i])-1)

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = np.zeros((N, N), dtype=np.int64)
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1, t-1] = graph[t-1, s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = dist <= L


dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = np.zeros((N, N), dtype=np.int64)
for _ in range(M):
    s, t, w = map(int, input().split())
    if w <= L:
        graph[s-1, t-1] = graph[t-1, s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = np.ones((N, N))
np.fill_diagonal(graph, 0)
graph[dist > L] = 0
dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = np.zeros((N, N), dtype=np.int64)
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1, t-1] = graph[t-1, s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = np.ones((N, N))
np.fill_diagonal(graph, 0)
graph[dist > L] = np.inf
dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


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

N, M, L = map(int, input().split())
graph = np.zeros((N, N), dtype=np.int64)
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1, t-1] = graph[t-1, s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = np.ones((N, N), dtype=np.int64)
np.fill_diagonal(graph, 0)
graph[dist > L] = 0
dist = floyd_warshall(graph, directed=False)
dist[np.isinf(dist)] = 0
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')

Solution (Python):
def io_tmp():
    global input
    import io
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


from scipy.sparse.csgraph import floyd_warshall


N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = [[0] * N for _ in range(N)]
for i in range(N):
    for j in range(i+1, N):
        if dist[i][j] <= L:
            graph[i][j] = graph[i][j] = 1
dist = floyd_warshall(graph, directed=False)

Q = int(input())
ans = []
for _ in range(Q):
    s, t = map(int, input().split())
    d = dist[s-1][t-1]
    if d == float("inf"):
        ans.append(-1)
    else:
        ans.append(int(d - 1))
print(*ans, sep='\n')

Solution (Python):
def io_tmp():
    global input
    import io, sys
    f = io.StringIO(open(0).read())
    input = f.readline

io_tmp()


from scipy.sparse.csgraph import floyd_warshall


N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = [[0] * N for _ in range(N)]
for i in range(N):
    for j in range(i+1, N):
        if dist[i][j] <= L:
            graph[i][j] = graph[i][j] = 1
dist = floyd_warshall(graph, directed=False)

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

Solution (Python):

def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    V = len(dist)
    for i in range(V):  
        for j, c2 in enumerate(dist[j][i] for j in range(V)):  
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3


def main():
    
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    INF = float("inf")
    dist = [[INF] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        dist[i][i] = 0
    for v, u, cost in zip(*[iter(ABC)] * 3):
        dist[v][u] = dist[u][v] = cost
    floyd_warshall(dist)

    
    modified_dist = [[1 if x <= L else INF for x in d] for d in dist]
    floyd_warshall(modified_dist)
    ans = [
        modified_dist[s][t] - 1 if modified_dist[s][t] != INF else -1
        for s, t in zip(*[iter(ST)] * 2)
    ]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):

def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    for i in range(N + 1):  
        for j, c2 in enumerate(dist[j][i] for j in range(N + 1)):  
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3
    return dist

def main():
    
    global N
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    INF = float("inf")
    dist = [[INF] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        dist[i][i] = 0
    for v, u, cost in zip(*[iter(ABC)] * 3):
        dist[v][u] = dist[u][v] = cost
    dist = floyd_warshall(dist)

    
    modified_dist = [[1 if x <= L else INF for x in d] for d in dist]
    modified_dist = floyd_warshall(modified_dist)
    ans = [
        modified_dist[s][t] - 1 if modified_dist[s][t] != INF else -1
        for s, t in zip(*[iter(ST)] * 2)
    ]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):
def main():
	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:]
	r = [[float("inf")] * n for _ in range(n)]
	for a, b, c in zip(*[iter(abc)] * 3):
		if c <= l: r[a - 1][b - 1] = c
	fw = floyd_warshall(r, 0)
	ans = floyd_warshall(np.where(fw <= l, 1, fw), 0) - 1
	for s, t in zip(*[iter(st)] * 2):
		x = ans[s - 1, t - 1]
		if x == float("inf"):
			print(-1)
		else:
			print(int(x))


if __name__ == "__main__":
	main()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from scipy.sparse.csgraph import floyd_warshall
n,m,L=map(int,input().split())
A=[[INF]*n for _ in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    A[a][b]=A[b][a]=c
A=floyd_warshall(A)
B=[[INF]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if(A[i][j]<=L): B[i][j]=1
B=floyd_warshall(B)
Q=int(input())
for _ in range(Q):
    s,t=map(int,input().split())
    s-=1; t-=1
    print(int(B[s][t])-1 if(B[s][t]!=INF) else -1)

Solution (Python):
from scipy.sparse.csgraph import floyd_warshall


N, M, L = map(int, input().split())
graph = [[0] * N for _ in range(N)]
for _ in range(M):
    s, t, w = map(int, input().split())
    graph[s-1][t-1] = graph[t-1][s-1] = w
dist = floyd_warshall(graph, directed=False)
graph = [[0] * N for _ in range(N)]
for i in range(N):
    for j in range(i+1, N):
        if dist[i][j] <= L:
            graph[i][j] = graph[i][j] = 1
dist = floyd_warshall(graph, directed=False)

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

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix

import numpy as np

N,M,L = map(int,readline().split())
ABCPST = np.array(read().split(),np.int64)
ABC = ABCPST[:M+M+M]
A = ABC[::3]; B = ABC[1::3]; C = ABC[2::3]
ST = ABCPST[M+M+M+1:]
S = ST[::2]; T = ST[1::2]


graph = csr_matrix((C,(A,B)),(N+1,N+1))
dist_mat = floyd_warshall(graph,directed=False)



graph2 = np.full((N+1,N+1),np.inf)
np.fill_diagonal(graph2,0)
graph2[dist_mat<=L] = 1

dist_mat2 = floyd_warshall(graph2,directed=False)

dist_mat2[dist_mat2 == np.inf] = 0
dist_mat2 = (dist_mat2).astype(int)

x = dist_mat2[S,T] - 1

print('\n'.join(x.astype(str)))

Solution (Python):
n,m,L=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
q=int(input())
ql=[list(map(int,input().split())) for i in range(q)]
distance=[[10**18]*n for i in range(n)]
for i in range(m):
  if l[i][2]<=L:
    distance[l[i][0]-1][l[i][1]-1]=l[i][2]
    distance[l[i][1]-1][l[i][0]-1]=l[i][2]
for i in range(n):
  for j in range(n):
    for k in range(n):
      distance[j][k]=min(distance[j][k],distance[j][i]+distance[i][k])
 
distance2=[[10**18]*n for i in range(n)]
for i in range(n):
  for j in range(n):
    if distance[i][j]<=L:
      distance2[i][j]=1
      distance2[j][i]=1
for i in range(n):
  for j in range(n):
    for k in range(n):
      distance2[j][k]=min(distance2[j][k],distance2[j][i]+distance2[i][k])
 
for i in range(q):
  if distance2[ql[i][0]-1][ql[i][1]-1]>=10**18:
    print(-1)
  else:
    print(distance2[ql[i][0]-1][ql[i][1]-1]-1)

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,m,L=map(int,input().split())
    A=[[INF]*n for _ in range(n)]
    for _ in range(m):
        a,b,c=map(int,input().split())
        a-=1; b-=1
        A[a][b]=A[b][a]=c
    from itertools import product
    for k,i,j in product(range(n),repeat=3):
        A[i][j]=min(A[i][j],A[i][k]+A[k][j])
    B=[[INF]*n for _ in range(n)]
    for i,j in product(range(n),repeat=2):
        if(A[i][j]<=L): B[i][j]=1
    for k,i,j in product(range(n),repeat=3):
        B[i][j]=min(B[i][j],B[i][k]+B[k][j])
    Q=int(input())
    for _ in range(Q):
        s,t=map(int,input().split())
        s-=1; t-=1
        print(B[s][t]-1 if(B[s][t]!=INF) else -1)
resolve()

Solution (Python):
import sys

def input():
    return sys.stdin.readline()[:-1]

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

e_list = [[] for i in range(N)]

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

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

for i in range(M):
    x,y,z = list(map(int,input().split()))
    if z<=L:
        d[x-1][y-1] = z
        d[y-1][x-1] = z

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

d = warshall_floyd(d)

e_list = [[] for i in range(N)]

d2 = [[float("inf") for i in range(N)] for i in range(N)]

for i in range(N):
    for j in range(i+1,N):
        if d[i][j] <= L:
            d2[i][j] = 1
            d2[j][i] = 1

d2 = warshall_floyd(d2)

Q = int(input())
for i in range(Q):
    s,t = list(map(int,input().split()))
    s,t = s-1,t-1
    if d2[s][t]>10**9:
        print(-1)
    else:
        print(d2[s][t]-1)

Solution (Python):


import sys
import numpy as np

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall


def main():
    
    read = sys.stdin.buffer.read
    N, M, L, *X = map(int, read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    A, B, C, S, T = ABC[::3], ABC[1::3], ABC[2::3], ST[::2], ST[1::2]

    G = csr_matrix((C, (A, B)), (N + 1, N + 1))
    dist = floyd_warshall(G, directed=0)  

    
    modified_G = np.full((N + 1, N + 1), np.inf)
    np.fill_diagonal(modified_G, 0)
    modified_G[dist <= L] = 1
    modified_dist = floyd_warshall(modified_G, directed=0)
    modified_dist[modified_dist == np.inf] = 0
    modified_dist = (modified_dist).astype(int)

    ans = modified_dist[S, T] - 1
    print("\n".join(ans.astype(str)))


if __name__ == "__main__":
    main()

Solution (Python):

import numpy as np

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall


def main():
    
    global L, G, dist, ancestors
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    A, B, C, S, T = ABC[::3], ABC[1::3], ABC[2::3], ST[::2], ST[1::2]

    G = csr_matrix((C, (A, B)), (N + 1, N + 1))
    dist = floyd_warshall(G, directed=0)

    modified_G = np.full((N + 1, N + 1), np.inf)
    np.fill_diagonal(modified_G, 0)
    modified_G[dist <= L] = 1
    modified_dist = floyd_warshall(modified_G, directed=0)
    modified_dist[modified_dist == np.inf] = 0
    modified_dist = (modified_dist).astype(int)
    
    ans = modified_dist[S, T] - 1
    print("\n".join(ans.astype(str)))


if __name__ == "__main__":
    main()

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
from scipy.sparse import*
f=csgraph.floyd_warshall
I=9e9
n,m,l,*t=map(int,open(0).read().split())
d=eval('[I]*-~n,'*-~n)
for a,b,c in zip(*[iter(t[:m*3])]*3):d[a][b]=d[b][a]=c
d=f(d)
d[d>l]=I
d[d<I]=1
d=f(d)
for i in zip(*[iter(t[m*3+1:])]*2):print((I>d[i])*int(d[i])-1)

Solution (Python):

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

lis = [ [float("inf")] * N for i in range(N) ]


for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    lis[A][B] = C
    lis[B][A] = C
    
for k in range(N):

    for i in range(N):

        for j in range(i):    

            if lis[i][j] > lis[i][k] + lis[k][j]:

                lis[i][j] = lis[i][k] + lis[k][j]
                lis[j][i] = lis[i][k] + lis[k][j]

lis2 = [ [float("inf")] * N for i in range(N) ]


for i in range(N):

    for j in range(i):

        if lis[i][j] <= L:
            lis2[i][j] = 1
            lis2[j][i] = 1

for k in range(N):

    for i in range(N):

        for j in range(i):

            if lis2[i][j] > lis2[i][k] + lis2[k][j]:

                lis2[i][j] = lis2[i][k] + lis2[k][j]
                lis2[j][i] = lis2[i][k] + lis2[k][j]

Q = int(input())

for i in range(Q):

    s,t = map(int,input().split())
    s -= 1
    t -= 1

    if lis2[s][t] == float("inf"):
        print (-1)
    else:
        print (lis2[s][t]-1)

Solution (Python):

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

lis = [ [float("inf")] * N for i in range(N) ]

for i in range(N):

    lis[i][i] = 0

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    lis[A][B] = C
    lis[B][A] = C
    
for k in range(N):

    for i in range(N):

        for j in range(i):    

            if lis[i][j] > lis[i][k] + lis[k][j]:

                lis[i][j] = lis[i][k] + lis[k][j]
                lis[j][i] = lis[i][k] + lis[k][j]

lis2 = [ [float("inf")] * N for i in range(N) ]

for i in range(N):

    lis2[i][i] = 0

for i in range(N):

    for j in range(i):

        if lis[i][j] <= L:
            lis2[i][j] = 1
            lis2[j][i] = 1

for k in range(N):

    for i in range(N):

        for j in range(i):

            if lis2[i][j] > lis2[i][k] + lis2[k][j]:

                lis2[i][j] = lis2[i][k] + lis2[k][j]
                lis2[j][i] = lis2[i][k] + lis2[k][j]

Q = int(input())

for i in range(Q):

    s,t = map(int,input().split())
    s -= 1
    t -= 1

    if lis2[s][t] == float("inf"):
        print (-1)
    else:
        print (lis2[s][t]-1)

Solution (Python):
from scipy.sparse import*
f=csgraph.floyd_warshall
I=9e9
n,m,l,*t=map(int,open(0).read().split())
d=eval('[I]*-~n,'*-~n)
for a,b,c in zip(*[iter(t[:m*3])]*3):d[a][b]=c
d=f(d,0)
d[d>l]=I
d[d<I]=1
d=f(d)
for i in zip(*[iter(t[m*3+1:])]*2):
	print((I>d[i])*int(d[i])-1)

Solution (Python):
import numpy as np
from scipy.sparse.csgraph import dijkstra

N, M, L = map(int, input().split())
abc = []
for _ in range(M):
    abc.append(list(map(int, input().split())))
abc = abc

Q = int(input())
query = []
for _ in range(Q):
    query.append(tuple(map(int, input().split())))
distance = np.zeros((N, N))
for (a, b, c) in abc:
    distance[a - 1, b - 1] = c
    distance[b - 1, a - 1] = c

x = np.where(dijkstra(distance) <= L, 1, 0)
x -= np.eye(N).astype(np.int64)
x = dijkstra(x)
for s, t in query:
    ans = x[s - 1, t - 1]
    if np.isinf(ans):
        print(-1)
    else:
        print(int(ans) - 1)

Solution (Python):

import random
import sys

sys.setrecursionlimit(100000)
input = sys.stdin.readline

INF = 2**62-1

def read_int():
    return int(input())


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


def warshall_floyd(g):
    N = len(g)
    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])
    return g


def slv(N, M, L, ABC, Q, ST):
    g = [[INF]*(N) for _ in range(N)]

    for a, b, c in ABC:
        if c > L:
            continue
        g[a-1][b-1] = c
        g[b-1][a-1] = c

    d = warshall_floyd(g)

    gg = [[INF]*(N) for _ in range(N)]
    for u in range(N):
        for v in range(N):
            if d[u][v] <= L:
                gg[u][v] = 1

    d = warshall_floyd(gg)

    for s, t in ST:
        c = d[s-1][t-1]
        if c != INF:
            print(c-1)
        else:
            print(-1)


def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]

    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Solution (Python):

import random
import sys

sys.setrecursionlimit(100000)
input = sys.stdin.readline

INF = 10**11

def read_int():
    return int(input())


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


def warshall_floyd(g):
    N = len(g)
    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])
    return g


def slv(N, M, L, ABC, Q, ST):
    g = [[INF]*(N) for _ in range(N)]

    for a, b, c in ABC:
        if c > L:
            continue
        g[a-1][b-1] = c
        g[b-1][a-1] = c

    d = warshall_floyd(g)

    gg = [[INF]*(N) for _ in range(N)]
    for u in range(N):
        for v in range(N):
            if d[u][v] <= L:
                gg[u][v] = 1

    d = warshall_floyd(gg)

    for s, t in ST:
        c = d[s-1][t-1]
        if c != INF:
            print(c-1)
        else:
            print(-1)


def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]

    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Solution (Python):

import random
import sys

sys.setrecursionlimit(100000)
input = sys.stdin.readline

INF = 10**11

def read_int():
    return int(input())


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


def warshall_floyd(g):
    d = g
    N = len(g)
    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 slv(N, M, L, ABC, Q, ST):
    g = [[INF]*(N) for _ in range(N)]

    for a, b, c in ABC:
        if c > L:
            continue
        g[a-1][b-1] = c
        g[b-1][a-1] = c

    d = warshall_floyd(g)

    gg = [[INF]*(N) for _ in range(N)]
    for u in range(N):
        for v in range(N):
            if d[u][v] <= L:
                gg[u][v] = 1

    d = warshall_floyd(gg)

    for s, t in ST:
        c = d[s-1][t-1]
        if c != INF:
            print(c-1)
        else:
            print(-1)


def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]

    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Solution (Python):

import random
import sys

sys.setrecursionlimit(100000)
input = sys.stdin.readline

INF = 10**11

def read_int():
    return int(input())


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


def warshall_floyd(g):
    d = g
    N = len(g)
    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 slv(N, M, L, ABC, Q, ST):
    g = [[INF]*(N) for _ in range(N)]
    for i in range(N):
        g[i][i] = 0
    for a, b, c in ABC:
        if c > L:
            continue
        g[a-1][b-1] = c
        g[b-1][a-1] = c

    d = g
    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])
    gg = [[INF]*(N) for _ in range(N)]
    for u in range(N):
        for v in range(N):
            if d[u][v] <= L:
                gg[u][v] = 1

    d = gg
    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:
        c = d[s-1][t-1]
        if c != INF:
            print(c-1)
        else:
            print(-1)


def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]

    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Solution (Python):
def slv():
    import sys
    input = sys.stdin.readline
    N, M, L = list(map(int, input().rstrip('\n').split()))
    INF = 10**11
    g = [[INF]*(N) for _ in range(N)]
    gg = [[INF]*(N) for _ in range(N)]

    for i in range(N):
        g[i][i] = 0
    for _ in range(M):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= L:
            g[a-1][b-1] = c
            g[b-1][a-1] = c
    
    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])
    
    for u in range(N):
        for v in range(N):
            if g[u][v] <= L:
                gg[u][v] = 1
    
    for k in range(N):
        for i in range(N):
            for j in range(N):
                gg[i][j] = min(gg[i][j], gg[i][k] + gg[k][j])

    Q = int(input())
    for _ in range(Q):
        s, t = list(map(int, input().rstrip('\n').split()))
        c = gg[s-1][t-1]
        if c != INF:
            print(c-1)
        else:
            print(-1)



def main():
    slv()

if __name__ == '__main__':
    main()