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:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    dis_table = [[10 ** 12 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        dis_table[i][i] = 0

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            dis_table[a][b] = c
            dis_table[b][a] = c

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

    #print(dis_table)

    nt = [[10 ** 12 for _ in range(N)] for _ in range(N)]


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

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

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

    q = iip(False)
    ans = []

    for i in range(q):
        a, b = iip()
        c = nt[a-1][b-1]
        if c == 10**12:
            ans.append(-1)
        else:
            ans.append(c-1)

    split_print_enter(ans)


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import dijkstra as di

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

inf = float('INF')
road = [[0 for i in range(n)] for j in range(n)]
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    road[a][b] = road[b][a] = c

def warshall(d, n):
    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]

roads = di(road, n)
# [print(cost) for cost in road]
# print()
costs = [[1 if roads[i][j] <= l and i != j else 0 for j in range(n)] for i in range(n)]
costs = di(costs, n)

# [print(cost) for cost in costs]
q = int(input())
for i in range(q):
    s,t = map(int, input().split())
    
    print(int(costs[s-1][t-1]-1) if costs[s-1][t-1] < inf else -1)

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

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

csr1=csr_matrix(d)

a=floyd_warshall(csr1)

d=[[0 for i in range(0,N)] for j in range(0,N)]
for i in range(0,N):
    for j in range(0,N):
        if L>=a[i][j]:
            d[i][j]=1


csr2=csr_matrix(d)

data=floyd_warshall(csr2)
ans=[]
Q=int(input())
for i in range(0,Q):
    s,t=map(int,input().split())
    if data[s-1][t-1]!=float('inf'):
        ans.append(int(data[s-1][t-1])-1)
    else:
        ans.append(-1)

for i in range(Q):
    print(ans[i])

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    n,m,l = map(int,input().split())
    E = [[float("INF")]*n for i in range(n)]
    for i in range(m):
        a,b,c = map(int,input().split())
        E[a-1][b-1] = c
        E[b-1][a-1] = c

    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])
    wa = [[float("INF")]*n for i in range(n)]
    for i in range(n):
        for j in range(n):
            if E[i][j] <= l:
                wa[i][j] = 1
    for k in range(n):
        for i in range(n):
            for j in range(n):
                wa[i][j] = min(wa[i][j],wa[i][k]+wa[k][j])
    
    x = int(input())
    for i in range(x):
        s,g = map(int,input().split())
        if wa[s-1][g-1] == float("INF"):
            print(-1)
        else:
            print(wa[s-1][g-1]-1)

    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,m,l = map(int, input().split())
wf=[[float("inf") for i in range(n)] for j in range(n)]
for i in range(m):
    a,b,c = list(map(int,input().split()))
    wf[a-1][b-1] = c
    wf[b-1][a-1] = c
q = int(input())
st=[list(map(int,input().split())) for i in range(q)]

from scipy.sparse.csgraph import floyd_warshall
for i in range(n):
    wf[i][i]=0
wf=floyd_warshall(wf)

for i in range(n):
    for j in range(n):
        if wf[i][j] <= l:
            wf[i][j] = 1
        else:
            wf[i][j] = float("inf")

wf=floyd_warshall(wf)

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

Submission status: Accepted

Solution code:
n,m,l = map(int, input().split())
wf=[[float("inf") for i in range(n)] for j in range(n)]
for i in range(m):
    a,b,c = list(map(int,input().split()))
    wf[a-1][b-1] = c
    wf[b-1][a-1] = c
q = int(input())
st=[list(map(int,input().split())) for i in range(q)]

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

for i in range(n):
    for j in range(n):
        if wf[i][j] <= l:
            wf[i][j] = 1
        else:
            wf[i][j] = float("inf")

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

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

Submission status: Accepted

Solution code:
#dame datta...
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix
def main():
    N, M, L = map(int, input().split())
    l = [[0] * N for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        if c > L:
            continue
        l[a-1][b-1] = c
        l[b-1][a-1] = c
    G = csr_matrix(l)
    d = floyd_warshall(G)
    l = [[0] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if d[i][j] <= L:
                l[i][j] = 1
    G = csr_matrix(l)
    d = floyd_warshall(G)
    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        x = d[s][t]
        if x != float('inf'):
            print(int(x)-1)
        else:
            print(-1)
main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

INF = 10 ** 15

def warshall_floyd(dist, n):
    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 = lr()
dist = [[INF] * (N+1) for _ in range(N+1)] # 1-indexed
for _ in range(M):
    a, b, c = lr()
    if c > L:
        continue
    dist[a][b] = c
    dist[b][a] = c

dist = warshall_floyd(dist, N+1)
supply = [[INF] * (N+1) for _ in range(N+1)] # 1-indexed 距離L以下で供給が1回必要
for i in range(1, N+1):
    for j in range(i+1, N+1):
        if dist[i][j] <= L:
            supply[i][j] = supply[j][i] =  1

supply = warshall_floyd(supply, N+1)
Q = ir()
for _ in range(Q):
    s, t = lr()
    x = supply[s][t] - 1
    print(-1 if x + 1 == INF else x)

Submission status: Accepted

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

input = sys.stdin.readline

cost = []
row = []
col = []

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

for _ in range(m):
    a, b, c = map(int, input().split())
    cost.append(c)
    row.append(a-1)
    col.append(b-1)

q = int(input())
st = [list(map(int, input().split())) for _ in range(q)]

csr = csr_matrix((cost, (row, col)), shape = (n, n))
path = floyd_warshall(csr, directed=False)

cost = []
row = []
col = []

for i in range(n):
    for j in range(n):
        if path[i][j] <= l:
            cost.append(1)
            row.append(i)
            col.append(j) 

csr = csr_matrix((cost, (row, col)), shape = (n, n))
path = floyd_warshall(csr, directed=False)

INF = float('inf')

for s,t in st:
    ans = path[s-1][t-1]
    if ans == INF:
        print(-1)
    else:
        print(int(ans) - 1)

Submission status: Accepted

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

input = sys.stdin.readline

n, m, l = list(map(int, input().split()))
g_dense = np.zeros((n, n))

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

q = int(input())
st = [list(map(int, input().split())) for _ in range(q)]

path = shortest_path(g_dense, directed=False)

g_dense = np.zeros((n, n))

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

path = shortest_path(g_dense, directed=False)

INF = float('inf')

for s,t in st:
    ans = path[s-1][t-1]
    if ans == INF:
        print(-1)
    else:
        print(int(ans) - 1)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    
    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
      
    n, m, l = map(int, input().split())
    f_inf = float('inf')
    dist = [[f_inf]*n for _ in range(n)]
    for _ 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 = [[f_inf]*n for _ 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 _ in range(q):
        s, t = map(int, input().split())
        if dist2[s-1][t-1] == f_inf:
            print(-1)
        else:
          ans = dist2[s-1][t-1]
          print(ans-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    
    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
      
    n, m, l = map(int, input().split())
    f_inf = float('inf')
    dist = [[f_inf]*n for _ in range(n)]
    
    for _ 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 = [[f_inf]*n for _ 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 _ in range(q):
        s, t = map(int, input().split())
        if dist2[s-1][t-1] == f_inf:
            print(-1)
        else:
          ans = dist2[s-1][t-1]
          print(ans-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

def main():
    n, m, l = map(int, input().split())
    f_inf = float('inf')
    dist = [[f_inf]*n for _ in range(n)]
    
    def Warshall_Floyd(d):
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    d[i][j] = min(d[i][j], d[i][k]+d[k][j])
        return d
      
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        dist[a][b] = c
        dist[b][a] = c

    Warshall_Floyd(dist)

    dist2 = [[f_inf]*n for _ 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 _ in range(q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if dist2[s][t] == f_inf:
            print(-1)
        else:
          ans = dist2[s][t]
          print(ans-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

    e = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if dist[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 _ in range(Q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if e[s][t] == float('inf'):
            print(-1)
            continue
        ans = e[s][t]
        print(ans-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
input = sys.stdin.buffer.readline
INF = 10**12

N, M, L = map(int, input().split())
G = np.zeros((N, N), dtype=np.int64)
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())
ST = [list(map(int, input().split())) for _ in range(Q)]

fw = floyd_warshall(G)
path = np.full((N, N), INF, dtype=np.int64)
path[fw <= L] = 1
path_fw = (floyd_warshall(path) + 0.5).astype(np.int64)

ans = []
for s, t in ST:
    s -= 1
    t -= 1
    if path_fw[s][t] >= INF:
        ans.append(-1)
        continue
    ans.append(path_fw[s][t]-1)

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

Submission status: Accepted

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

class Graph():  #non-directed
    def __init__(self, n, edge):
        self.n = n
        self.graph = [[] for _ in range(n)]
        for e in edge:
            self.graph[e[0] - 1].append((e[1] - 1, e[2]))
            self.graph[e[1] - 1].append((e[0] - 1, e[2]))

    def warshall_floyd(self, INF=10**18):
        dist = [[INF for j in range(self.n)] for i in range(self.n)]
        for i in range(self.n):
            dist[i][i] = 0
        for i in range(self.n):
            for j, cost in self.graph[i]:
                dist[i][j] = cost
        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][k] != INF and dist[k][j] != INF:
                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
        return dist

INF = 10**18

N, M, L = map(int, input().split())
E = [tuple(map(int, input().split())) for _ in range(M)]

G = Graph(N, E)
D = G.warshall_floyd()

for i in range(N):
    for j in range(N):
        if i == j:
            continue
        if D[i][j] > L:
            D[i][j] = INF
        else:
            D[i][j] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            if D[i][k] != INF and D[k][j] != INF:
                D[i][j] = min(D[i][j], D[i][k] + D[k][j])

Q = int(input())

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

Submission status: Accepted

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

# scipy version

import sys
from collections import deque
from array import array

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

def input():
    return sys.stdin.readline().rstrip('\n')

##### main

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

C = [[0]*N for _ in range(N)]

for i in range(M):
    a,b,c = list(map(int, input().split()))
    if c>L:
        continue
    C[a-1][b-1] = c

Q = int(input())

ST = [None]*Q

for i in range(Q):
    s, t = list(map(int, input().split()))
    ST[i] = (s-1,t-1)

dist_matrix, predecessors = floyd_warshall(csgraph=C, directed=False, return_predecessors=True)

# D[i][j] <= L となる i,j に辺を張る
for i in range(N):
    for j in range(i+1,N):
        if dist_matrix[i][j] <= L:
            C[i][j] = 1

dist_matrix, predecessors = floyd_warshall(csgraph=C, directed=False, return_predecessors=True)

# answer
for q in range(Q):
    i,j = ST[q]
    step = dist_matrix[i][j]
    if step > 10**9:
        print(-1)
    else:
        print(int(step-1))

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
Max = 10**18
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())

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

def on():
    N,M,L = m()

    e = [[Max for i in range(N)]for j in range(N)]

    for i in range(M):
        a,b,c = m()
        e[a-1][b-1] = c
        e[b-1][a-1] = c

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

    d = wa(e)


    E = [[Max for i in range(N)]for j in range(N)]

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

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

    E = wa(E)
    q = onem()
    for i in range(q):
        s,t = m()
        if E[s-1][t-1] == Max:
            print(-1)
        else:
            print(E[s-1][t-1]-1)

if __name__ == "__main__":
    on()

Submission status: Accepted

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

def main():
    N,M,L = map(int,input().split())
    edge = np.zeros((N,N))
    for _ in range(M):
        a,b,c = map(int,input().split())
        edge[a-1][b-1] = edge[b-1][a-1] = c
        
    length = floyd_warshall(edge,directed=False)
    ref = np.where(length<=L,1,0)
    ans = floyd_warshall(ref,directed=False)
    Q = int(input())
    for _ in range(Q):
        s,t = map(int,input().split())
        if ans[s-1][t-1] == float("inf"):
            print(-1)
        else:
            print(int(ans[s-1][t-1])-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

N, M, L = (int(i) for i in input().split())

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

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

graph = csr_matrix(graph)
d = floyd_warshall(csgraph=graph, directed=False)

new_graph = [[0]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        if d[i][j] <= L:
            new_graph[i][j] = 1
            new_graph[j][i] = 1

graph = csr_matrix(new_graph)
d = floyd_warshall(csgraph=graph, directed=False)
Q = int(input())
for i in range(Q):
    s, t = (int(i) for i in 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:
N, M, L = (int(i) for i in input().split())

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

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

graph = csr_matrix(graph)
d = floyd_warshall(csgraph=graph, directed=False)

new_graph = [[0]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        if d[i][j] <= L:
            new_graph[i][j] = 1
            new_graph[j][i] = 1

graph = csr_matrix(new_graph)
d = floyd_warshall(csgraph=graph, directed=False)
Q = int(input())
for i in range(Q):
    s, t = (int(i) for i in 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:
n, m, l = map(int, input().split())
x = [[] for _ in range(n)]
dp = [[n*10**9 for _ in range(n)] for _ in range(n)]
for _ in range(m):
  a, b, c = map(int, input().split())
  if c <= l:
    x[a-1].append(b-1)
    x[b-1].append(a-1)
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
q = int(input())
st = []
for _ in range(q):
  st.append(list(map(int, input().split())))
dp[0][0] = 0
for i in range(1,n):
  dp[i][i] = 0
  for j in range(i):
    for a in x[i]:
      dp[i][j] = min(dp[i][j],dp[i][a]+dp[a][j])
    dp[j][i] = dp[i][j]
  for j in range(i):
    for k in range(i):
      dp[j][k] = min(dp[j][k],dp[j][i]+dp[i][k])
dp2 = [[n for _ in range(n)] for _ in range(n)]
for i in range(n):
  for j in range(n):
    if dp[i][j] <= l:
      dp2[i][j] = 1
for i in range(1,n):
  for j in range(i):
    for k in range(i):
      dp2[i][j] = min(dp2[i][j],dp2[i][k]+dp2[k][j])
    dp2[j][i] = dp2[i][j]
  for j in range(i):
    for k in range(i):
      dp2[j][k] = min(dp2[j][k],dp2[j][i]+dp2[i][k])
for u in st:
  ans = dp2[u[0]-1][u[1]-1]
  if ans >= n:
    print(-1)
  else:
    print(ans-1)

Submission status: Accepted

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

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

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

    e = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if dist[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 _ in range(Q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if e[s][t] == float('inf'):
            print(-1)
            continue
        ans = e[s][t]
        print(ans-1)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

N, M, L = map(int, input().split())
inf = 10**15
V = [[] for _ in range(N)]

for _ in range(M):
    A, B, C = map(int, input().split())
    if C>L:continue
    V[A-1].append((B-1, C))
    V[B-1].append((A-1, C))

dists = []
for i in range(N):
    dist = [(inf,inf)] * N
    dist[i] = (0, 0)
    u = [False] * N
    for _ in range(N):
        (charged, used), j = min([(dist[i], i) for i in range(N) if not u[i]])
        u[j] = True
        for k, next_cost in V[j]:
            if j==k: continue
            c = (charged+1, next_cost) if used+next_cost>L else (charged, used+next_cost)
            if dist[k] > c:
                dist[k] = c
    dists.append(dist)

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
import sys
input = sys.stdin.readline

N, M, L = map(int, input().split())
inf = 10**15
V = [[] for _ in range(N)]

for _ in range(M):
    A, B, C = map(int, input().split())
    if C>L:continue
    V[A-1].append((B-1, C))
    V[B-1].append((A-1, C))

dists = []
for i in range(N):
    dist = [(inf,inf)] * N
    dist[i] = (0, 0)
    u = [False] * N
    for _ in range(N):
        (charged, used), j = min([(dist[i], i) for i in range(N) if not u[i]])
        u[j] = True
        for k, next_cost in V[j]:
            if j==k: continue
            c = (charged+1, next_cost) if used+next_cost>L else (charged, used+next_cost)
            if dist[k] > c:
                dist[k] = c
    dists.append(dist)

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

Submission status: Accepted

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, L = lr()
INF = 10 ** 19
dis = [[INF for _ in range(N+1)] for _ in range(N+1)]
for _ in range(M):
    a, b, c = lr()
    if c > L:
        continue
    dis[a][b] = c
    dis[b][a] = c

for k in range(N+1): # kが中継地点
    for i in range(N+1):
        for j in range(i+1, N+1):
            x = dis[i][k] + dis[k][j]
            if x < dis[i][j]:
                dis[i][j] = dis[j][i] = x

supply = [[INF] * (N+1) for _ in range(N+1)]
for i in range(N+1):
    for j in range(i+1, N+1):
        if dis[i][j] <= L:
            supply[i][j] = supply[j][i] = 1

for k in range(N+1): # kが中継地点
    for i in range(N+1):
        for j in range(i+1, N+1):
            y = supply[i][k] + supply[k][j]
            if y < supply[i][j]:
                supply[i][j] = supply[j][i] = y

Q = ir()
for _ in range(Q):
    s, t = lr()
    if supply[s][t] == INF:
        print(-1)
    else:
        print(supply[s][t] - 1)

# 59

Submission status: Accepted

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

def Warshall_Floyd(N,DIST):
    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())

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

inf=L+1
dist=[[inf]*N for i in range(N)]
for i in range(N):
    dist[i][i]=0
for A,B,C in ABC:
    dist[A-1][B-1]=min(dist[A-1][B-1],C)
    dist[B-1][A-1]=min(dist[B-1][A-1],C)

dist=Warshall_Floyd(N,dist)
dist_2=[[N+1]*N for i in range(N)]

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

dist_2=Warshall_Floyd(N,dist_2)

for s,t in st:
    if dist_2[s-1][t-1]==N+1:
        print(-1)
    else:
        print(dist_2[s-1][t-1]-1)

Submission status: Accepted

Solution code:
n,m,l = map(int,input().split())
abe = [list(map(int,input().split())) for i in range(m)]
dist = [[10**18 for i in range(n)] for i in range(n)]
for a,b,e in abe:
  dist[a-1][b-1] = e
  dist[b-1][a-1] = e
for k in range(n):
  for i in range(n):
    for j in range(n):
      dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j])
for i in range(n):
  for j in range(n):
    if dist[i][j] <= l:
      dist[i][j] = 1
    else:
      dist[i][j] = 10**18
for k in range(n):
  for i in range(n):
    for j in range(n):
      dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j])
q = int(input())
for i in range(q):
  s,t = map(int,input().split())
  x = dist[s-1][t-1]-1
  if x == 10**18-1:
    print(-1)
  else:
    print(x)