Problem:


Score : 500 points

Problem Statement

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

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

Process the following Q queries:

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

Constraints

All values in input are integers.

2 \leq N \leq 300

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

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

1 \leq C_i \leq 10^9

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

1 \leq s_i, t_i \leq N

s_i \neq t_i

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

Input

Input is given from Standard Input in the following format:

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

Output

Print Q lines.

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

Sample Input 1

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

Sample Output 1

0
1

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

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

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

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



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


Sample output:
0
1

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense,dijkstra,floyd_warshall
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = int(0)
N,M,L =LI()
s = []
t = []
dp = [[inf] * (N) for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
Q = I()
for i in range(Q):
    a,b = LI()
    s.append(a-1)
    t.append(b-1)

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

#print(warshall_floyd(N,dp))
#d1 = [[0] * (N) for _ in range(N)]
#d1 = warshall_floyd(N,dp)
G = csgraph_from_dense(dp)
d1 = floyd_warshall(G)

newdp = [[inf] * (N) for _ in range(N)]
for i in range(N):
    for j in range(i+1,N):
        if d1[i][j]<=L:
            newdp[i][j] = 1
            newdp[j][i] = 1

for i in range(N):
    newdp[i][i] = 0
#print(newdp)
#print(warshall_floyd(N,newdp))
#d2 = [[0] * (N) for _ in range(N)]
#d2 = warshall_floyd(N,newdp)
G2 = csgraph_from_dense(newdp)
d2 = floyd_warshall(G2)

for i in range(Q):
    ans = d2[s[i]][t[i]]-1
    if ans!= inf:
        print(int(ans))
    else:
        print("-1")

Submission status: Accepted

Solution code:
n,m,l=map(int,input().split())
inf=10000000000
g=[[inf for i in range(n)] for j in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    g[a-1][b-1]=c
    g[b-1][a-1]=c
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])
r=[[inf for i in range(n)] for j in range(n)]
for i in range(n):
    for j in range(n):
        if g[i][j]<=l:
            r[i][j]=1
        elif g[i][j]>=inf:
            r[i][j]=inf
for k in range(n):
    for i in range(n):
        for j in range(n):
            r[i][j]=min(r[i][j],r[i][k]+r[k][j])
q=int(input())
for i in range(q):
    s,e=map(int,input().split())
    if r[s-1][e-1]>=inf:
        print(-1)
    else:
        print(r[s-1][e-1]-1)

Submission status: Accepted

Solution code:
#################################
##ワーシャルフロイド法 n~3
#################################
def warshall_floyd(n,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
##############################
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = int(0)
N,M,L =LI()
s = []
t = []
dp = [[inf] * (N) for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
Q = I()
for i in range(Q):
    a,b = LI()
    s.append(a-1)
    t.append(b-1)

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

#print(warshall_floyd(N,dp))
d1 = [[0] * (N) for _ in range(N)]
d1 = warshall_floyd(N,dp)

newdp = [[inf] * (N) for _ in range(N)]
for i in range(N):
    for j in range(i+1,N):
        if d1[i][j]<=L:
            newdp[i][j] = 1
            newdp[j][i] = 1

for i in range(N):
    newdp[i][i] = 0
#print(newdp)
#print(warshall_floyd(N,newdp))
d2 = [[0] * (N) for _ in range(N)]
d2 = warshall_floyd(N,newdp)

for i in range(Q):
    ans = d2[s[i]][t[i]]-1
    if ans!= inf:
        print(ans)
    else:
        print("-1")

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall, dijkstra
input = lambda: sys.stdin.readline()[:-1]
sys.setrecursionlimit(10**8)

# f = floyd_warshall(G,directed=True(有向か、defaultはTrue))
# d = dijkstra(G, indices=0,directed=True(有向か、defaultはTrue))
n,m,l=map(int,input().split())
rinsetsu=[[0]*n for i in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    rinsetsu[a-1][b-1]=c
    rinsetsu[b-1][a-1]=c

# G = csgraph_from_dense(rinsetsu, null_value=0)
f = floyd_warshall(rinsetsu,directed=True)
# print(f)
for i in range(n):
    for j in range(n):
        f[i][j]= 1 if 1<=f[i][j]<=l else 0
# print(f)
f2= floyd_warshall(f,directed=True)

q = int(input())
for i in range(q):
    s,g=map(int,input().split())
    s-=1;g-=1
    print(int(f2[s][g])-1 if f2[s][g]!=float("inf") else -1)

# print(f2)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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
d=floyd_warshall(g)
g2=[[float('inf')]*(n+1) for _ in range(n+1)]
for i in range(1,n+1):
  for j in range(1,n+1):
    if d[i][j]<=l:
      g2[i][j]=1
d2=floyd_warshall(g2)
q=int(input())
for _ in range(q):
  a,b=map(int,input().split())
  tmp=d2[a][b]
  if tmp==float('inf'):
    print(-1)
  else:
    print(int(tmp-1))

Submission status: Accepted

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

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

    return d

def main():
    N, M, L = map(int, input().split())
    d = [[float('inf')] * N for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        d[A][B] = C
        d[B][A] = C

    e = warshal_floyd(d,N)
    f = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if e[i][j] <= L:
                f[i][j] = 1

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



if __name__ == "__main__":
    main()

Submission status: Accepted

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

n, m, l = map(int, input().split())
mw =[[float('inf')] * n for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    mw[a-1][b-1] = c
    mw[b-1][a-1] = c

def warshall_floyd(d): # 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 = warshall_floyd(mw)
mw =[[float('inf')] * n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            mw[i][j] = 1
dd = warshall_floyd(mw)

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

Submission status: Accepted

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

def dijkstra(s,n,cost,l):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True
        dist_v = d[v]
        for j,weight in enumerate(cost[v]):
            alt = dist_v + weight
            r = (dist_v - 1) // l
            if (r != (alt - 1) // l) and dist_v != 0:
                alt = (r + 1) * l + weight         
            d[j] = min(d[j],alt)
    return d
 
n,m,l = map(int, input().split())
abc = [list(map(int, input().split())) for i in range(m)]
q = int(input())
st = [list(map(int, input().split())) for i in range(q)]
path = [[float("inf") for i in range(n)] for i in range(n)]
ans_list = []
for i in abc:
  a,b,cost = i[0]-1, i[1]-1, i[2]
  if cost <= l:
    path[a][b] = cost
    path[b][a] = cost
for s in range(n):
  ans_list.append(dijkstra(s,n,path,l))
for i in st:
  s, t = i[0] - 1, i[1] - 1
  ans = ans_list[s][t]
  if ans == float("inf"):
    ans = -1
  else:
    ans = (ans - 1) // l
  print(ans)

Submission status: Accepted

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

def dijkstra(s,n,cost,l):
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True
        dist_v = d[v]
        for j, weight in enumerate(cost[v]):
            alt = dist_v + weight
            r = (dist_v - 1) // l
            if r != ((alt - 1) // l) and dist_v != 0:
                alt = (r + 1) * l + weight         
            d[j] = min(d[j],alt)
    return d

n,m,l = map(int, input().split())
path = [[float("inf") for i in range(n)] for i in range(n)]
ans_list = []
for i in range(m):
  a,b,cost = map(int, input().split())
  a -= 1
  b -= 1
  if cost <= l:
    path[a][b] = cost
    path[b][a] = cost
for s in range(n):
  ans_list.append(dijkstra(s,n,path,l))
q = int(input())

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

Submission status: Accepted

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

Submission status: Accepted

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

INF = 10 ** 9 + 6
graph = [[INF] * N for _ in range(N)]

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

for u, v, l in edges:
    graph[u - 1][v - 1] = l
    graph[v - 1][u - 1] = l

for k in range(N):
    for i in range(N):
        if graph[i][k] == INF:
            continue
        for j in range(N):
            if graph[k][j] == INF:
                continue
            graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])

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

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

for i in range(N):
    for j in range(N):
        if i == j:
            continue
        if graph[i][j] <= L:
            cnt[i][j] = 1
            cnt[j][i] = 1

for k in range(N):
    for i in range(N):
        if cnt[i][k] == INF:
            continue
        for j in range(N):
            if cnt[k][j] == INF:
                continue
            cnt[i][j] = min(cnt[i][j], cnt[i][k] + cnt[k][j])

for s, t in X:
    if cnt[s - 1][t - 1] == INF:
        print(-1)
    else:
        print(cnt[s - 1][t - 1] - 1)

Submission status: Accepted

Solution code:
N,M,L = map(int, input().split())
Edges = [map(int, input().split()) for i in range(M)]
Q = int(input())
Queries = [map(int, input().split()) for i in range(Q)]

INF = 10**18
# 初期化
d = [[INF]*N for i in range(N)]
for i in range(N):
    d[i][i] = 0
for a,b,c in Edges:
    a -= 1
    b -= 1
    # 多重辺の場合はMIN
    d[a][b] = c
    d[b][a] = c
# 最適化(わーしゃゆふよいど)
for k in range(N):
    for i in range(N):
        # 左右は対称だろう
        for j in range(i+1,N):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])
            d[j][i] = d[i][j]

# 初期化2
d2 = [[INF]*N for i in range(N)]
for i in range(N):
    d2[i][i] = 0
for i in range(N):
    for j in range(N):
        # 給油できるところに辺を張る
        if d[i][j] <= L:
            d2[i][j] = 1
for k in range(N):
    for i in range(N):
        for j in range(i+1,N):
            d2[i][j] = min(d2[i][j], d2[i][k] + d2[k][j])
            d2[j][i] = d2[i][j]
            

#query
for a,b in Queries:
    s = min(a,b)-1
    t = max(a,b)-1
    
    ans = d2[s][t]
    if ans == INF:
        ans = 0
    print(ans-1)

Submission status: Accepted

Solution code:
N,M,L = map(int, input().split())
INF = 10**18
# 初期化
d = [[INF]*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 -= 1
    b -= 1
    # 多重辺の場合はMIN
    d[a][b] = c
    d[b][a] = c
# 最適化(わーしゃゆふよいど)
for k in range(N):
    for i in range(N):
        # 左右は対称だろう
        for j in range(i+1,N):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])
            d[j][i] = d[i][j]

# 初期化2
d2 = [[INF]*N for i in range(N)]
for i in range(N):
    d2[i][i] = 0
for i in range(N):
    for j in range(N):
        # 給油できるところに辺を張る
        if d[i][j] <= L:
            d2[i][j] = 1
for k in range(N):
    for i in range(N):
        for j in range(i+1,N):
            d2[i][j] = min(d2[i][j], d2[i][k] + d2[k][j])
            d2[j][i] = d2[i][j]
            

#query
Q = int(input())
for i in range(Q):
    l  = list(map(int, input().split()))
    s = min(l)-1
    t = max(l)-1
    
    ans = d2[s][t]
    if ans == INF:
        ans = 0
    print(ans-1)

Submission status: Accepted

Solution code:
def main():

    import sys
    input = sys.stdin.readline

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

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

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

    D2 = warshall_floyd(D2)

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

    D = warshall_floyd(D)

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

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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

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

#print(A)


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

B= floyd_warshall(B,directed = False)
"""for c in range(1,N+1):
    for a in range(1,N+1):
        for b in range(1,N+1):
            B[a][b]=min(B[a][b],B[a][c]+B[c][b])"""

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

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[float('inf')] * n_nodes for _ in range(n_nodes)]

    def add_edge(self, s, t, d):
        self.edges[s][t] = d
        self.edges[t][s] = d


class FloydWarshall:
    def __init__(self, graph):
        self.graph = graph
        self.distances = [[float('inf')] * graph.n_nodes
                          for _ in range(graph.n_nodes)]
        self._init()

    def _init(self):
        for x in range(self.graph.n_nodes):
            self.distances[x][x] = 0
        for source in range(self.graph.n_nodes):
            for destination, distance in enumerate(self.graph.edges[source]):
                self.distances[source][destination] = distance

    def compute_shortest_path_lengths(self):
        for k in range(self.graph.n_nodes):
            for i in range(self.graph.n_nodes):
                for j in range(self.graph.n_nodes):
                    s = self.distances[i][k] + self.distances[k][j]
                    if s < self.distances[i][j]:
                        self.distances[i][j] = s
        return self.distances


n, m, l = read_i()
graph = Graph(n)
for _ in range(m):
    a, b, c = read_i()
    if c > l:
        continue
    graph.add_edge(a - 1, b - 1, c)
fw = FloydWarshall(graph)
ds = fw.compute_shortest_path_lengths()

graph = Graph(n)
for s in range(n):
    for t in range(s + 1, n):
        if ds[s][t] > l:
            continue
        graph.add_edge(s, t, 1)
fw = FloydWarshall(graph)
ds = fw.compute_shortest_path_lengths()

q = int(input())
for _ in range(q):
    s, t = read_i()
    d = ds[s - 1][t - 1] - 1
    if d == float('inf'):
        print(-1)
    else:
        print(d)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[float('inf')] * n_nodes for _ in range(n_nodes)]

    def add_edge(self, s, t, d):
        self.edges[s][t] = d
        self.edges[t][s] = d


class FloydWarshall:
    def __init__(self, graph):
        self.graph = graph
        self.distances = [[float('inf')] * graph.n_nodes
                          for _ in range(graph.n_nodes)]
        self._init()

    def _init(self):
        for x in range(self.graph.n_nodes):
            self.distances[x][x] = 0
        for source in range(self.graph.n_nodes):
            for destination, distance in enumerate(self.graph.edges[source]):
                self.distances[source][destination] = distance

    def compute_shortest_path_lengths(self):
        for k in range(self.graph.n_nodes):
            for i in range(self.graph.n_nodes):
                for j in range(self.graph.n_nodes):
                    s = self.distances[i][k] + self.distances[k][j]
                    if s < self.distances[i][j]:
                        self.distances[i][j] = s
        return self.distances


n, m, l = read_i()
graph = Graph(n)
for _ in range(m):
    a, b, c = read_i()
    if c > l:
        continue
    graph.add_edge(a - 1, b - 1, c)
fw = FloydWarshall(graph)
ds = fw.compute_shortest_path_lengths()

graph = Graph(n)
for s in range(n):
    for t in range(n):
        if s >= t:
            continue
        if ds[s][t] > l:
            continue
        graph.add_edge(s, t, 1)
fw = FloydWarshall(graph)
ds = fw.compute_shortest_path_lengths()

q = int(input())
for _ in range(q):
    s, t = read_i()
    s -= 1
    t -= 1
    d = ds[s][t] - 1
    if d == float('inf'):
        print(-1)
    else:
        print(d)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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


def read_is(n=1):
    return [read_i() for _ in range(n)]


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[] for _ in range(n_nodes)]

    def add_edge(self, s, t, d=None, undirected=False):
        if d is not None:
            self.edges[s].append((t, d))
        else:
            self.edges[s].append(t)
        if undirected:
            self.add_edge(t, s, d)


class FloydWarshall:
    def __init__(self, graph):
        self.graph = graph
        self.distances = [[float('inf')] * graph.n_nodes
                          for _ in range(graph.n_nodes)]
        self.nexts = [[None] * graph.n_nodes for _ in range(graph.n_nodes)]
        self._init()

    def _init(self):
        for x in range(self.graph.n_nodes):
            self.distances[x][x] = 0
        for source in range(self.graph.n_nodes):
            for destination, distance in self.graph.edges[source]:
                self.distances[source][destination] = distance
                self.nexts[source][destination] = destination

    def compute_shortest_path_lengths(self):
        for k in range(self.graph.n_nodes):
            for i in range(self.graph.n_nodes):
                for j in range(self.graph.n_nodes):
                    s = self.distances[i][k] + self.distances[k][j]
                    if s < self.distances[i][j]:
                        self.distances[i][j] = s
                        self.nexts[i][j] = self.nexts[i][k]


n, m, l = read_i()
graph = Graph(n)
for _ in range(m):
    a, b, c = read_i()
    if c > l:
        continue
    graph.add_edge(a - 1, b - 1, d=c, undirected=True)
fw = FloydWarshall(graph)
fw.compute_shortest_path_lengths()

graph2 = Graph(n)
for s in range(n):
    for t in range(n):
        if s >= t:
            continue
        if fw.distances[s][t] > l:
            continue
        graph2.add_edge(s, t, d=1, undirected=True)
fw = FloydWarshall(graph2)
fw.compute_shortest_path_lengths()

q = int(input())
for _ in range(q):
    s, t = read_i()
    s -= 1
    t -= 1
    d = fw.distances[s][t] - 1
    if d == float('inf'):
        print(-1)
    else:
        print(d)

Submission status: Accepted

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

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


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

    g = [[float("inf")] * n for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        g[a][b] = c
        g[b][a] = c

    q = int(input())

    def f(x):
        return int(x) - 1

    st = (tuple(map(f, input().split())) for _ in range(q))

    g = csr_matrix(g)

    d = floyd_warshall(csgraph=g)

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

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

    refuel = csr_matrix(refuel)

    ans = floyd_warshall(refuel)

    for s, t in st:
        print(int(ans[s][t] - 1) if ans[s][t] != float("inf") else -1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
Q = int(input())
ST = [tuple(map(int,input().split())) for i in range(Q)]

INF = float('inf')
dist1 = [[INF]*N for i in range(N)]
dist2 = [[INF]*N for i in range(N)]
for a,b,c in ABC:
    if c > L: continue
    a,b = a-1,b-1
    dist1[a][b] = dist1[b][a] = c
for i in range(N):
    dist1[i][i] = 0
    dist2[i][i] = 0

for k in range(N):
    for i in range(N):
        for j in range(N):
            d = dist1[i][k] + dist1[k][j]
            if dist1[i][j] <= d: continue
            dist1[i][j] = d
for i in range(N):
    for j in range(N):
        if i==j: continue
        if dist1[i][j] <= L:
            dist2[i][j] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            d = dist2[i][k] + dist2[k][j]
            if dist2[i][j] <= d: continue
            dist2[i][j] = d
ans = []
for s,t in ST:
    d = dist2[s-1][t-1]
    if d == INF:
        ans.append(-1)
    else:
        ans.append(d-1)
print(*ans, sep='\n')

Submission status: Accepted

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


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

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

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



            



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
from collections import deque
N, M, L = map(int, input().split())
D = [[1<<40] * N for _ in range(N)]
for i in range(N):
    D[i][i] = 0
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    D[a][b] = c
    D[b][a] = c

for k in range(N):
    for i in range(N):
        for j in range(N):
            D[i][j] = min(D[i][j], D[i][k] + D[k][j])
Y = [[] for _ in range(N)]
for i in range(N):
    for j in range(N):
        if i == j: continue
        if D[i][j] <= L:
            Y[i].append(j)
def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return D
D2 = []
for i in range(N):
    D2.append(BFS(N, Y, i))

ans = []
for _ in range(int(input())):
    s, t = map(int, input().split())
    a = D2[s-1][t-1]-1
    ans.append(str(a if a >= 0 else -1))
print("\n".join(ans))

Submission status: Accepted

Solution code:
import sys


def main():
    n, m, l = [int(s) for s in sys.stdin.readline().strip().split()]
    a = [0] * m
    b = [0] * m
    c = [0] * m
    for i in range(m):
        a[i], b[i], c[i] = [int(s) for s in sys.stdin.readline().strip().split()]

    INF = float('inf')
    dist = [[INF] * n for _ in range(n)]
    for i in range(m):
        dist[a[i]-1][b[i]-1] = c[i]
        dist[b[i]-1][a[i]-1] = c[i]

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

    ldist = [[INF] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if dist[i][j] <= l:
                ldist[i][j] = 1

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

    q = int(sys.stdin.readline().strip())
    s = [0] * q
    t = [0] * q
    for i in range(q):
        s[i], t[i] = [int(s) for s in sys.stdin.readline().strip().split()]

    for i in range(q):
        s0, t0 = s[i] - 1, t[i] - 1
        if ldist[s0][t0] == INF:
            print(-1)
        else:
            print(ldist[s0][t0]-1)


main()

Submission status: Accepted

Solution code:
def use_fast_io():
    global input
    import io
    import sys
    f = io.BytesIO(sys.stdin.buffer.read())
    input = f.readline


#use_fast_io()

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


def solve():
    n, m, l = map(int, input().split())
    graph = np.full((n, n), 10 ** 10)
    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
    graph = floyd_warshall(graph, directed=False)
    graph = floyd_warshall(graph <= l, directed=False)
    graph[np.isinf(graph)] = 0
    Q = int(input())
    ans = []
    for _ in range(Q):
        s, t = map(int, input().split())
        ans.append(int(graph[s - 1][t - 1]) - 1)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
def use_fast_io():
    global input
    import io
    import sys
    f = io.BytesIO(sys.stdin.buffer.read())
    input = f.readline


use_fast_io()

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


def solve():
    n, m, l = map(int, input().split())
    graph = np.full((n, n), 10 ** 10)
    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
    graph = floyd_warshall(graph, directed=False)
    graph = floyd_warshall(graph <= l, directed=False)
    graph[np.isinf(graph)] = 0
    Q = int(input())
    ans = []
    for _ in range(Q):
        s, t = map(int, input().split())
        ans.append(int(graph[s - 1][t - 1]) - 1)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()