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:
# https://atcoder.jp/contests/abc143/submissions/15557307

"""
タグ: ワーシャルフロイド
"""

class Graph:
    class Edge:
        def __init__(self, to, cost):
            """
            :param to:  終点ノード
            :param cost: 辺の重み
            """
            self.to, self.cost = to, cost

    def __init__(self, n, directed=False, decrement=True, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.edges2 = []                            # ワーシャルフロイド用
        for x, y, cost in edges:
            self.add_edge(x, y, cost)

    def add_edge(self, x, y, cost):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges2.append((x, y, cost))
        if self.directed == False:
            self.edges2.append((y, x, cost))     # ワーシャルフロイド用

    def warshall_folyd(self, INF=1<<30):
        """
        :param INF: INF = 10**18 にすると、負のコストがある場合に少し面倒になる
        :return: 頂点 i, j 間の距離を行列として返す
        """
        dist = [[INF] * self.n for _ in range(self.n)]

        for i, j, cost in self.edges2:
            dist[i][j] = cost
        for i in range(self.n):
            dist[i][i] = 0  # 自身のところに行くコストは０

        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        return dist

def max2(x,y):
    return x if x > y else y

from itertools import combinations

N, M, L = map(int, input().split())
graph = Graph(N, directed=False, decrement=True)
for _ in range(M):
    x, y, cost = map(int, input().split())
    graph.add_edge(x, y, cost)

d = graph.warshall_folyd()

graph2 = Graph(N, directed=False, decrement=False)
for i, j in combinations(range(N), 2):
    if d[i][j] <= L:
        graph2.add_edge(i, j, 1)


d = graph2.warshall_folyd()

for _ in range(int(input())):
    s, t, = map(int, input().split())
    s, t = s-1, t-1
    print(d[s][t]-1 if d[s][t] < 1<<20 else -1)

Submission status: Accepted

Solution code:
import numpy as np

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

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

if M == 0:
    Q = int(input())
    for _ in range(Q):
        print(-1)
    exit()

R = np.array([tuple(map(int, input().split())) for _ in range(M)])
matr = csr_matrix((R[:, 2], (R[:, 0] - 1, R[:, 1] - 1)), shape=(N, N))
way = floyd_warshall(matr, directed=False).astype(int)

way = np.where((way >= 0) & (way <= L), 1, 0)
matr_replenishment = csr_matrix(way)
way_replenishment = floyd_warshall(matr_replenishment, directed=False).astype(int).tolist()

Q = int(input())
for _ in range(Q):
    S, T = map(int, input().split())
    print(res - 1 if (res := way_replenishment[S - 1][T - 1]) >= 0 else -1)

Submission status: Accepted

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


def solve(N,L,edges,queries):

    graph = np.zeros((N,N),dtype=int)
    for a,b,c in edges:
        graph[a-1,b-1] = c
        graph[b-1,a-1] = c

    dist = floyd_warshall(graph, directed=False)
    dist = (dist<=L)
    dist = floyd_warshall(dist, directed=False)
    res = []
    for a,b in queries:
        d = dist[a-1,b-1]
        res.append(int(d-1) if d != float('inf') else -1)
    return res

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

if __name__ == '__main__':

    t = read().split()

    N,M,L = map(int,t[:3])

    m = map(int,t[3:M*3+3])
    edges = zip(m,m,m)

    Q = int(t[M*3+3])
    m = map(int, t[M*3+4:])
    queries = zip(m,m)

    print(*solve(N,L,edges,queries), sep='\n')

Submission status: Accepted

Solution code:

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

INF = 10 ** 9 + 7
graph = [[INF] * N for _ in range(N)]
count = [[INF] * N for _ in range(N)]
for i in range(N):
    graph[i][i] = 0
    count[i][i] = 0

for a, b, c in X:
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c

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

for i in range(N):
    for j in range(N):
        if i != j and graph[i][j] <= L:
            count[i][j] = 1

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

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

Submission status: Accepted

Solution code:
class Graph:
    class Edge:
        def __init__(self, to, cost):
            """
            :param to:  終点ノード
            :param cost: 辺の重み
            """
            self.to, self.cost = to, cost

    def __init__(self, n, directed=False, decrement=True, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.edges2 = []                            # ワーシャルフロイド用
        for x, y, cost in edges:
            self.add_edge(x, y, cost)

    def add_edge(self, x, y, cost):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges2.append((x, y, cost))
        if self.directed == False:
            self.edges2.append((y, x, cost))     # ワーシャルフロイド用

    def warshall_folyd(self, INF=1<<30):
        """
        :param INF: INF = 10**18 にすると、負のコストがある場合に少し面倒になる
        :return: 頂点 i, j 間の距離を行列として返す
        """
        dist = [[INF] * self.n for _ in range(self.n)]

        for i, j, cost in self.edges2:
            dist[i][j] = cost
        for i in range(self.n):
            dist[i][i] = 0  # 自身のところに行くコストは０

        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        return dist

    def warshall_folyd2(self, INF=1<<30):
        """
        :param INF: INF = 10**18 にすると、負のコストがある場合に少し面倒になる
        :return: 頂点 i, j 間の距離を行列として返す
        """
        dist = [[INF] * self.n for _ in range(self.n)]

        for i, j, cost in self.edges2:
            dist[i][j] = cost
            if dist[i][j] <= L:
                data.append((i, j))
        for i in range(self.n):
            dist[i][i] = 0

        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
                        if dist[i][j] <= L:
                            data.append((i, j))
        return dist

def max2(x,y):
    return x if x > y else y

from itertools import combinations

N, M, L = map(int, input().split())
graph = Graph(N, directed=False, decrement=True)
for _ in range(M):
    x, y, cost = map(int, input().split())
    graph.add_edge(x, y, cost)

data = []
d = graph.warshall_folyd2()

graph2 = Graph(N, directed=False, decrement=False)
for i, j in combinations(range(N), 2):
    if d[i][j] <= L:
        graph2.add_edge(i, j, 1)


d = graph2.warshall_folyd()

for _ in range(int(input())):
    s, t, = map(int, input().split())
    s, t = s-1, t-1
    print(d[s][t]-1 if d[s][t] < 1<<20 else -1)

Submission status: Accepted

Solution code:
class Graph:
    class Edge:
        def __init__(self, to, cost):
            """
            :param to:  終点ノード
            :param cost: 辺の重み
            """
            self.to, self.cost = to, cost

    def __init__(self, n, directed=False, decrement=True, edges=[]):
        self.n = n
        self.directed = directed
        self.decrement = decrement
        self.edges = [[] for _ in range(self.n)]
        self.edges2 = []                            # ワーシャルフロイド用
        self.parent = [-1]*self.n
        self.info = [-1]*self.n
        for x, y, cost in edges:
            self.add_edge(x, y, cost)

    def add_edge(self, x, y, cost):
        if self.decrement:
            x -= 1
            y -= 1
        self.edges[x].append(self.Edge(y, cost))
        self.edges2.append((x, y, cost))
        if self.directed == False:
            self.edges[y].append(self.Edge(x, cost))
            self.edges2.append((y, x, cost))     # ワーシャルフロイド用

    def warshall_folyd(self, INF=1<<30):
        """
        :param INF: INF = 10**18 にすると、負のコストがある場合に少し面倒になる
        :return: 頂点 i, j 間の距離を行列として返す
        """
        dist = [[INF] * self.n for _ in range(self.n)]

        for i, j, cost in self.edges2:
            dist[i][j] = cost
        for i in range(self.n):
            dist[i][i] = 0  # 自身のところに行くコストは０

        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        return dist

    def warshall_folyd2(self, INF=1<<30):
        """
        :param INF: INF = 10**18 にすると、負のコストがある場合に少し面倒になる
        :return: 頂点 i, j 間の距離を行列として返す
        """
        dist = [[INF] * self.n for _ in range(self.n)]

        for i, j, cost in self.edges2:
            dist[i][j] = cost
            if dist[i][j] <= L:
                data.append((i, j))
        for i in range(self.n):
            dist[i][i] = 0

        for k in range(self.n):
            for i in range(self.n):
                for j in range(self.n):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
                        if dist[i][j] <= L:
                            data.append((i, j))
        return dist

def max2(x,y):
    return x if x > y else y

from itertools import combinations

N, M, L = map(int, input().split())
graph = Graph(N, directed=False, decrement=True)
for _ in range(M):
    x, y, cost = map(int, input().split())
    graph.add_edge(x, y, cost)

data = []
d = graph.warshall_folyd2()

graph2 = Graph(N, directed=False, decrement=False)
for i, j in combinations(range(N), 2):
    if d[i][j] <= L:
        graph2.add_edge(i, j, 1)


d = graph2.warshall_folyd()

for _ in range(int(input())):
    s, t, = map(int, input().split())
    s, t = s-1, t-1
    print(d[s][t]-1 if d[s][t] < 1<<20 else -1)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,m,l = list(map(int, input().split()))
from collections import defaultdict
ns = defaultdict(set)
for i in range(m):
    a,b,c = map(int, input().split())
    a-=1
    b-=1
    if c<=l:
        ns[a].add((c,b))
        ns[b].add((c,a))

def wf(ns):
    """全頂点間距離
    """
    d = [[float("inf")]*n for _ in range(n)]
    for i in range(n):
        for t,j in ns[i]:
            d[i][j] = t
        d[i][i] = 0
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])
    return d
dist = wf(ns)
ns2 = defaultdict(set)
for i in range(n):
    for j in range(i+1,n):
        if dist[i][j]<=l:
            ns2[i].add((1,j))
            ns2[j].add((1,i))
ddist = wf(ns2)
q = int(input())
ans = [None]*q
for i in range(q):
    s,t = map(int, input().split())
    s-=1
    t-=1
    if dist[s][t]==float("inf"):
        ans[i] = -1
    else:
        ans[i] = ddist[s][t] - 1
write("\n".join(map(str, ans)))

Submission status: Accepted

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

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

start = []
goal = []
cost = []
for _ in range(M):
    A, B, C = map(int, input().split())
    A -= 1
    B -= 1
    start.append(A)
    goal.append(B)
    cost.append(C)
    start.append(B)
    goal.append(A)
    cost.append(C)

graph = csr_matrix((cost, (start, goal)), shape = (N, N))
can_reach_with_L = floyd_warshall(graph, directed = False)
can_reach_with_L[can_reach_with_L > L] = 0
ans = floyd_warshall(can_reach_with_L, directed = False, unweighted = True)

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

Submission status: Accepted

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

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

start = []
goal = []
cost = []
for _ in range(M):
    A, B, C = map(int, input().split())
    A -= 1
    B -= 1
    start.append(A)
    goal.append(B)
    cost.append(C)
    start.append(B)
    goal.append(A)
    cost.append(C)

graph = csr_matrix((cost, (start, goal)), shape = (N, N))
can_reach_with_L = dijkstra(graph, directed = False, limit = L)
ans = dijkstra(can_reach_with_L, directed = False, unweighted = True)

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

Submission status: Accepted

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def read_into(*A):
    for a, v in zip(A, read_ints()):
        a.append(v)


def solve():
    N, M, L = read_ints()
    dist = [
        [math.inf for _ in range(N)] for _ in range(N)
    ]
    for i in range(N):
        dist[i][i] = 0
    for _ in range(M):
        a, b, c = read_ints()
        dist[a-1][b-1] = dist[b-1][a-1] = c
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = dist[j][i] = min(dist[i][j], dist[i][k]+dist[k][j])
    for i in range(N):
        for j in range(N):
            if i == j: continue
            dist[i][j] = 1 if dist[i][j] <= L else math.inf
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = dist[j][i] = min(dist[i][j], dist[i][k]+dist[k][j])
    Q = read_int()
    for _ in range(Q):
        s, t = read_ints()
        if dist[s-1][t-1] == math.inf:
            print(-1)
        else:
            print(dist[s-1][t-1]-1)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
from numpy import where
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)]
t=[[float("inf")]*n for _ in range(n)]
for a,b,c in abc:
 if c<=l:t[a-1][b-1]=c
f=floyd_warshall(t,0)
l=floyd_warshall(where(f<=l,1,f),0)
for s, t in st:print(-1if l[s-1,t-1]==float("inf")else int(l[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)]

"""
g=[[] for _ in range(n)]
for a,b,c in abc:
  if c>l:continue
  a,b=a-1,b-1
  g[a].append([b,c])
  g[b].append([a,c])
"""
q=int(input())
st=[list(map(int,input().split())) for _ in range(q)]

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
inf=float('inf')
d=[[inf]*n for _ in range(n)]

for a,b,c in abc:
  a,b=a-1,b-1
  d[a][b]=c
  d[b][a]=c
for i in range(n):
  d[i][i]=0
d=warshall_floyd(d)
nabc=[]
dd=[[inf]*n for _ in range(n)]
#g=[[] for _ in range(n)]
for i in range(n):
  for j in range(n):
    if d[i][j]<=l:
      dd[i][j]=1
for i in range(n):
  dd[i][i]=0
dd=warshall_floyd(dd)
for s,t in st:
  s,t=s-1,t-1
  tmp=dd[s][t]
  print(max(0,tmp-1) if tmp!=inf else -1)
#print(dd)

Submission status: Accepted

Solution code:
n,m,l=map(int,input().split())
inf=100000000000
wf=[[inf]*n for i in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    wf[a-1][b-1]=c
    wf[b-1][a-1]=c
for i in range(n):
    wf[i][i]=0
for k in range(n):
    for i in range(n):
        for j in range(n):
            wf[i][j]=min(wf[i][j],wf[i][k]+wf[k][j])
for i in range(n):
    for j in range(n):
        if i!=j:
            wf[i][j]=1 if wf[i][j]<=l else inf
for k in range(n):
    for i in range(n):
        for j in range(n):
            wf[i][j]=min(wf[i][j],wf[i][k]+wf[k][j])
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    x=wf[s-1][t-1]
    print(-1 if x==inf else wf[s-1][t-1]-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, M, L = map(int, input().split())
d = [[10 ** 16 * (i != j) for j in range(N + 1)] for i in range(N + 1)]
for _ in range(M):
  x, y, c = map(int, input().split())
  d[x][y] = c
  d[y][x] = c
for k in range(N + 1):
  for i in range(N + 1):
    for j in range(N + 1): d[i][j] = min(d[i][j], d[i][k] + d[k][j])

dd = [[(d[i][j] <= L) + (d[i][j] > L) * 10 ** 16 for j in range(N + 1)] for i in range(N + 1)]
for k in range(N + 1):
  for i in range(N + 1):
    for j in range(N + 1): dd[i][j] = min(dd[i][j], dd[i][k] + dd[k][j])

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

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense, shortest_path


def main():
    import heapq
    import sys
    input = sys.stdin.buffer.readline
    N, M, L = map(int, input().split())

    G = [[-1]*N for i in range(N)]

    for i in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        G[A][B] = C
        G[B][A] = C
    g = csgraph_from_dense(G, null_value=-1)
    D = shortest_path(g)
    G2 = [[-1]*N for i in range(N)]
    for i in range(N):
        for j in range(N):
            if D[i][j] >= 0 and D[i][j] <= L:
                G2[i][j] = 1

    g2 = csgraph_from_dense(G2, null_value=-1)
    D = shortest_path(g2)

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


main()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra


def main():
    import heapq
    import sys
    input = sys.stdin.buffer.readline
    N, M, L = map(int, input().split())

    G = [[-1]*N for i in range(N)]

    for i in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        G[A][B] = C
        G[B][A] = C
    g = csgraph_from_dense(G, null_value=-1)
    D = dijkstra(g)
    G2 = [[-1]*N for i in range(N)]
    for i in range(N):
        for j in range(N):
            if D[i][j] >= 0 and D[i][j] <= L:
                G2[i][j] = 1

    g2 = csgraph_from_dense(G2, null_value=-1)
    D = dijkstra(g2)


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


main()

Submission status: Accepted

Solution code:
#import numpy as np
from scipy.sparse.csgraph import floyd_warshall, csgraph_from_dense
from scipy.sparse import csr_matrix

N,M,L = map(int, input().split())
V = [[ 10**12 for _ in range(N) ] for _ in range(N)]
for _ in range(M):
  a,b,c = map(int, input().split())
  a,b = a-1, b-1
  V[a][b] = c
  V[b][a] = c
  
G = csgraph_from_dense(V, null_value=10**12)
d = floyd_warshall(G)

V2 = [[ 10**9 for _ in range(N) ] for _ in range(N)]
for i in range(N):
  for j in range(N):
    if 0 < d[i][j] <= L:
      V2[i][j] = 1
      
G2 = csgraph_from_dense(V2, null_value=10**9)
d2 = floyd_warshall(G2)

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

Submission status: Accepted

Solution code:
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N,M,L = LI()

class WarshallFloyd():
    def __init__(self,N):  # Nは頂点の個数
        self.N = N
        self.d = [[float('inf')]*N for _ in range(N)]  # d[i][j] = iからjへの最短距離,0-indexed
    def add(self,u,v,c,directed = False):
        if directed is False:  # 無向グラフの場合
            self.d[u][v] = c
            self.d[v][u] = c
        else:  # 有向グラフの場合
            self.d[u][v] = c
    def WarshallFloyd_search(self):
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    self.d[i][j] = min(self.d[i][j],self.d[i][k] + self.d[k][j])
        for i in range(self.N):
            self.d[i][i] = 0
        return self.d

G1 = WarshallFloyd(N)

for i in range(M):
    a,b,c = LI()
    G1.add(a-1,b-1,c,directed=False)

G1.WarshallFloyd_search()

G2 = WarshallFloyd(N)

for i in range(N-1):
    for j in range(i+1,N):
        if G1.d[i][j] <= L:
            G2.add(i,j,1,directed=False)

G2.WarshallFloyd_search()

Q = I()
for i in range(Q):
    s,t = LI()
    if G2.d[s-1][t-1] == float('inf'):
        print(-1)
    else:
        print(G2.d[s-1][t-1]-1)

Submission status: Accepted

Solution code:
INF = 10**12

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


def main():

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

    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

    warshall_floyd(d2,n)
    ans = []
    q = int(input())
    for _ in range(q):
        s,t = map(int, input().split())
        dist = d2[s-1][t-1]
        if dist == INF: dist = 0
        ans.append(dist-1)

    for a in ans:
        print(a)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict
    n, m, l = map(int, readline().split())
    dist = [[INF] * n for _ in range(n)]

    for _ in range(m):
        a, b, c = map(int, readline().split())
        a, b = 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])

    dist2 = [[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

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

    q = int(readline())

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
inf = float("inf")

import numpy as np
import scipy.sparse.csgraph as csg

def main():
    N,M,L = map(int,input().split())
    ABC = [tuple(map(int,input().split())) for _ in range(M)]
    Q = int(input())
    ST = [tuple(map(int,input().split())) for _ in range(Q)]

    # 町の最短距離を求める
    A = np.array([[inf]*N]*N)
    for a,b,c in ABC:
        A[a-1][b-1] = c
        A[b-1][a-1] = c
    A = csg.floyd_warshall(A)
    
    # 求めた町の距離が L以下 に 1の辺をはる (給油なしでたどり着ける)
    B = np.array([[inf]*N]*N)
    for i in range(N):
        for j in range(N):
            if A[i][j] <= L:
                B[i][j] = 1
    # 最短距離を求める
    B = csg.floyd_warshall(B)
    
    for s,t in ST:
        if B[s-1][t-1] == inf:
            print(-1)
        else:
            print(int(B[s-1][t-1] - 1))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
I=sys.stdin.readlines()
N,M,L=map(int,I[0].split())
a,b,c=0,0,0
D=[[L+1]*N for i in range(N)]
for i in range(M):
  a,b,c=map(int,I[i+1].split())
  a,b=a-1,b-1
  D[a][b]=c
  D[b][a]=c
for i in range(N):
  D[i][i]=0
for k in range(N):
  for i in range(N):
    for j in range(N):
      D[i][j]=min(D[i][j],D[i][k]+D[k][j])
D2=[[N*N+2]*N for i in range(N)]
for i in range(N):
  D2[i][i]=0
  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(N):
      D2[i][j]=min(D2[i][j],D2[i][k]+D2[k][j])
Q=int(I[M+1])
for i in range(Q):
  a,b=map(int,I[i+2+M].split())
  if N<D2[a-1][b-1]:
    print(-1)
  else:
    print(D2[a-1][b-1]-1)

Submission status: Accepted

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

inf = 10 ** 9 + 7
graph = [[inf] * N for _ in range(N)]
count = [[inf] * N for _ in range(N)]

for i in range(N):
    graph[i][i] = 0
    count[i][i] = 0
    
for a, b, c in X:
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c

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

for i in range(N):
    for j in range(N):
        if i != j and graph[i][j] <= L:
            count[i][j] = 1

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

for s, t in Y:
    if count[s - 1][t - 1] == inf:
        print(-1)
    else:
        print(count[s - 1][t - 1] - 1)

Submission status: Accepted

Solution code:
N,M,L=map(int,input().split())
A=[[] for i in range(N)]
for i in range(M):
    a,b,c=map(int,input().split())
    A[a-1].append((b-1,c))
    A[b-1].append((a-1,c))
d=[[100000000001]*N for i in range(N)]
for i in range(N):
    d[i][i]=0
for i in range(N):
    for to,cost in A[i]:
        d[i][to] = cost
for k in range(N):
    for i in range(N):
        for j in range(N):
            if d[i][k] != 100000000001 and d[k][j] != 100000000001:
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
B=[[] for i in range(N)]
for i in range(N):
    for j in range(N):
        if d[i][j]<=L:
            B[i].append((j,1))
times=[[100000000001]*N for i in range(N)]
for i in range(N):
    times[i][i]=0
for i in range(N):
    for to,cost in B[i]:
        times[i][to] = cost
for k in range(N):
    for i in range(N):
        for j in range(N):
            if times[i][k] != 100000000001 and times[k][j] != 100000000001:
                times[i][j] = min(times[i][j], times[i][k] + times[k][j])
Q=int(input())
for i in range(Q):
    s,t=map(int,input().split())
    if times[s-1][t-1]!=100000000001:
    	print(times[s-1][t-1]-1)
    else:
      	print(-1)

Submission status: Accepted

Solution code:
def main():
    INF = 10 ** 12
    N, M, L = list(map(int, input().split(' ')))
    D = [[INF for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        A, B, C = list(map(int, input().split(' ')))
        A -= 1
        B -= 1
        D[A][B] = C
        D[B][A] = C
    Q = int(input())
    query_list = [list(map(lambda x: int(x) - 1, input().split(' '))) for _ in range(Q)]
    # calc min cost by warshall-floyd method
    for via in range(N):
        for s in range(N):
            for t in range(N):
                d = D[s][via] + D[via][t]
                if D[s][t] > d:
                    D[s][t] = d
                    D[t][s] = d
    # calc min number of charges
    counts = [[INF for _ in range(N)] for _ in range(N)]
    for s in range(N):
        for t in range(N):
            if D[s][t] <= L:
                counts[s][t] = 1
                counts[t][s] = 1
    for via in range(N):
        for s in range(N):
            for t in range(N):
                d = counts[s][via] + counts[via][t]
                if counts[s][t] > d:
                    counts[s][t] = d
                    counts[t][s] = d
    # answer query
    for query in query_list:
        s, t = query
        if counts[s][t] >= INF:
            print(-1)
        else:
            print(counts[s][t] - 1)


if __name__ == '__main__':
    main()