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):
from scipy.sparse.csgraph import floyd_warshall
N,M,L=map(int,input().split())
inf=10**9+1

distance=[[inf for n in range(N)] for n in range(N)]
for n in range(N):
    distance[n][n]=0
for m in range(M):
    a,b,c=map(int,input().split())
    distance[a-1][b-1]=c
    distance[b-1][a-1]=c
distance=floyd_warshall(distance)

distance2=[[inf for n in range(N)] for n in range(N)]
for i in range(N):
    for j in range(N):
        if distance[i][j]<=L:
            distance2[i][j]=1
for n in range(N):
    distance2[n][n]=0
distance2=floyd_warshall(distance2)

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

Solution (Python):
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

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

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Solution (Python):
import sys


def main():
	input = sys.stdin.readline
	N, M, L = list(map(int,input().split()))
	P = [list(map(int,input().split())) for i in range(M)]
	Q = int(input())
	st = [list(map(int,input().split())) for i in range(Q)]

	neighbor = [[] for i in range(N)]
	for s,e,d in P:
		if d<=L:
			neighbor[s-1].append((e-1,d))
			neighbor[e-1].append((s-1,d))
		
		

	
	

	fuellist = [0]*N
	def bfs(start, end):
		
		fuelc, fuelm = [10000000]*N, [L+1]*N
		
		
		fuelc[start], fuelm[start] = 0, L
		queue = [start]
		while len(queue)>0:
			nq = []						
			nq_append = nq.append
			for i in queue:				
				oc, om = fuelc[i], fuelm[i]
				for j, d in neighbor[i]:
				
					
					if om<d:
						nc = oc+1
						nm = L-d
					else:
						nc = oc
						nm = om-d

					

					if nc<fuelc[j]:
						fuelc[j], fuelm[j] = nc, nm
						nq_append(j)
					elif nc==fuelc[j] and nm>fuelm[j]:
						fuelm[j] = nm
						nq_append(j)

			queue = nq					

		
		ans = fuelc[end]
		if ans==10000000: ans = -1

		fuellist[start] = fuelc

		print(ans)

	for s, t in st:
		start, end = s-1, t-1

		if fuellist[start]!=0:
			ans = fuellist[start][end]
			if ans==10000000: ans = -1
			print(ans)
		elif fuellist[end]!=0:
			ans = fuellist[end][start]
			if ans==10000000: ans = -1
			print(ans)
		else:
			bfs(start,end)


if __name__ == '__main__':
	main()

Solution (Python):
def warshall_floyd(G):
    '''
    G: N * N Array (Adjacency matrix)
    ret: N * N Array (Minimum path)
    '''
    import copy
    ret = copy.deepcopy(G)
    for k in range(N):
        for i in range(N):
            for j in range(N):
                ret[i][j] = min(ret[i][j], ret[i][k] + ret[k][j])
    return ret


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

G = [[INF] * N for _ in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    G[A - 1][B - 1], G[B - 1][A - 1] = C, C

MinG = warshall_floyd(G)
GL = [[1 if MinG[i][j] <= L else INF for j in range(N)] for i in range(N)]
MinGL = warshall_floyd(GL)

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

Solution (Python):
def e_travel_by_car(INF=float('inf')):
    from copy import deepcopy
    from scipy.sparse.csgraph import floyd_warshall
    N, M, L = [int(i) for i in input().split()]
    Roads = [[int(i) for i in input().split()] for j in range(M)]
    Q = int(input())
    Queries = [[int(i) for i in input().split()] for j in range(Q)]

    graph = [[INF] * N for _ in range(N)]
    for k in range(N):
        graph[k][k] = 0
    fuel = deepcopy(graph)

    for a, b, c in Roads:
        graph[a - 1][b - 1] = graph[b - 1][a - 1] = c
    dist = floyd_warshall(graph)

    for i in range(N):
        for j in range(i):
            fuel[i][j] = fuel[j][i] = int(dist[i][j] <= L)
    fuel = floyd_warshall(fuel)

    ans = [-1 if fuel[s - 1][t - 1] == INF else int(fuel[s - 1][t - 1]) - 1 for s, t in Queries]
    return '\n'.join(map(str, ans))

print(e_travel_by_car())

Solution (Python):
def e_travel_by_car(INF=float('inf')):
    from copy import deepcopy
    from scipy.sparse.csgraph import floyd_warshall
    N, M, L = [int(i) for i in input().split()]
    Roads = [[int(i) for i in input().split()] for j in range(M)]
    Q = int(input())
    Queries = [[int(i) for i in input().split()] for j in range(Q)]

    graph = [[INF] * N for _ in range(N)]
    for k in range(N):
        graph[k][k] = 0
    fuel = deepcopy(graph)

    for a, b, c in Roads:
        graph[a - 1][b - 1] = graph[b - 1][a - 1] = c
    dist = floyd_warshall(graph)

    for i in range(N):
        for j in range(N):
            fuel[i][j] = int(dist[i][j] <= L)
    fuel = floyd_warshall(fuel)

    ans = [-1 if fuel[s - 1][t - 1] == INF else int(fuel[s - 1][t - 1]) - 1 for s, t in Queries]
    return '\n'.join(map(str, ans))

print(e_travel_by_car())

Solution (Python):
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

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

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Solution (Python):
def WarshallFloyd(M):
    N = len(M)
    for k in range(N):
        for j in range(N):
            for i in range(N):
                M[i][j] = min(M[i][j], M[i][k] + M[k][j])
    return M

INF = float("inf")

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[INF] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c


E = WarshallFloyd(E)

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

E = WarshallFloyd(E)

for s, t in zip(*[iter(ST)] * 2):
    a = E[s - 1][t - 1] - 1
    print(-1 if a == INF else a)

Solution (Python):
N, M, L = map(int,input().split(' '))
Ms=[]
inf = 10**11
for i in range(N+1):
    
    Ms.append([inf]*(N+1) )


for i in range(M):
    a,b,c = map(int,input().split(' '))
    
    Ms[a][b] = c
    Ms[b][a] = c
    
Q = int(input())

def warshall_floyd(Ms):
    for k in range(1,len(Ms)):
        for i in range(1,len(Ms)):
            for j in range(1,len(Ms)):
                Ms[i][j]=min(Ms[i][j],Ms[i][k]+Ms[k][j])
    return Ms

Ms = warshall_floyd(Ms)



Ls = Ms
for i in range(N+1):
    for j in range(N+1):
        if Ls[i][j] <= L:
            Ls[i][j] = 1
        else:
            Ls[i][j]=inf

Ls = warshall_floyd(Ls)

for i in range(Q):
    s,t = map(int,input().split(' '))
    if Ls[s][t] == inf:
        print(-1)
    else:
        print(Ls[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):
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)
d[d>I]=I
for i in zip(*[iter(t[m*3+1:])]*2):print(int(d[i]%I-1))

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

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c

E = floyd_warshall(E)
E = [[(eij <= L) for j, eij in enumerate(ei)] for i, ei in enumerate(E)]
E = floyd_warshall(E)

INF = float("inf")

print("\n".join("-1" if E[s - 1][t - 1] == INF else str(int(E[s - 1][t - 1] - 1)) for s, t in zip(*[iter(ST)] * 2)))

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

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c

E = floyd_warshall(E)
E = [[(eij <= L) for j, eij in enumerate(ei)] for i, ei in enumerate(E)]
E = floyd_warshall(E)

INF = float("inf")

A = []
for s, t in zip(*[iter(ST)] * 2):
    a = E[s - 1][t - 1] - 1
    A.append("-1" if a == INF else str(int(a)))

print("\n".join(A))

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

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c

E = floyd_warshall(E)

for i, ei in enumerate(E):
    for j, eij in enumerate(ei):
        E[i][j] = (eij <= L)

E = floyd_warshall(E)

INF = float("inf")

A = []
for s, t in zip(*[iter(ST)] * 2):
    a = E[s - 1][t - 1] - 1
    A.append("-1" if a == INF else str(int(a)))

print("\n".join(A))

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

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c

E = floyd_warshall(E)

for i in range(N):
    for j in range(N):
        E[i][j] = (E[i][j] <= L)

E = floyd_warshall(E)

INF = float("inf")

A = []
for s, t in zip(*[iter(ST)] * 2):
    a = E[s - 1][t - 1] - 1
    A.append("-1" if a == INF else str(int(a)))

print("\n".join(A))

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

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

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

N, M, L, *I = map(int, open(0).read().split())
ABC, ST = I[:3 * M], I[3 * M + 1:]

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    E[a - 1][b - 1] = E[b - 1][a - 1] = c

E = floyd_warshall(E)

for i in range(N):
    for j in range(N):
        E[i][j] = (E[i][j] <= L)

E = floyd_warshall(E)

INF = float("inf")

for s, t in zip(*[iter(ST)] * 2):
    a = E[s - 1][t - 1] - 1
    print(-1 if a == INF else int(a))

Solution (Python):
N, M, L = map(int, input().split())
INF = 1001001001

class Graph():
    def __init__(self, N):
        self.graph = [[INF for _ in range(N)] for _ in range(N)]
        for i in range(N):
            self.graph[i][i] = 0

    def add_path(self, a, b, c):
        self.graph[a][b] = c
        self.graph[b][a] = c

    def get(self, a, b):
        return self.graph[a][b]

    def warshall_floyd(self):
        N = len(self.graph)
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    self.graph[i][j] = min(self.graph[i][j], self.graph[i][k]+self.graph[k][j])

path = Graph(N)
for _ in range(M):
    A, B, C = map(int, input().split())
    path.add_path(A-1, B-1, C)
path.warshall_floyd()
aid = Graph(N)
for i in range(N):
    for j in range(i+1, N):
        if path.get(i, j) <= L:
            aid.add_path(i, j, 1)
aid.warshall_floyd()
Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    ans = aid.get(s-1, t-1)
    if ans == INF:
        print(-1)
    else:
        print(ans-1)

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

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

E = floyd_warshall(E)

for i in range(N):
    for j in range(N):
        E[i][j] = (E[i][j] <= L)

E = floyd_warshall(E)

INF = float("inf")

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

Solution (Python):




class Node(object):

  def __init__(self):
    self.fixed = False
    self.supply = 300
    self.tank = 0
    self.edges = []

  def __repr__(self):
    return str(self)

  def __str__(self):
    return '{}/{}({})'.format(self.supply, self.tank, int(self.fixed))


def main():
  n, m, tank = map(int, input().split())
  nodes = [Node() for _ in range(n)]

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

    nodes[a - 1].edges.append((nodes[b - 1], c))
    nodes[b - 1].edges.append((nodes[a - 1], c))

  queries = [list(map(int, input().split())) for _ in range(int(input()))]
  results = [[None] * len(nodes) for _ in range(len(nodes))]

  for start in range(len(nodes)):
    for node in nodes:
      node.fixed = False
      node.supply = 300
      node.tank = 0

    nodes[start].supply = 0
    nodes[start].tank = tank

    while True:
      targets = [n for n in nodes if not n.fixed ]

      if len(targets) == 0:
        break

      target = min(targets, key=lambda n: (n.supply, -n.tank))
      target.fixed = True

      for n, d in target.edges:
        if n.fixed or d > tank:
          continue

        if d > target.tank:
          new_supply = target.supply + 1
          new_tank = tank - d
        else:
          new_supply = target.supply
          new_tank = target.tank - d

        if (new_supply, -new_tank) < (n.supply, -n.tank):
          n.supply = new_supply
          n.tank = new_tank

    for end in range(len(nodes)):
      results[start][end] = nodes[end].supply

  for start, end in queries:
    if results[start - 1][end - 1] == 300:
      print(-1)
    else:
      print(results[start - 1][end - 1])


if __name__ == '__main__':
  main()

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))

class SegmentTree:
    def __init__(self, value=[], N=0, comp=lambda x,y: x<=y, reverse=False):
        M = max(len(value),N)
        N = 2**(len(bin(M))-3)
        if N < M: N *= 2
        self.N = N
        self.node = [0] * (2*N-1)
        for i in range(N):
            self.node[N-1+i] = i
        self.value = [None] * N
        for i, v in enumerate(value):
            self.value[i] = v
        self.comp = lambda x, y: True if y is None else False if x is None else comp(x,y)^reverse
        for i in range(N-2,-1,-1):
            left_i, right_i = self.node[2*i+1], self.node[2*i+2]
            left_v, right_v = self.value[left_i], self.value[right_i]
            self.node[i] = left_i if self.comp(left_v, right_v) else right_i

    def update(self, n, v):
        self.value[n] = v
        i = (self.N-1) + n
        while i > 0:
            i = (i-1)//2
            left_i, right_i = self.node[2*i+1], self.node[2*i+2]
            left_v, right_v = self.value[left_i], self.value[right_i]
            new_i = left_i if self.comp(left_v, right_v) else right_i
            if new_i == self.node[i] and new_i != n:
                break
            else:
                self.node[i] = new_i

    def at(self, n):
        if n is None:
            return None
        else:
            return self.value[n]

    def query(self, l=0, r=-1):
        return self.at(self.query_index(l,r))

    def query_index(self, l=0, r=-1):
        if r < 0: r = self.N
        L = l + self.N; R = r + self.N
        s = None
        while L < R:
            if R & 1:
                R -= 1
                if self.comp(self.at(self.node[R-1]), self.at(s)):
                    s = self.node[R-1]
            if L & 1:
                if self.comp(self.at(self.node[L-1]), self.at(s)):
                    s = self.node[L-1]
                L += 1
            L >>= 1; R >>= 1
        return s

N, M, L = inpl()
road = [[] for _ in range(N)]
for i in range(M):
    A, B, C = inpl()
    if C <= L:
        road[A-1].append((B-1,C))
        road[B-1].append((A-1,C))
minimum = [ [-1]*N for _ in range(N)]
for i in range(N):
    minimum[i][i] = 0

INF = 10**4
Q = int(input())
ST = [inpl() for _ in range(Q)]
starts = set([ s-1 for s,t in ST])
segtree = SegmentTree(N=N)
for start in starts:
    for i in range(N):
        segtree.update(i, (INF,0))
    segtree.update(start, (0,0))
    while True:
        p = segtree.query_index()
        pnred = segtree.at(p)
        if pnred is None:
            break
        else:
            pn, pred = pnred
            if pn >= INF:
                break
        minimum[start][p] = pn
        segtree.update(p, None)

        for q, c in road[p]:
            if segtree.at(q) is None:
                continue
            else:
                qn, qred = segtree.at(q)
            if pred + c > L:
                qn2, qred2 = pn + 1, c
            else:
                qn2, qred2 = pn, pred + c
            if qn < 0 or (qn2,qred2) < (qn,qred):
                segtree.update(q, (qn2, qred2))

for s,t in ST:
    print(minimum[s-1][t-1])

Solution (Python):
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

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

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Solution (Python):
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

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

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

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

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

Solution (Python):
import sys
input=sys.stdin.readline
n,m,l=map(int,input().split())
INF=10**10
graph=[[INF for i in range(n)] for j in range(n)]
fuel=[[INF for i in range(n)] for j in range(n)]
for i in range(n):
    graph[i][i]=0
for i in range(m):
    a,b,c=map(int,input().split())
    a-=1;b-=1
    if c>l:continue
    graph[a][b],graph[b][a]=c,c
for i in range(n):
  for j in range(n):
    for k in range(n):
      graph[j][k]=min(graph[j][k],graph[j][i]+graph[i][k])
for i in range(n):
    for j in range(n):
        if graph[i][j]<=l:
            fuel[i][j]=1
for i in range(n):
  for j in range(n):
    for k in range(n):
      fuel[j][k]=min(fuel[j][k],fuel[j][i]+fuel[i][k])
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    s-=1;t-=1
    if fuel[s][t]==INF:print(-1)
    else:print(fuel[s][t]-1)

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

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

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

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