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: Runtime Error

Solution code:

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = defaultdict(dict)
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v))
    V = set(V)
    for i in V:
        for j in V:
            if i in g and j in g[i]:
                d[i][j] = g[i][j]
            else:
                d[i][j] = sys.maxsize
    for k in g:
        for i in g:
            for j in g:
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d

@mt
def slv(N, M, L, ABC, Q, ST):

    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = c
        g[b][a] = c
    
    d = warshall_floyd(g)
    gg = defaultdict(dict)
    for u in range(1, N+1):
        for v in range(1, N+1):
            if d[u][v] <= L:
                gg[u][v] = 1
    dd = warshall_floyd(gg)

    for s, t in ST:
        if s in dd and t in dd[s]:
            print(dd[s][t]-1)
        else:
            print(-1)



def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]
    (slv(N, M, L, ABC, Q, ST))

    N = 300
    M = (N*(N-1))//2
    L = random.randint(1, 10**9)
    ABC = []
    for i in range(1, N+1):
        for j in range(i+1, N+1):
            ABC.append([i, j, random.randint(1, 10**9)])
    
    ST = []
    for i in range(1, N+1):
        for j in range(1, N+1):
            if i == j:
                continue
            ST.append([i, j])
    Q = len(ST)
    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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


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

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

            else:
                continue
    return reachable


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

for i in range(n):
    L_edges[i] = dijkstra(n, edges, i, full)

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

for start in range(n):
    dist[start][start] = 0
    todo = deque([])
    todo.append([-1, start])

    while todo:
        d, node = todo.popleft()

        for new_node in L_edges[node]:
            if dist[start][new_node] > d + 1:
                dist[start][new_node] = d + 1
                todo.append([d+1, new_node])

            else:
                continue

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

Submission status: Runtime Error

Solution code:
n, m, l = [int(x) for x in input().split()]
ws      = [None]
ds      = [None]

for i in range(1, n + 1):
	ws.append([None] * (n + 1))
	ds.append([None] * (n + 1))
	
 
for i in range(0, m):
	x, y, z  = [int(a) for a in input().split()]
	ws[x][y] = z
	ws[y][x] = z
	ds[x][y] = z
	ds[y][x] = z
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		if ds[i][k] is None:
			continue
		for j in range(1, n + 1):
			if ds[k][j] is None:
				continue
			if ds[i][j] is None or ds[i][k] + ds[k][j] < ds[i][j]:
				ds[i][j] = ds[i][k] + ds[k][j]

for i in range(1, n + 1):
	for j in range(1, n + 1):
		if ds[i][j] <= l:
			ds[i][j] = 1
		else:
			ds[i][j] = None
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		if ds[i][k] is None:
			continue
		for j in range(1, n + 1):
			if ds[k][j] is None:
				continue
			if ds[i][j] is None or ds[i][k] + ds[k][j] < ds[i][j]:
				ds[i][j] = ds[i][k] + ds[k][j]
 
q = int(input())
 
for _ in range(0, q):
	s, t = [int(x) for x in input().split()]
	d    = ds[s][t]
	
	print(d - 1 if d < n else -1)

Submission status: Runtime Error

Solution code:
import sys

imput = sys.stdin.readline
N,M,L = map(int,input().split())
road = [[float('inf')]*N for i in range(N)]
for i in range(N):
    road[i][i] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    road[a-1][b-1] = c

for i in range(N):
    for j in range(N):
        for k in range(N):
            road[i][j] = min(road[i][j],road[i][k]+road[k][j])
ans = [[float("inf")]*N for i in range(N)]
for i in range(N):
    ans[i][i] = 0
for i in range(N):
    for j in range(N):
        if road[i][j] <= L:
            ans[i][j] = 1
for i in range(N):
    for j in range(N):
        for k in range(N):
            ans[i][j] = min(ans[i][j],ans[i][k]+ans[k][j])
for i in range(int(input()):
    a,b = map(int,input().split())
    o = ans[a-1][b-1]
    if o == float('inf'):
        print(-1)
    else:
        print(o-1)

Submission status: Runtime Error

Solution code:
n, m, l = [int(x) for x in input().split()]
ws      = [None]
ds      = [None]
ps      = [None]

for i in range(1, n + 1):
	ws.append([10 ** 20] * (n + 1))
	ds.append([10 ** 20] * (n + 1))
	ps.append([None]     * (n + 1))
	
 
for i in range(0, m):
	x, y, z  = [int(a) for a in input().split()]
	ws[x][y] = z
	ws[y][x] = z
	ds[x][y] = z
	ds[y][x] = z
	ps[x][y] = [x, y]
	ps[y][x] = [y, x]
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		for j in range(1, n + 1):
			if ds[i][k] + ds[k][j] < ds[i][j]:
				ds[i][j] = ds[i][k] + ds[k][j]
				ps[i][j] = ps[i][k] + ps[k][j][1:]
 
q = int(input())
 
for _ in range(0, q):
	s, t = [int(x) for x in input().split()]
	p    = ps[s][t]
	e    = l
	c    = 0
	f    = True
	
	for j in range(1, len(p)):
		d = ds[p[j - 1]][p[j]]
		
		if l < d:
			f = False
			break
		elif e < d:
			e  = l
			c += 1
		
		e -= d
		
	print(c if f else -1)

Submission status: Runtime Error

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(E):
    N = len(E)
    dist = [[INF for _ in range(N)] for _ in range(N)]
    for v in V:
        dist[v][v] = 0
        for u, c in E[v]: dist[v][u] = c
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

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

E_charge = [[] for _ in V]
for u, v in combinations(V, 2):
    if dist[u][v] <= L:
        E_charge[u].append((v, 1))
        E_charge[v].append((u, 1))
charge = floyd_warshall(E_charge)

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

Submission status: Runtime Error

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(E):
    N = len(E)
    dist = [[INF for _ in range(N)] for _ in range(N)]
    for v in V:
        dist[v][v] = 0
        for u, c in E[v]: dist[v][u] = c
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

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

E_charge = [[] for _ in V]
for u, v in combinations(V, 2):
    if dist[u][v] <= L:
        E_charge[u].append((v, 1))
        E_charge[v].append((u, 1))
charge = floyd_warshall(V, E_charge)

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

Submission status: Runtime Error

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(V, E):
    dist = {u: {v: INF for v in V} for u in V}
    for v in V:
        dist[v][v] = 0
        for u, c in E[v]: dist[v][u] = c
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

N, M, L = map(int, input().split())
V = list(range(N))
E = [[] for _ in V]
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((b-1, c))
    E[b-1].append((a-1, c))

dist = floyd_warshall(V, E)
E_charge = [[] for _ in V]
for u, v in combinations(V, 2):
    if dist[u][v] <= L: E_charge[u][v] = 1; E_charge[v][u] = 1;
charge = floyd_warshall(V, E_charge)

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

Submission status: Runtime Error

Solution code:
import numpy as np
N, M, L = map(int, input().split())
l = [list(map(int, input().split())) for _ in range(M)]
l = np.array(l)
a = l[:, 0]
b = l[:, 1]
c = l[:, 2]

Q = int(input())
s = [sorted(list(map(int, input().split()))) for _ in range(Q)]

for i in range(Q):
    start = np.where(a == s[i][0])
    end = np.where(b == s[i][1])
    if start == end:
        print(int(c[start]) // L)
        continue
    print(c[start], c[end])
    ans = np.sum(c[int(c[start]):int(c[end])])
    print(ans)

Submission status: Runtime Error

Solution code:
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

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

n, w = N, M
d = [[float("inf") for i in range(n)] for i in range(n)] 

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

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

D = warshall_floyd(d)

Q = int(input())
for i in range(Q):
    s,t = tuple(map(int, input().split()))
    print(D[s][t])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 19 22:03:54 2019
ABC143E
@author: maezawa
"""

class WarshallFloyd():
    def __init__(self, N):
        self.N = N
        self.d = [[float("inf") for i in range(N)]
                  for i in range(N)]  # d[u][v] : 辺uvのコスト(存在しないときは'inf')

    def add(self, u, v, c, directed=False):
        """
        0-indexedであることに注意
        u = from, v = to, c = cost
        directed = Trueなら、有向グラフである
        """
        if directed:
            self.d[u][v] = c
        else:
            self.d[u][v] = c
            self.d[v][u] = c

    def WarshallFloyd_search(self):
        # これを d[i][j]: iからjへの最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行ける
        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
    

# 使い方の例
        
n, m, l = list(map(int, input().split()))    
    
num_v = n        
graph = WarshallFloyd(num_v)
num_edges = m

data = []
for _ in range(m):
    ai, bi, ci = list(map(int, input().split()))
    if ci >= l:
        continue
    data.append([ai-1, bi-1, ci])
#data = [[0, 1, 2],
#        [0, 2, 3],
#        [1, 2, 5],
#        [1, 3, 1],    
#        [2, 3, 2]] # [v_from, v_to, weight]
for i in range(num_edges):
    graph.add(data[i][0], data[i][1], data[i][2], directed=False)

result = graph.WarshallFloyd_search()

graph2 = WarshallFloyd(num_v)

for i in range(num_v-1):
    for j in range(i+1,num_v):
        if result[i][j] <= l:
            graph2.add(i, j, 1, directed=False)

result2 = graph2.WarshallFloyd_search()

q = int(input())
for _ in range(q):
    si, ti = list(map(int,input().split()))
    res = result2[si-1][ti-1]
    if res == float("inf"):
        print(-1)
    else:
        print(res-1)

Submission status: Runtime Error

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


def WF(mat, N):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                mat[i][j] = min(mat[i][j], mat[i][k]+mat[k][j])
    return mat


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

roads = WF(roads)
for i in range(N):
    for j in range(i+1, N):
        if roads[i][j] <= L:
            kyuyu[i][j] = 1
            kyuyu[j][i] = 1
kyuyu = WF(kyuyu)
Q = int(input())
for _ in range(Q):
    s, t = map(lambda x: int(x)-1, input().split())
    dist = kyuyu[s][t]
    if dist == float('inf'):
        print(-1)
    else:
        print(dist-1)

Submission status: Runtime Error

Solution code:
from scipy.sparse.csgraph import floyd_warshall as fw
INF = float('inf')
N,M,L = map(int,input().split())
cost = [[INF]*N for _ 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 = [[0,1,2],[INF,0,2],[INF,INF,1]]

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

cost = fw(cost)

for i in range(N):
    for j in range(N):
        if cost[i][j] == INF:
            cost[i][j] = -1
        else:
            cost[i][j] -= 1

Q = int(input())

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

Submission status: Runtime Error

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

N,M,L=map(int, input().split())
graph=np.zeros((N,N),int)
g=np.zeros((N,N),int)
for _ in range(M):
    A,B,C=map(int, input().split())
    if C<=L:
      graph[A-1,B-1]=C
      graph[B-1,A-1]=C
        
graph = csr_matrix(graph)
dist_matrix, predecessors = dijkstra(csgraph=graph, directed=False, return_predecessors=True)
g[dist_matrix<=L]=1
graph=csr_matrix(g)
dist_matrix, predecessors = dijkstra(csgraph=graph, directed=False, return_predecessors=True)

Q=int(input())
for _ in range(Q):
  S,T=map(int, input().split()) 
  
  l=dist_matrix[S-1,T-1]

  print(int(l-1))

Submission status: Runtime Error

Solution code:
#何とか法, AOJのgrl1c
#初め満杯
import sys
input = sys.stdin.readline
#print = sys.stdout.write

n,m,l =map(int, input().split( ))
Edge = [[] for _ in range(n)]

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

dp = [[10**10 for _ in range(n)] for __ in range(n)]

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

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

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

"""
以下が要点
"""
dp2 = [[10**8 for _ in range(n)] for __ in range(n)]
for j in range(n):
    for i in range(j+1):###
        if dp[i][j] <=l:
            dp2[i][j] = 1
            dp2[j][i] = 1
for k in range(n):
    for j in range(n):
        for i in range(n):
            dp[i][j] = min(dp[i][j],dp[i][k] + dp[k][j])
"""
以上
"""
q = int(input())
ans = []
for i in range(q):
    s,t = map(int, input().split( ))
    if dp[s-1][t-1] >10**10:###
        print(-1)
    else:
        print(dp[s-1][t-1][0])
#print(dp)
#print(*ans)

Submission status: Runtime Error

Solution code:
import heapq as hq
import sys
input = sys.stdin.readline


def f():
    N, M, L = map(int, input().split())
    out_link = {i: set() for i in range(N)}
    min_length = {(i, j): -1 for i in range(N) for j in range(N)}


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


    def should_supply(now_cost, next_cost):
        if now_cost % L == 0:
            return False

        return (now_cost - 1) // L != (next_cost - 1) // L


    def search(S):
        for 



    calced_s = set()
    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if s not in calced_s:
            search(s)
            calced_s.add(s)
        res = min_length[(s, t)]
        print(res)

if __name__ == '__main__':
   f()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from itertools import accumulate
INF = float("inf")

# 無向グラフを仮定する。


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = [[] for _ in range(N)]

    def add_edge(self, s, t, w=1):
        self.E[s].append((t, w))
        self.E[t].append((s, w))


@functools.lru_cache(maxsize=None)
def shortestPath(g: Graph, s: int, L: int):

    charge = [INF]*g.N
    charge[s] = 0

    rest = [INF]*g.N            # 現在の走行距離
    rest[s] = 0

    Q = []
    heapq.heappush(Q, s)

    while len(Q) > 0:
        u = heapq.heappop(Q)
        for v, w in g.E[u]:
            if rest[u]+w > L:
                c, r = (charge[u]+1, w)
            else:
                c, r = (charge[u], rest[u]+w)
            if charge[v] > c or (charge[v] == c and rest[v] > r):
                rest[v] = r
                charge[v] = c
                heapq.heappush(Q, v)

    return charge, rest


def solve(N: int,
          M: int,
          L: int,
          A: "List[int]",
          B: "List[int]",
          C: "List[int]",
          Q: int,
          s: "List[int]",
          t: "List[int]"):
    g = Graph(N)
    for i in range(M):
        if C[i] <= L:
            g.add_edge(A[i]-1, B[i]-1, C[i])

    for i in range(Q):
        charge, rest = shortestPath(g, s[i]-1, L)
        if charge[t[i]-1] == INF:
            print(-1)
        else:
            print(charge[t[i]-1])

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    L = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    Q = int(next(tokens))  # type: int
    s = [int()] * (Q)  # type: "List[int]"
    t = [int()] * (Q)  # type: "List[int]"
    for i in range(Q):
        s[i] = int(next(tokens))
        t[i] = int(next(tokens))
    solve(N, M, L, A, B, C, Q, s, t)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

inf = float('INF')


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

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

p_route = di(route)
for i in range(n):
    for j in range(n):
        if p_route[i][j] == inf:
            continue
        elif p_route[i][j] <= l:
            p_route[i][j] = 1
p_route = di(p_route)

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

Submission status: Runtime Error

Solution code:
N,M,L = map(int, input().split())
A = [0]*M
B = [0]*M
C = [0]*M
for i in range(M):
    A[i], B[i], C[i] = map(int, input().split())
    
Q = int(input())
qlist = [[int(q) for q in input().split()] for _ in range(Q)]

INF = 10**15
G = [[INF for _ in range(N+1)] for _ in range(N+1)]
for i in range(M):
    if C[i] <= L:
        G[A[i]][B[i]] = C[i]
        G[B[i]][A[i]] = C[i]
        

        
def dijkstra(s,t,n,w,cost,L):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [INF] * n
    used = [False] * n
    d[s] = 0
    c = [INF]*n
    c[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and c[i] < c[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
            t = c[v]+((d[v]-c[v]*L)+cost[v+1][j+1])
            if (c[v]+((d[v]-c[v]*L)+cost[v+1][j+1]))%L == 0:
                f = t//L -1
            c[j] = min(c[j], min(c[v]+((d[v]-c[v]*L)+cost[v+1][j+1])//L,f))
            if c[j] > min(c[v]+((d[v]-c[v]*L)+cost[v+1][j+1])//L,f):
                d[j] = d[v] + cost[v+1][j+1]
            elif c[j] == min(c[v]+((d[v]-c[v]*L)+cost[v+1][j+1])//L,f):
                d[j] = min(d[j], d[v] + cost[v+1][j+1])
    print(c)
    return c[t]


for i in range(Q):
    ans = dijkstra(qlist[i][0]-1,qlist[i][1]-1,N,M,G,L)
    if ans == INF:
        print(-1)
    else:
        print(ans)

Submission status: Runtime Error

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

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

for k in range(N):
    for i in range(N):
        for j in range(N):
            if dist[i][k] == INF or dist[k][j] == INF: continue
            a,x = divmod(dist[i][k],L)
            b,y = divmod(dist[k][j],L)
            if x+y > L:
                dist[i][j] = min(dist[i][j], (a+b+1)*L + min(x,y))
            else:
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
            print(i,j,dist[i][j])

ans = []
for s,t in ST:
    s,t = s-1,t-1
    if (s,t) in st:
        ans.append(0)
    elif dist[s][t] == INF:
        ans.append(-1)
    else:
        ans.append(dist[s][t])//L))
print(*ans, sep='\n')

Submission status: Runtime Error

Solution code:
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d

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

n, w = N, M
d = [[float("inf") for i in range(n)] for i in range(n)] 
cost = [[float("inf") for i in range(n)] for i in range(n)] 
#cost[u][v] : 辺uvのコスト(存在しないときはinf この場合は10**10)
for i in range(w):
    x,y,z = map(int,input().split())
    cost[x-1][y-1] = z
    cost[y-1][x-1] = z

Q = int(input())
for i in range(Q):
    s,t = tuple(map(int, input().split()))
    print(dijkstra(0,s,t,cost)//L)

Submission status: Runtime Error

Solution code:
N, M, L = map(int, input().split())
town = [[] for i in range(N+1)]
for i in range(M):
    A, B, C = map(int, input().split())
    town[A].append([B, C])
    town[B].append([A, C])
Q = int(input())
def check(a):
    if a >= 0:
        return 1
    else:
        return 0
def bfs(s, t, cnt, lngth, l):
    if s == t:
        return cnt
    else:
        l.append(s)
        ans = []
        for i in range(len(town[s])):
            if (town[s][i][0] not in l):
                ans.append(bfs(town[s][i][0], t, cnt + check(town[s][i][1] + lngth - L), (town[s][i][1] + lngth) % L, l))
        return min(ans)
for i in range(Q):
    s, t = map(int, input().split())
    print(bfs(s, t, 0, 0, []))

Submission status: Runtime Error

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


class Node(object):

  def __init__(self, idx):
    self.idx = idx
    self.fixed = False
    self.supply = 300
    self.remain = 0
    self.edges = []

  # def __str__(self):
  #  return (f'{self.idx}: {self.supply}/{self.remain} - ' +
  #          ','.join(f'{e.idx}({d})' for e, d in self.edges))


def main():
  n, m, tank = map(int, input().split())
  nodes = [Node(i) for i in range(n + 1)]

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

  results = [[None] * len(nodes) for _ in range(len(nodes) - 1)]

  for start in range(len(nodes) - 1):
    for n in nodes:
      n.fixed = False
      n.supply = 300
      n.remain = 0

    nodes[start].supply = 0
    nodes[start].remain = tank

    while True:
      node = min([n for n in nodes if not n.fixed], key=lambda n: (n.supply, -n.remain))
      node.fixed = True

      if node.idx == len(nodes) - 1:
        break

      for e, d in node.edges:
        if e.fixed or d > tank:
          continue

        if d > node.remain:
          remain = tank - d
          supply = node.supply + 1
        else:
          remain = node.remain - d
          supply = node.supply

        if e.supply > supply or e.remain < remain:
          e.supply = supply
          e.remain = remain

    for end in range(len(nodes)):
      results[start][end] = nodes[end].supply

  for _ in range(int(input)):
    start, end = map(int, input().split())
    print(results[start - 1][end - 1])


if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

def main():
	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)]

	neighbor = [[] for i in range(N)]
	for pi in P:
		if pi[2]<=L:
			neighbor[pi[0]-1].append((pi[1]-1,pi[2]))
			neighbor[pi[1]-1].append((pi[0]-1,pi[2]))

	fuellist = [0]*N
	n_append = nq.append
	def bfs(start, end):
		fuel = [[10000000,L+1] for i in range(N)]
		fuel[start][0] = 0
		fuel[start][1] = L
		queue = [start]
		while len(queue)>0:
			nq = []						# next target node
			for i in queue:				# target node
				oc, om = fuel[i]
				for j, d in neighbor[i]:	# next node
					if om<d:
						nc = oc+1
						nm = L-d
					else:
						nc = oc
						nm = om-d

					# print(i,j,nc,nm)

					if (nc<fuel[j][0]) or (nc==fuel[j][0] and nm>fuel[j][1]):
						fuel[j][0], fuel[j][1] = nc, nm
						n_append(j)

			queue = nq					# update target node

		ans = fuel[end][0]
		if fuel[end][0]==10000000: ans = -1

		fuellist[start] = fuel

		print(ans)

	for s, t in st:
		start, end = s-1, t-1
		if fuellist[start]==0:
			bfs(start,end)
		else:
			ans = fuellist[start][end][0]
			if ans==10000000: ans = -1
			print(ans)


if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
import numpy as np
n,m,l=list(map(int, input().split()))
X=np.zeros((n,3)) #X:roads
Y=np.zeros((q,2)) #Y:question
for i in range(m):
    X[i]=list(map(int, input().split()))
q=int(input())
for i in range(q):
    Y[i]=list(map(int, input().split()))

D=np.zeros((n,n)) #D:隣接行列
for i in range(m):
    D[X[i][0],X[i][1]]=X[i][2]
    D[X[i][1],X[i][0]]=X[i][2]
for i in range(q):
    start=Y[i][0] #s:start
    t=Y[i][1] #t:goal
    ans=0
    opt=np.zeros(n)-1
    going(start,l,opt,ans)
    printopt[j]
def going(s,F,opt,ans):
    for j in range(n):
        if s==start:
            ans=0
        if (D[s][j]!=0 and F>=D[s][j]):
            if opt[j]==-1 or ans<opt[j]:
                opt[j]=ans
                F=F-D[s][j]
        elif(D[s][j]!=0 and l>=D[s][j]):
            if opt[j]==-1 or ans<opt[j]:
                opt[j]=ans+1
                F=l-D[s][j]
        else:
            break;