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: Time Limit Exceeded

Solution code:
def warshall_floyd(dist):
    #d[i][j]: iからjへの最短距離
    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])
    return dist

n, m, l = map(int, input().split()) #N:頂点数　M:辺の数 L:容量
dist = [[float("inf") for i in range(n)] for j in range(n)]

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

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

warshall_floyd(dist)
dist2 = [[float("inf") for i in range(n)] for j in range(n)]

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

warshall_floyd(dist2)
q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    ans = dist2[s-1][t-1]-1
    if dist2[s-1][t-1] == float("inf"):
        ans = -1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(dist):
    #d[i][j]: iからjへの最短距離
    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])
    return dist

n, m, l = map(int, input().split()) #N:頂点数　M:辺の数 L:容量
dist = [[float("inf") for i in range(n)] for j in range(n)]
dist2 = [[float("inf") for i in range(n)] for j in range(n)]

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

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

warshall_floyd(dist)

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

warshall_floyd(dist2)

q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    ans = dist2[s-1][t-1]-1
    if dist2[s-1][t-1] == float("inf"):
        ans = -1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


class UnionFind:
    def __init__(self, n):
        self.table = [-1] * n

    def _root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self._root(self.table[x])
            return self.table[x]

    def find(self, x, y):
        return self._root(x) == self._root(y)

    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.table[r1] += d2
        else:
            self.table[r1] = r2
            self.table[r2] += d1

    def united_count(self, x):
        return -self.table[self._root(x)]


def dijkstra(s, links, f9, f30):
    q = [s]
    ret = [-1] * n
    visited = set()
    limit = uft.united_count(s)
    while q:
        item = heappop(q)

        v = item & f9
        if v in visited:
            continue
        visited.add(v)

        count = item >> 39
        used = (item >> 9) & f30
        ret[v] = count

        if len(visited) >= limit:
            break

        for u, c in links[v]:
            if u in visited:
                continue
            if l - used < c:
                new_item = ((count + 1) << 39) + (c << 9) + u
            else:
                new_item = (count << 39) + ((used + c) << 9) + u
            heappush(q, new_item)

    return ret


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

links = [set() for _ in range(n)]
uft = UnionFind(n)

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if l < c:
        continue
    links[a].add((b, c))
    links[b].add((a, c))
    uft.union(a, b)

f9 = (1 << 9) - 1
f30 = (1 << 30) - 1

ans = [dijkstra(v, links, f9, f30) for v in range(n)]
buf = []

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def dijkstra(s, links, f9, f30):
    q = [s]
    ret = [-1] * n
    visited = set()
    while q:
        item = heappop(q)

        v = item & f9
        if v in visited:
            continue
        visited.add(v)

        count = item >> 39
        used = (item >> 9) & f30
        ret[v] = count

        for u, c in links[v]:
            if u in visited:
                continue
            if l - used < c:
                new_item = ((count + 1) << 39) + (c << 9) + u
            else:
                new_item = (count << 39) + ((used + c) << 9) + u
            heappush(q, new_item)

    return ret


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

links = [set() for _ in range(n)]

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

f9 = (1 << 9) - 1
f30 = (1 << 30) - 1

ans = [dijkstra(v, links, f9, f30) for v in range(n)]
buf = []

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

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

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int,input().split())
INF = (500, 10**9)
dist = [[INF if i != j else (0,0) for i in range(N)] for j in range(N)]
edge = [[] for i in range(N)]
for i in range(M):
	A,B,C = map(int,input().split())
	if C <= L:
		edge[A-1].append((B-1, C))
		edge[B-1].append((A-1, C))

import heapq as hq
for i in range(N):
	searched = [False for j in range(N)]
	n = i
	while n != None:
		searched[n] = True
		for e in edge[n]:
			if searched[e[0]]:
				continue
			d = dist[i][n]
			n2, d2 = e[0], e[1]
			if d[1] + d2 > L:
				new_d = (d[0] + 1, d2)
			else:
				new_d = (d[0], d[1] + d2)
			dist[i][n2] = min(dist[i][n2], new_d)
		n = None
		m = INF
		for j in range(N):
			if not searched[j] and dist[i][j] < m:
				n = j
				m = dist[i][j]


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

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def main():
    n, m, l = map(int, input().split())
    inf = 1001001001
    dist = [[inf] * n for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        a, b = a - 1, b - 1
        dist[a][b] = dist[b][a] = c
    for w in range(n):
        dw = dist[w]
        for u in range(n):
            du = dist[u]
            duw = du[w]
            for v in range(n):
                tmp = duw + dw[v]
                if tmp < du[v]: du[v] = tmp
    dist2 = [[inf] * n for _ in range(n)]
    for u in range(n):
        du = dist[u]
        d2u = dist2[u]
        for v in range(n):
            if du[v] <= l: d2u[v] = 1
    for w in range(n):
        dw = dist2[w]
        for u in range(n):
            du = dist2[u]
            duw = du[w]
            for v in range(n):
                tmp = duw + dw[v]
                if tmp < du[v]: du[v] = tmp

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

main()

Submission status: Time Limit Exceeded

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

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

def warshall_floyd(V,E):
    for k in range(V):
        for i in range(V):
            for j in range(V):
                if E[i][j] == -1:
                    if (E[i][k] != -1) and (E[k][j] != -1):
                        E[i][j]=E[i][k]+E[k][j]
                elif E[i][k] == -1 or E[k][j] == -1:
                    pass
                else:
                    E[i][j]=min(E[i][j],E[i][k]+E[k][j])
    return E

E=warshall_floyd(N,E)
for i in range(N):
    E[i][i]=-1
E=[[1 if __<= L and __!= -1 else -1 for __ in _] for _ in E]
E=warshall_floyd(N,E)


for s,t in ST:
    if E[s-1][t-1]>0:
        print(E[s-1][t-1]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
inf=10**9+7
n,m,l=map(int,input().split())
D=[[inf]*(n+1) for _ in range(n+1)]
for _ in range(m):
    a,b,c=map(int,input().split())
    D[a][b]=c
    D[b][a]=c

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

DD=[[inf]*(n+1) for _ in range(n+1)]
for x in range(1,n+1):
    for y in range(1,n+1):
        if D[x][y]<=l:
            DD[x][y]=1

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

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

Submission status: Time Limit Exceeded

Solution code:
########ワーシャルフロイド法

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

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

d = [[float("inf") for i in range(n)] for i in range(n)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(w):
    x,y,z = map(int,input().split())
    x -= 1
    y -= 1
    d[x][y] = z
    d[y][x] = z
for i in range(n):
    d[i][i] = 0 #自身のところに行くコストは０
d = warshall_floyd(d)

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

for i in range(n):
    for j in range(n):
        if i == j:
            D[i][j] = 0
        elif d[i][j] <= L:
            D[i][j] = 1

D = warshall_floyd(D)

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

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import csr_matrix #pypyだとエラーになるので、pythonを使うこと
from scipy.sparse.csgraph import shortest_path

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

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

graph = csr_matrix((N, N))

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


dist = shortest_path(graph, method='FW', directed=False)
graph2 = csr_matrix((N, N))
for i in range(N):
	for j in range(N):
		if dist[i, j] <= L:
			graph2[i, j] = 1
graph2 = csr_matrix(graph2)
num = shortest_path(graph2, method="FW", directed=False)


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

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import csr_matrix #pypyだとエラーになるので、pythonを使うこと
from scipy.sparse.csgraph import shortest_path

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

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

graph = csr_matrix((N, N))

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


dist = shortest_path(graph, method='FW')
graph2 = csr_matrix((N, N))
for i in range(N):
	for j in range(N):
		if dist[i, j] <= L:
			graph2[i, j] = 1
graph2 = csr_matrix(graph2)
num = shortest_path(graph2, method="FW")


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

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import csr_matrix, lil_matrix#pypyだとエラーになるので、pythonを使うこと
from scipy.sparse.csgraph import shortest_path

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

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

graph = lil_matrix((N, N))

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

graph = csr_matrix(graph)

dist = shortest_path(graph, method='FW')
graph2 = lil_matrix((N, N))
for i in range(N):
	for j in range(N):
		if dist[i, j] <= L:
			graph2[i, j] = 1
graph2 = csr_matrix(graph2)
num = shortest_path(graph2, method="FW")


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

Submission status: Time Limit Exceeded

Solution code:
# ABC143E - Travel by Car
def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    V = len(dist)
    for i in range(V):  # intermediate point
        for j, c2 in enumerate(dist[j][i] for j in range(V)):  #  source
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  # target
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3


def main():
    # FW -> once more FW to edges <= L
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    INF = 1 << 60
    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)

    # assume distance within L as 1 and compute the number of fueling
    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()

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq

cost=[]
def check(a,b):
    if a[0]<b[0]:
        return True
    elif a[0]==b[0]:
        return a[1]>b[1]
    else:
        return False


def djks(s,t,L,pathes,N):
    Q=[]
    global cost

    if cost[s]:
        return cost[s][t][0] if cost[s][t][0] != 2**29 else -1
    cost[s]=[[2**29,0] for i in range(N)]
    cost[s][s]=[0,L]
    vflg=[False for i in range(N)]
    hq.heappush(Q,(0,-L,s))
    while(Q):

        (times,remain,nom)=hq.heappop(Q)

        if vflg[nom]:
            continue
        vflg[nom]=True
        remain *= -1
        for target in pathes[nom]:
            if remain >= target[1]:
                sample=[times,remain-target[1]]
                if check(sample,cost[s][target[0]]):
                        cost[s][target[0]]=sample
                        hq.heappush(Q,[times,-remain+target[1],target[0]])
            elif L>=target[1]:
                sample=[times+1,L-target[1]]
                if check(sample,cost[s][target[0]]):
                    cost[s][target[0]]=sample
                    hq.heappush(Q,[times+1,-L+target[1],target[0]])
    return cost[s][t][0] if cost[s][t][0] != 2**29 else -1 

        









def resolve():
    (N,M,L)=map(int,input().split())
    global cost
    cost=[[] for i in range(N)]
    pathes=[[] for i in range(N)]
    for i in range(M):
        temp= list(map(int,input().split()))
        pathes[temp[0]-1].append([temp[1]-1,temp[2]])
        pathes[temp[1]-1].append([temp[0]-1,temp[2]])
    Q=int(input())
    for i in range(Q):
        s,t=(int(i)-1 for i in input().split())
        print(djks(s,t,L,pathes,N))





if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq



def check(a,b):
    if a[0]<b[0]:
        return True
    elif a[0]==b[0]:
        return a[1]>b[1]
    else:
        return False


def djks(s,t,L,pathes,N):
    Q=[]
    cost=[[N,0] for i in range(N)]
    cost[s]=[0,L]
    vflg=[False for i in range(N)]
    hq.heappush(Q,(0,-L,s))
    while(Q):

        (times,remain,nom)=hq.heappop(Q)

        if vflg[nom]:
            continue
        vflg[nom]=True
        remain *= -1
        for target in pathes[nom]:
            if remain >= target[1]:
                sample=[times,remain-target[1]]
                if check(sample,cost[target[0]]) and check(sample,cost[t]):
                        cost[target[0]]=sample
                        hq.heappush(Q,[times,-remain+target[1],target[0]])
            elif L>=target[1]:
                sample=[times+1,L-target[1]]
                if check(sample,cost[target[0]]) and check(sample,cost[t]):
                    cost[target[0]]=sample
                    hq.heappush(Q,[times+1,-L+target[1],target[0]])
    return cost[t][0] if cost[t][0] != N else -1 

        









def resolve():
    (N,M,L)=map(int,input().split())
    pathes=[[] for i in range(N)]
    for i in range(M):
        temp= list(map(int,input().split()))
        pathes[temp[0]-1].append([temp[1]-1,temp[2]])
        pathes[temp[1]-1].append([temp[0]-1,temp[2]])
    Q=int(input())
    for i in range(Q):
        s,t=(int(i)-1 for i in input().split())
        print(djks(s,t,L,pathes,N))





if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq



def check(a,b):
    if a[0]<b[0]:
        return True
    elif a[0]==b[0]:
        return a[1]>b[1]
    else:
        return False


def djks(s,t,L,pathes,N):
    Q=[]
    cost=[[2**29,0] for i in range(N)]
    cost[s]=[0,L]
    vflg=[False for i in range(N)]
    hq.heappush(Q,(0,-L,s))
    while(Q):

        (times,remain,nom)=hq.heappop(Q)

        if vflg[nom]:
            continue
        vflg[nom]=True
        remain *= -1
        for target in pathes[nom]:
            if remain >= target[1]:
                sample=[times,remain-target[1]]
                if check(sample,cost[target[0]]) and check(sample,cost[t]):
                        cost[target[0]]=sample
                        hq.heappush(Q,[times,-remain+target[1],target[0]])
            elif L>=target[1]:
                sample=[times+1,L-target[1]]
                if check(sample,cost[target[0]]) and check(sample,cost[t]):
                    cost[target[0]]=sample
                    hq.heappush(Q,[times+1,-L+target[1],target[0]])
    return cost[t][0] if cost[t][0] != 2**29 else -1 

        









def resolve():
    (N,M,L)=map(int,input().split())
    pathes=[[] for i in range(N)]
    for i in range(M):
        temp= list(map(int,input().split()))
        pathes[temp[0]-1].append([temp[1]-1,temp[2]])
        pathes[temp[1]-1].append([temp[0]-1,temp[2]])
    Q=int(input())
    for i in range(Q):
        s,t=(int(i)-1 for i in input().split())
        print(djks(s,t,L,pathes,N))





if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
D = [[1000000000000]*N for i 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, B = 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):
      D[i][j] = min(D[i][j], D[i][k]+D[k][j])
E = [[1000000000000]*N for i in range(N)]
for i in range(N):
  E[i][i] = 0
for i in range(N):
  for j in range(N):
    if D[i][j] <= L:
      E[i][j] = 1
for k in range(N):
  for i in range(N):
    for j in range(N):
      E[i][j] = min(E[i][j], E[i][k]+E[k][j])
Q = int(input())
for i in range(Q):
  s, t = map(int, input().split())
  s, t = s-1, t-1
  if E[s][t] == 1000000000000:
    r = -1
  else:
    r = E[s][t]-1
  print(r)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense
from scipy.sparse.csgraph import floyd_warshall
import heapq

n, m, full = map(int, input().split())
edges = [[]*n for _ in range(n)]

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


def dijkstra(num_of_node, edge, start, limit):
    distance = [float('INF')] * num_of_node
    distance[start] = 0
    todo = []
    heapq.heapify(todo)
    heapq.heappush(todo, [0, start])

    while todo:
        d, node = heapq.heappop(todo)
        if d > limit:
            break
        L_edges[start][node] = 1
        for new_node, cost in edge[node]:
            if distance[new_node] > d + cost:
                distance[new_node] = d + cost
                heapq.heappush(todo, [d+cost, new_node])

            else:
                continue
    return


L_edges = [[float('INF')]*n for _ in range(n)]

for i in range(n):
    dijkstra(n, edges, i, full)

for i in range(n):
    L_edges[i][i] = float('INF')
G = csgraph_from_dense(L_edges, null_value=float('INF'))
answers = floyd_warshall(G)

Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    ans = answers[s-1][t-1] - 1
    if ans == float('INF'):
        ans = -1
    print(int(ans))

Submission status: Time Limit Exceeded

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

G = [[float('inf')] * (N+1) for _ in range(N+1)]

for _ in range(M):
    a, b, c = map(int, input().split())
    G[a][b] = c
    G[b][a] = c


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

GL = [[float('inf')] * (N+1) for _ in range(N+1)]
for i in range(1, N):
    for j in range(i+1, N+1):
        if G[i][j] <= L:
            GL[i][j] = 1
            GL[j][i] = 1

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

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

Submission status: Time Limit Exceeded

Solution code:
INFTY = 10**12
def wf(H):
    d = [[INFTY for _ in range(N+1)] for _ in range(N+1)]
    for i in range(1,N+1):
        d[i][i] = 0
        if i in H:
            for x in H[i]:
                j,c = x[0],x[1]
                d[i][j] = c
    for k in range(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d
N,M,L = map(int,input().split())
G = {}
for _ in range(M):
    A,B,C = map(int,input().split())
    if A not in G:
        G[A] = []
    G[A].append((B,C))
    if B not in G:
        G[B] = []
    G[B].append((A,C))
d1 = wf(G)
F = {}
for i in range(1,N):
    for j in range(i+1,N+1):
        if d1[i][j]<=L:
            if i not in F:
                F[i] = []
            F[i].append((j,1))
            if j not in F:
                F[j] = []
            F[j].append((i,1))
d2 = wf(F)
Q = int(input())
for _ in range(Q):
    s,t = map(int,input().split())
    if d2[s][t]<INFTY:
        print(d2[s][t]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

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

edge_lst = []
for i in range(m):
    a,b,c = map(int ,input().split())
    if c <= l:
        edge_lst.append((a,b,c))
        edge_lst.append((b,a,c))
        
d_matrix = [[(-1, 10**10)] * (n+1) for _ in range(n+1)]
for i in range(n):
    d = [(-1, 10**10)] * (n+1)
    d[i+1] = (l, 0)
    while True:
        update = False
        for abc in edge_lst:
            a, b, c = abc
            if d[a][1] != 10**10:
                if d[a][0] < c:
                    cnt = d[a][1] + 1
                    f = l - c
                else:
                    cnt = d[a][1]
                    f = d[a][0] - c
                if d[b][1] == cnt:
                    if d[b][0] < f:
                        d[b] = (f, cnt)
                        update = True
                if d[b][1] > cnt:
                    d[b] = (f, cnt)
                    update = True
        if not update:
            break
        d_matrix[i+1] = d

q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    print(d_matrix[s][t][1]) if d_matrix[s][t][1] != 10**10 else print(-1)

Submission status: Time Limit Exceeded

Solution code:
n, m, l = map(int, input().split())
abc_lst = [list(map(int, input().split())) for _ in range(m)]
q = int(input())
q_lst = [list(map(int, input().split())) for _ in range(q)]

edge_lst = []
for abc in abc_lst:
    a,b,c = abc
    if c <= l:
        edge_lst.append((a,b,c))
        edge_lst.append((b,a,c))
        
d_matrix = [[(-1, 10**10)] * (n+1) for _ in range(n+1)]
for i in range(n):
    d = [(-1, 10**10)] * (n+1)
    d[i+1] = (l, 0)
    while True:
        update = False
        for abc in edge_lst:
            a, b, c = abc
            if d[a][1] != 10**10:
                if d[a][0] < c:
                    cnt = d[a][1] + 1
                    f = l - c
                else:
                    cnt = d[a][1]
                    f = d[a][0] - c
                if d[b][1] == cnt:
                    if d[b][0] < f:
                        d[b] = (f, cnt)
                        update = True
                if d[b][1] > cnt:
                    d[b] = (f, cnt)
                    update = True
        if not update:
            break
        d_matrix[i+1] = d

for q in q_lst:
    s, t = q
    print(d_matrix[s][t][1]) if d_matrix[s][t][1] != 10**10 else print(-1)

Submission status: Time Limit Exceeded

Solution code:
n, m, l = map(int, input().split())
abc_lst = [list(map(int, input().split())) for _ in range(m)]
q = int(input())
q_lst = [list(map(int, input().split())) for _ in range(q)]

edge_lst = []
for abc in abc_lst:
    a,b,c = abc
    if c <= l:
        edge_lst.append((a,b,c))
        edge_lst.append((b,a,c))
        
d_matrix = [[(-1, 10**10)] * (n+1) for _ in range(n+1)]
for i in range(n):
    d = [(-1, 10**10)] * (n+1)
    d[i+1] = (l, 0)
    while True:
        update = False
        for abc in edge_lst:
            a, b, c = abc
            if d[a][1] != 10**10:
                if d[a][0] < c:
                    cnt = d[a][1] + 1
                    f = l - c
                else:
                    cnt = d[a][1]
                    f = d[a][0] - c
                if d[b][1] == cnt:
                    if d[b][0] <= f:
                        d[b] = (f, cnt)
                        update = True
                if d[b][1] > cnt:
                    d[b] = (f, cnt)
                    update = True
        if not update:
            break
        d_matrix[i+1] = d

for q in q_lst:
    s, t = q
    print(d_matrix[s][t][1]) if d_matrix[s][t][1] != 10**10 else print(-1)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import*
f=csgraph.johnson
t=map(int,open('/dev/fd/0').read().split())
n,m,l=t[:3]
m=m*3+3
for i in f(f(csr_matrix((t[5:m:3],(t[3:m:3],t[4:m:3])),[n+1]*2),0)<=l)[t[m+1::2],t[m+2::2]]:print min(n,i)%n-1

Submission status: Time Limit Exceeded

Solution code:
def froyd(n, d):
    for k in range(n):
        for s in range(n):
            ds = d[s]
            for t in range(n):
                ds[t] = min(ds[t], ds[k] + d[k][t])


def main():
    N, M, L = [int(x) for x in input().split()]
    INF = float("inf")
    A = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    for i in range(N):
        A[i] = [INF] * N
        A[i][i] = 0
        B[i] = [INF] * N
        B[i][i] = 0
    for i in range(M):
        a, b, c = [int(x) for x in input().split()]
        A[a - 1][b - 1] = c
        A[b - 1][a - 1] = c
    froyd(N, A)
    # print(A)
    for s in range(N):
        for t in range(N):
            B[s][t] = 0 if s == t else 1 if A[s][t] <= L else INF
    # print(B)
    froyd(N, B)
    # print(B)

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


main()

Submission status: Time Limit Exceeded

Solution code:
def froyd(n, d):
    for k in range(n):
        for s in range(n):
            # ds = d[s]
            for t in range(n):
                d[s][t] = min(d[s][t], d[s][k] + d[k][t])


def main():
    N, M, L = [int(x) for x in input().split()]
    INF = float("inf")
    A = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    for i in range(N):
        A[i] = [INF] * N
        A[i][i] = 0
        B[i] = [INF] * N
        B[i][i] = 0
    for i in range(M):
        a, b, c = [int(x) for x in input().split()]
        A[a - 1][b - 1] = c
        A[b - 1][a - 1] = c
    froyd(N, A)
    # print(A)
    for s in range(N):
        for t in range(N):
            B[s][t] = 0 if s == t else 1 if A[s][t] <= L else INF
    # print(B)
    froyd(N, B)
    # print(B)

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


main()