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 floyd_warshall

n, m, l = map(int, input().split())
inf = 10**12
d = [[inf for i in range(n)] for i in range(n)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(m):
    x,y,z = map(int,input().split())
    d[x-1][y-1] = z
    d[y-1][x-1] = z
for i in range(n):
    d[i][i] = 0 #自身のところに行くコストは０
dd = floyd_warshall(d)
ddd = [[inf for i in range(n)] for i in range(n)]
for i in range(n):
  for j in range(n):
    if dd[i][j] <= l:
      ddd[i][j] = 1
dddd =floyd_warshall(ddd)
q = int(input())
for i in range(q):
  s, t = map(int, input().split())
  if dddd[s-1][t-1] == inf:
    print(-1)
  else:
    print(int(dddd[s-1][t-1]-1))

Submission status: Accepted

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

class WarshallFloyd:
    def __init__(self,n):
        self.n = n
        self.inf = 100000000000000
        self.d = [[self.inf for _ in range(n)] for _ in range(n)]
        for i in range(self.n):
            self.d[i][i] = 0
    def register(self,v1,v2,l,multiple=True):
        self.d[v1][v2] = l
        if multiple:
            self.d[v2][v1] = l
    
    def solve(self):
        for i in range(self.n):
            for j in range(self.n):
                for k in range(self.n):
                    self.d[j][k] = min(self.d[j][k],self.d[j][i]+self.d[i][k])
        return self.d

W = WarshallFloyd(N)
for a,b,c in ABC:
    W.register(a-1,b-1,c)
D = W.solve()

WL = WarshallFloyd(N)
for i in range(N):
    for j in range(N):
        if D[i][j] <= L and i != j:
            WL.register(i,j,1)
DL = WL.solve()
ST = [list(map(int,input().split())) for _ in range(Q)]
for i in range(Q):
    s,t = ST[i]
    transition = DL[s-1][t-1]
    if transition == 100000000000000:
        print(-1)
    else:
        print(transition-1)

Submission status: Accepted

Solution code:
INF=10**15
N,M,L=map(int,input().split())
d=[[INF for i in range(N)] for j in range(N)]
d1=[[INF for i in range(N)] for j in range(N)]
for i in range(N):
    d[i][i]=0
for m in range(M):
    A,B,C=map(int,input().split())
    d[A-1][B-1]=C
    d[B-1][A-1]=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])
for i in range(N):
        for j in range(N):
            if i!=j and d[i][j]<=L:
                d1[i][j]=1
                d1[j][i]=1
for k in range(N):
    for i in range(N):
        for j in range(N):
            d1[i][j]=min(d1[i][j],d1[i][k]+d1[k][j])

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

Submission status: Accepted

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

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

T = []
T1 = []
for _ in range(N):
    T.append([float("inf")] * N)
    T1.append([float("inf")] * N)
for n in range(N):
    T[n][n] = 0
    T1[n][n] = 0

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

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

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

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

Q = int(input())
for _ in range(Q):
    S, G = list(map(int, input().split()))
    if math.isinf(T1[S-1][G-1]):
        print(-1)
    else:
        print(T1[S-1][G-1]-1)

Submission status: Accepted

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


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


def main():
    N, M, L = map(int, input().split())
    adj = [{} for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        adj[A-1][B-1] = C
        adj[B-1][A-1] = C
    dst = [[float("inf")] * N for _ in range(N)]
    for i in range(N):
        dst[i][i] = 0
        for j in adj[i]:
            dst[i][j] = adj[i][j]
    calc(N, dst)
    ans = [[float("inf")] * N for _ in range(N)]
    for i in range(N):
        ans[i][i] = 0
        for j in range(i+1, N):
            if dst[i][j] <= L:
                ans[i][j] = 1
                ans[j][i] = 1
    calc(N, ans)
    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        x = ans[s-1][t-1]
        print(-1 if x == float("inf") else x-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

def warshall_floyd(dp):
    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

dp = [[float('inf')]*n for _ in range(n)]

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

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

dp = warshall_floyd(dp)

dp2 = [[float('inf')]*n for _ in range(n)]

for i in range(n):
    for j in range(n):
        if dp[i][j] <= l:
            dp2[i][j] = 1
    dp2[i][i] = 0
dp2 = warshall_floyd(dp2)

q = int(input())

ans = [0]*q
for i in range(q):
    s, t = map(int,input().split())
    tmp = dp2[s-1][t-1]
    ans[i] = -1 if tmp == float('inf') else tmp - 1

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

Submission status: Accepted

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

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

def warshall_floyd(dp):
    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

dp = [[float('inf')]*n for _ in range(n)]

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

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

dp = warshall_floyd(dp)

dp2 = [[float('inf')]*n for _ in range(n)]

for i in range(n):
    for j in range(n):
        if dp[i][j] <= l:
            dp2[i][j] = 1
    dp2[i][i] = 0
dp2 = warshall_floyd(dp2)

q = int(input())

ans = [0]*q
for i in range(q):
    s, t = map(int,input().split())
    tmp = dp2[s-1][t-1]
    ans[i] = -1 if tmp == float('inf') else tmp - 1

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

Submission status: Accepted

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

N, M, L = map(int, input().split())
graph = np.array([[0 if i == j else float("inf")
                   for i in range(N)] for j in range(N)])
graph2 = np.array([[0 if i == j else float("inf")
                   for i in range(N)] for j in range(N)])


for _ in range(M):
    a, b, c = map(int, input().split())
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c
dist = floyd_warshall(graph)

graph2[(dist <= L) & (dist != 0)] = 1
dist2 = floyd_warshall(graph2)
dist2[dist2 == float("inf")] = 0

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

Submission status: Accepted

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

n, m, l = map(int, input().split())
INF = float("inf")

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

d = [[INF] * n for _ in range(n)]
for i in range(n):
    d[i][i] = 0
for i in range(m):
    a, b, c = map(int, input().split())
    d[a - 1][b - 1] = c
    d[b - 1][a - 1] = c
d = warshall_floyd(d, n)

d2 = [[INF] * n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            d2[i][j] = 1
    d2[i][i] = 0
d2 = warshall_floyd(d2, n)

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

Submission status: Accepted

Solution code:
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()
d = [[float("inf") for i in range(N)] for i in range(N)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(M):
    x,y,z = map(int,input().split())
    d[x-1][y-1] = z
    d[y-1][x-1] = z
for i in range(N):
    d[i][i] = 0 #自身のところに行くコストは０
#print(warshall_floyd(N,d))
cur = warshall_floyd(N,d)
newD = [[float("inf") for i in range(N)] for i in range(N)]
for i in range(N):
    for l,j in enumerate(cur[i]):
        if j<=L:
            newD[i][l] = 1
            newD[l][i]

ansC = warshall_floyd(N,newD)

Q = I()
for i in range(Q):
    s, t = LI()
    ans = ansC[s-1][t-1]-1
    if ans==inf:
        ans = -1
    print(ans)

Submission status: Accepted

Solution code:
import sys
import copy

N, M, L = list(map(int, sys.stdin.readline().strip().split(" ")))
INF = 10**10

def warshall_floyd(g_mat):
    dp = copy.copy(g_mat)
    
    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

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

for _ in range(M):
    a, b, c = list(map(int, sys.stdin.readline().strip().split(" ")))
    graph[a-1][b-1] = c
    graph[b-1][a-1] = c

dist_graph = warshall_floyd(graph)
bool_graph = [[INF for _ in range(N)] for _ in range(N)]

for i in range(N):
    for j in range(N):
        if dist_graph[i][j] <= L:
            bool_graph[i][j] = 1

ans_graph = warshall_floyd(bool_graph)

Q = int(sys.stdin.readline().strip())
for _ in range(Q):
    s, t = list(map(int, sys.stdin.readline().strip().split(" ")))
    ans = ans_graph[s-1][t-1]
    print(ans-1 if ans != INF else -1)

Submission status: Accepted

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

n,m,l = map(int,input().split())
cost = [[0]*n for i in range(n)]
for i in range(m):
  a,b,c = map(int,input().split())
  cost[a-1][b-1] = c
  cost[b-1][a-1] = c  

Cost = F(CSR(cost))
Cost = F(CSR(np.where((0<Cost)&(Cost<=l),1,0)))

q = int(input())
for i in range(q):
  s,t = map(int,input().split())
  print(-1 if np.isinf(Cost[s-1][t-1]) else int(Cost[s-1][t-1])-1)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

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

ABCQST = np.array(read().split(), dtype=np.int64)
ABC = ABCQST[:3*M]
A = ABC[::3]; B = ABC[1::3]; C = ABC[2::3]

Q = ABCQST[3*M]

ST = ABCQST[3*M + 1:]
S = ST[::2]; T = ST[1::2]

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

d[d <= L] = 1
d[d > L] = INF

d = floyd_warshall(d, directed=False).astype(int)
d[d == INF] = 0

d -= 1
print('\n'.join(d.astype(str)[S, T]))

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix
INF = 10**12
N, M, L = map(int, input().split())

A = []; B = []; C = []
for i in range(M):
    a, b, c = map(int, input().split())
    A.append(a - 1); B.append(b - 1); C.append(c)
A = np.array(A); B = np.array(B); C = np.array(C)

graph = csr_matrix((C, (A, B)), (N, N))
d = floyd_warshall(graph, directed=False)

d[d <= L] = 1
d[d > L] = INF

d = floyd_warshall(d, directed=False)

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

Submission status: Accepted

Solution code:
from sys import setrecursionlimit as SRL, stdin
inf = 10**15
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())

n, m, l = rrd()
dis = [[inf] * 305 for _i in range(305)]
need = [[inf] * 305 for _i in range(305)]
for i in range(n):
    dis[i][i] = 0
for i in range(m):
    a, b, c = rrd()
    dis[a][b] = c
    dis[b][a] = c

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

for i in range(1, n + 1):
    for j in range(1, n + 1):
        if i == j:
            need[i][j] = 0
        elif dis[i][j] <= l:
            need[i][j] = 1

for k in range(1, n + 1):
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            need[i][j] = min(need[i][j], need[i][k] + need[k][j])
q = int(input())

while q:
    s, t = rrd()
    if need[s][t] < inf:
        print(need[s][t]-1)
    else:
        print(-1)
    q -= 1

Submission status: Accepted

Solution code:
import math
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N, M, L = IL()
abc = [IL() for _ in range(M)]
Q = I()
q = [IL() for _ in range(Q)]

dp1 = [[MAX_INT]*N for _ in range(N)]
for a, b, c in abc:
  dp1[a - 1][b - 1] = c
  dp1[b - 1][a - 1] = c

for k in range(N):
  for i in range(N):
    for j in range(N):
      if i == j:
        dp1[i][j] = 0
      else:
        dp1[i][j] = min(dp1[i][j], dp1[i][k] + dp1[k][j])

dp2 = [[MAX_INT]*N for _ in range(N)]
for i in range(N):
  for j in range(N):
    if dp1[i][j] <= L:
      dp2[i][j] = 1

for k in range(N):
  for i in range(N):
    for j in range(N):
      if i == j:
        dp2[i][j] = 0
      else:
        dp2[i][j] = min(dp2[i][j], dp2[i][k] + dp2[k][j])

for s, t in q:
  if dp2[s - 1][t - 1] == MAX_INT:
    print(-1)
  else:
    print(dp2[s - 1][t - 1] - 1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]

    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        distk = dist[k]
        for i in range(n):
            if i == k:
                continue
            disti = dist[i]
            distik = dist[i][k]
            for j in range(i + 1, n):
                if distik + distk[j] < disti[j]:
                    disti[j] = distik + distk[j]
                    dist[j][i] = disti[j]

    lis = [[] for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if dist[i][j] <= l:
                supply[i][j] = 0
                supply[j][i] = 0
                lis[i].append(j)
                lis[j].append(i)

    for i in range(n):
        q = []
        for k in lis[i]:
            heappush(q, (0, k))
        supplyi = supply[i]

        while q:
            time, p = heappop(q)
            for k in lis[p]:
                if supplyi[k] > time + 1:
                    supplyi[k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]

    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        distk = dist[k]
        for i in range(n):
            if i == k:
                continue
            disti = dist[i]
            for j in range(i + 1, n):
                if disti[k] + distk[j] < disti[j]:
                    disti[j] = disti[k] + distk[j]
                    dist[j][i] = disti[j]

    lis = [[] for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if dist[i][j] <= l:
                supply[i][j] = 0
                supply[j][i] = 0
                lis[i].append(j)
                lis[j].append(i)

    for i in range(n):
        q = []
        for k in lis[i]:
            heappush(q, (0, k))
        supplyi = supply[i]

        while q:
            time, p = heappop(q)
            for k in lis[p]:
                if supplyi[k] > time + 1:
                    supplyi[k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Accepted

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

N, M, L = map(int, input().split())
graph = np.array([[0 if i == j else float("inf")
                   for i in range(N)] for j in range(N)])
for _ in range(M):
    a, b, c = map(int, input().split())
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c

Q = int(input())
dist = floyd_warshall(graph)


graph2 = np.array([[float("inf")] * N for _ in range(N)])
np.fill_diagonal(graph2, 0)
graph2[(dist <= L) & (dist != 0)] = 1

dist2 = floyd_warshall(graph2)
dist2[dist2 == float("inf")] = 0

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

Submission status: Accepted

Solution code:
import numpy as np
import sys
from scipy.sparse.csgraph import floyd_warshall,csgraph_from_dense
from scipy.sparse import csr_matrix
input = sys.stdin.readline
def inputs():return [int(x) for x in input().split()]
N,M,L = inputs()
ABC =[inputs() for _ in range(M)]
graph = [[10**13]*(N+1) for _ in range(N+1)]
for a,b,c in ABC:
    graph[a][b] = c
G = csgraph_from_dense(graph, null_value=10**13)
dist_mat = floyd_warshall(graph,directed=False)
graph2 = np.array([[10**13]*(N+1) for _ in range(N+1)])
np.fill_diagonal(graph2,0)
graph2[dist_mat<=L]=1
dist_mat2 = floyd_warshall(graph2,directed=False)
dist_mat2[dist_mat2==10**13]=0
Q = int(input())
for i in range(Q):
    s,t = inputs()
    print(int(dist_mat2[s,t])-1)

Submission status: Accepted

Solution code:
from enum import Enum
from queue import Queue

import numpy as np

import collections
import bisect
import sys
import math

from scipy.sparse.csgraph import floyd_warshall

BIG_NUM = 200000000000
MOD = 1000000007
EPS = 0.000000001

def warshall_floyd(d,n):
    #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,M,L = map(int,input().split())
d = [[float("inf") for i in range(N)] for j in range(N)]
for i in range(M):
    a,b,c = map(int,input().split())
    d[a-1][b-1] = c
    d[b-1][a-1] = c
for i in range(N):
    d[i][i] = 0
d = floyd_warshall(d)
for i in range(N):
    for j in range(i,N):
        if d[i][j] <= L:
            d[i][j] = 1
            d[j][i] = 1
        else:
            d[i][j] = float("inf")
            d[j][i] = float("inf")
    d[i][i] = 1
d = floyd_warshall(d)
Q = int(input())
for q in range(Q):
    s,t = map(int,input().split())
    if d[s-1][t-1] == float("inf"):
        print(-1)
    else:
        print(int(d[s-1][t-1])-1)

Submission status: Accepted

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

n, m, l = map(int, input().split())
abc = []
for _ in range(m):
    abc.append(map(int, input().split()))
q = int(input())
st = []
for _ in range(q):
    st.append(map(int, input().split()))

adjacency_matrix = np.zeros((n, n))
for a, b, c in abc:
    adjacency_matrix[a-1, b-1] = c
    adjacency_matrix[b-1, a-1] = c

shotest = dijkstra(adjacency_matrix)
fuel_once = np.where(shotest <= l, 1, 0)
fuel_times = dijkstra(fuel_once-np.eye(n))

for s, t in st:
    ans = fuel_times[s-1][t-1]
    if np.isinf(ans):
        print(-1)
    else:
        print(int(ans) - 1)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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

G = [list(map(int, input().split())) for _ in range(M)]
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]

# neighborhood graph
nei_graph = [[0] * N for _ in range(N)]
for a, b, c in G:
    nei_graph[a - 1][b - 1] = c
    nei_graph[b - 1][a - 1] = c

# Warshall Floyd
nei_graph = floyd_warshall(nei_graph)

# 1 if distance is less than L
for i in range(N):
    for j in range(N):
        if nei_graph[i][j] <= L:
            nei_graph[i][j] = 1
        else:
            nei_graph[i][j] = 0

nei_graph = floyd_warshall(nei_graph)

for start, end in Query:
    if nei_graph[start - 1][end - 1] - 1 == float('inf'):
        print(-1)
    else:
        print(int(nei_graph[start - 1][end - 1] - 1))

Submission status: Accepted

Solution code:
N, M, L = map(int,input().split())
MAX=99999999999
A=[]
B=[]
C=[]
D=[[MAX for _ in range(N)] for _ in range(N)]
F=[[MAX for _ in range(N)] for _ in range(N)]
s=[]
t=[]
 
for i in range(M):
    l=list(map(int,input().split()))
    A.append(l[0]-1)
    B.append(l[1]-1)
    C.append(l[2])
 
 
 
Q=int(input())
 
for i in range(Q):
    m=list(map(int,input().split()))
    s.append(m[0]-1)
    t.append(m[1]-1)
 
 
for i in range(M):
    if C[i]>L : continue
    D[A[i]][B[i]]=C[i]
    D[B[i]][A[i]]=C[i]
 
for i in range(N):  D[i][i]=0
 
for k in range(N):
    for i in range(N):
        for j in range(N):
            if (D[i][k]+D[k][j])<D[i][j] :
                D[i][j]=D[i][k]+D[k][j]
 
for i in range(N):
    for j in range(N):
        if i==j : continue
        if D[i][j]<=L: F[i][j]=1
 
 
for i in range(N):  F[i][i]=0
 
for k in range(N):
    for i in range(N):
        for j in range(N):
            if (F[i][k]+F[k][j])<F[i][j] :
                F[i][j]=F[i][k]+F[k][j]
 
 
for p in range(Q) :
    if F[s[p]][t[p]] < MAX :
        print(F[s[p]][t[p]]-1)
    else :
        print(-1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
ii0 = lambda: ii() - 1
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')

def main():
    N,M,L = mis()
    from scipy.sparse.csgraph import floyd_warshall
    import numpy as np
    INF = np.iinfo(np.int64).max
    d = np.full((N,N), INF, dtype=np.uint64)
    for i in range(N):
        d[i,i] = 0
    #
    for _ in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        if c <= L:
            d[a,b] = c
            d[b,a] = c
    #
    '''
    for k in range(N):
        for i in range(N):
            np.minimum(d[i,:], d[i,k]+d[k,:], out=d[i,:])    
    '''
    d = floyd_warshall(d)
    #
    d2 = np.full((N,N), INF, dtype=np.uint64)
    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):
            np.minimum(d2[i,:], d2[i,k]+d2[k,:], out=d2[i,:])    
    '''
    d2 = floyd_warshall(d2)
    #
    Q = ii()
    for _ in range(Q):
        s,t = mis()
        s -= 1
        t -= 1
        dist = d2[s,t]
        if dist == INF:
            print(-1)
        else:
            print(int(dist)-1)




main()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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

Q = int(input())
st = []
for _ in range(Q):
    st.append([int(j) - 1 for j in input().split()])

edges = floyd_warshall(edges)

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

edges = floyd_warshall(edges)

for i, j in st:
    if edges[i][j] == float("inf"):
        print(-1)
    else:
        print(int(edges[i][j]) - 1)

Submission status: Accepted

Solution code:
"""
気付き
１、float('inf')はちょい遅いみたい
２、input()よりもinput = sys.stdin.readlineの方が爆速らしい（知らんがな）
"""
import sys
inf = 10 ** 15
input = sys.stdin.readline

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

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])
#print('distance={}'.format(dp))


dp2 = [[inf] * N for _ in range(N)]
for a in range(N - 1):
    for b in range(a+1, N):
        if dp[a][b] <= L:
            dp2[a][b] = 1
            dp2[b][a] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k] + dp2[k][j])
#print('times={}'.format(dp2))


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

Submission status: Accepted

Solution code:
inf = 10 ** 15

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

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])
#print('distance={}'.format(dp))


dp2 = [[inf] * N for _ in range(N)]
for a in range(N - 1):
    for b in range(a+1, N):
        if dp[a][b] <= L:
            dp2[a][b] = 1
            dp2[b][a] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k] + dp2[k][j])
#print('times={}'.format(dp2))


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

Submission status: Accepted

Solution code:
import sys

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

INF = 100100100100100

dp = [[INF]*N for i in range(N)]
for s,e,d in P:
	if d<=L:
		dp[s-1][e-1] = d
		dp[e-1][s-1] = d
for i in range(N):
	dp[i][i] = 0

for k in range(N):
	for y in range(N):
		for x in range(N):
			dp[y][x] = min(dp[y][x], dp[y][k]+dp[k][x])

dp2 = [[INF]*N for i in range(N)]
for y in range(N):
	for x in range(N):
		if dp[y][x]<=L:
			dp2[y][x] = 1

for k in range(N):
	for y in range(N):
		for x in range(N):
			dp2[y][x] = min(dp2[y][x], dp2[y][k]+dp2[k][x])

for s, t in st:
	count = dp2[s-1][t-1]
	if count==INF:
		print(-1)
	else:
		print(count-1)