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: Wrong Answer

Solution code:
# ABC143E - Travel by Car
def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    for i in range(N):  # intermediate point
        for j, c2 in enumerate(dist[j][i] for j in range(N)):  #  source
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  # target
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3
    return dist

def main():
    # FW -> once more FW to edges <= L
    global N
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    INF = float("inf")
    dist = [[INF] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        dist[i][i] = 0
    for v, u, cost in zip(*[iter(ABC)] * 3):
        dist[v][u] = dist[u][v] = cost
    dist = floyd_warshall(dist)

    # assume distance within L as 1 and compute the number of fueling
    modified_dist = [[1 if x <= L else INF for x in d] for d in dist]
    modified_dist = floyd_warshall(modified_dist)
    ans = [
        modified_dist[s][t] - 1 if modified_dist[s][t] != INF else -1
        for s, t in zip(*[iter(ST)] * 2)
    ]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# ABC143E - Travel by Car
def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    for i in range(N):  # intermediate point
        for j, c2 in enumerate(dist[j][i] for j in range(N)):  #  source
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  # target
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3
    return dist

def main():
    # FW -> once more FW to edges <= L
    global N
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    A, B, C, S, T = ABC[::3], ABC[1::3], ABC[2::3], ST[::2], ST[1::2]
    INF = 1 << 60
    dist = [[INF] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        dist[i][i] = 0
    for v, u, cost in zip(*[iter(ABC)] * 3):
        dist[v][u] = dist[u][v] = cost
    dist = floyd_warshall(dist)

    # assume distance within L as 1 and compute the number of fueling
    modified_dist = [[1 if x <= L else INF for x in d] for d in dist]
    modified_dist = floyd_warshall(modified_dist)
    ans = [
        modified_dist[s][t] - 1 if modified_dist[s][t] != INF else -1
        for s, t in zip(*[iter(ST)] * 2)
    ]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# ABC143E - Travel by Car
def floyd_warshall(dist):
    """
    Compute the shortest paths of all pairs and modify dist.
    """
    for i in range(N):  # intermediate point
        for j, c2 in enumerate(dist[j][i] for j in range(N)):  #  source
            for k, (c1, c3) in enumerate(zip(dist[j], dist[i])):  # target
                if c2 + c3 < c1:
                    dist[j][k] = c2 + c3


def main():
    # FW -> once more FW to edges <= L
    global N
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    A, B, C, S, T = ABC[::3], ABC[1::3], ABC[2::3], ST[::2], ST[1::2]
    INF = 1 << 60
    dist = [[INF] * (N + 1) for _ in range(N + 1)]
    for i in range(N + 1):
        dist[i][i] = 0
    for v, u, cost in zip(*[iter(ABC)] * 3):
        dist[v][u] = dist[u][v] = cost
    floyd_warshall(dist)

    # assume distance within L as 1 and compute the number of fueling
    modified_dist = [[1 if x <= L else INF for x in d] for d in dist]
    floyd_warshall(modified_dist)
    ans = [
        modified_dist[s][t] - 1 if modified_dist[s][t] != INF else -1
        for s, t in zip(*[iter(ST)] * 2)
    ]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n, m, l = [int(i) for i in input().split()]
street = [[int(i) for i in input().split()] for _ in range(m)]
_q = int(input())
question = [[int(i) for i in input().split()] for _ in range(_q)]

# https://ja.wikipedia.org/wiki/ワーシャル–フロイド法
distance = {}
for i in range(1, n + 1):
    for j in range(i + 1, n + 1):
        distance[(i, j)] = -1
for s in street:
    small = min(s[0], s[1])
    big = max(s[0], s[1])
    distance[(small, big)] = s[2]

def warshall_Floyd(distance, n):
    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            for k in range(i + 1, j):
                if distance[(i, k)] == -1 or distance[(k, j)] == -1:
                    continue
                if distance[(i, j)] == -1:
                    distance[(i, j)] = distance[(i, k)] + distance[(k, j)]
                else:
                    distance[(i, j)] = min(distance[(i, j)], (distance[(i, k)] + distance[(k, j)]))

warshall_Floyd(distance, n)
for k in distance:
    if distance[k] == -1:
        continue
    if distance[k] <= l:
        distance[k] = 1
    else:
        distance[k] = -1
warshall_Floyd(distance, n)

for q in question:
    small = min(q[0], q[1])
    big = max(q[0], q[1])
    ans = distance[(small, big)]
    if ans == -1:
        print(ans)
    else:
        print(ans - 1)

Submission status: Wrong Answer

Solution code:
# ABC143E - Travel by Car
import numpy as np

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


def main():
    # FW -> once more FW to edges <= L
    global L, G, dist, ancestors
    N, M, L, *X = map(int, open(0).read().split())
    ABC, ST = X[: 3 * M], X[3 * M + 1 :]
    A, B, C, S, T = ABC[::3], ABC[1::3], ABC[2::3], ST[::2], ST[1::2]
    
    G = csr_matrix((C, (A, B)), (N + 1, N + 1))
    dist = floyd_warshall(G, directed=0)
    
    modified_G = np.full((N + 1, N + 1), np.inf)
    np.fill_diagonal(modified_G, 0)
    modified_G[dist <= L] = 1
    modified_dist = floyd_warshall(modified_G, directed=0)
    ans = modified_dist[S, T] - 1
    print("\n".join(ans.astype(str)))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:

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

lis = [ [float("inf")] * N for i in range(N) ]

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    lis[A][B] = C
    lis[B][A] = C

for i in range(N):

    for j in range(i):

        for k in range(N):

            if lis[i][j] > lis[i][k] + lis[k][j]:

                lis[i][j] = lis[i][k] + lis[k][j]
                lis[j][i] = lis[i][k] + lis[k][j]

lis2 = [ [float("inf")] * N for i in range(N) ]

for i in range(N):

    for j in range(i):

        if lis[i][j] <= L:
            lis2[i][j] = 1
            lis2[j][i] = 1


for i in range(N):

    for j in range(i):

        for k in range(N):

            if lis2[i][j] > lis2[i][k] + lis2[k][j]:

                lis2[i][j] = lis2[i][k] + lis2[k][j]
                lis2[j][i] = lis2[i][k] + lis2[k][j]

Q = int(input())

for i in range(Q):

    s,t = map(int,input().split())
    s -= 1
    t -= 1

    if lis2[s][t] == float("inf"):
        print (-1)
    else:
        print (lis2[s][t]-1)

Submission status: Wrong Answer

Solution code:

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

lis = [ [float("inf")] * N for i in range(N) ]

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    lis[A][B] = C
    lis[B][A] = C

for i in range(N):

    for j in range(N):

        for k in range(N):

            if lis[i][j] > lis[i][k] + lis[k][j]:

                lis[i][j] = lis[i][k] + lis[k][j]
                lis[j][i] = lis[i][k] + lis[k][j]

lis2 = [ [float("inf")] * N for i in range(N) ]

for i in range(N):

    for j in range(i):

        if lis[i][j] <= L:
            lis2[i][j] = 1
            lis2[j][i] = 1


for i in range(N):

    for j in range(N):

        for k in range(N):

            if lis2[i][j] > lis2[i][k] + lis2[k][j]:

                lis2[i][j] = lis2[i][k] + lis2[k][j]
                lis2[j][i] = lis2[i][k] + lis2[k][j]

Q = int(input())

for i in range(Q):

    s,t = map(int,input().split())
    s -= 1
    t -= 1

    if lis2[s][t] == float("inf"):
        print (-1)
    else:
        print (lis2[s][t]-1)

Submission status: Wrong Answer

Solution code:
import collections
import heapq


def dijkstra_back(s, t, n, w, cost):
    # sからtへの最短経路の経路復元
    prev = [s] * n  # 最短経路の直前の頂点
    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 i in range(n):
            if d[i] > d[v] + cost[v][i]:
                d[i] = d[v] + cost[v][i]
                prev[i] = v

    path = [t]
    while prev[t] != s:
        path.append(prev[t])
        prev[t] = prev[prev[t]]
    path.append(s)
    path = path[::-1]
    return path


N, M, L = map(int, input().split())
A = [0]*M
B = [0]*M
C = [0]*M
cost = [[float("inf")] * N for i in range(N)]
for i in range(M):
    A[i], B[i], C[i] = map(int, input().split())
    if C[i] > L:
        C[i] = float("Inf")
    cost[A[i]-1][B[i]-1] = C[i]
    cost[B[i]-1][A[i]-1] = C[i]


# way = [-1]*N


Q = int(input())


s = [0]*Q
t = [0]*Q

for i in range(Q):
    s[i], t[i] = map(int, input().split())
    tmp = dijkstra_back(s[i]-1, t[i]-1, N, M, cost)
    id = 0
    oil = L
    ans = 0
    if len(tmp) == 0:
        print(-1)
    else:
        for i in range(1, len(tmp)):
            oil -= cost[tmp[i-1]][tmp[i]]
            if oil < 0:
                ans += 1
                oil = L
                oil -= cost[tmp[i-1]][tmp[i]]
        print(ans)

Submission status: Wrong Answer

Solution code:
def warshall_floyd(G):
    '''
    G: N * N Array (Adjacency matrix)
    ret: N * N Array (Minimum path)
    '''
    import copy
    ret = copy.deepcopy(G)
    for k in range(N):
        for i in range(N):
            for j in range(N):
                ret[i][j] = min(ret[i][j], ret[i][k] + ret[k][j])
    return ret


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

G = [[INF] * N for _ in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    G[A - 1][B - 1], G[B - 1][A - 1] = C, C

MinG = warshall_floyd(G)
GL = [[1 if MinG[i][j] <= L else INF for j in range(N)] for i in range(N)]
MinGL = warshall_floyd(GL)

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

Submission status: Wrong Answer

Solution code:
def e_travel_by_car(INF=float('inf')):
    from copy import deepcopy
    from scipy.sparse.csgraph import floyd_warshall
    N, M, L = [int(i) for i in input().split()]
    Roads = [[int(i) for i in input().split()] for j in range(M)]
    Q = int(input())
    Queries = [[int(i) for i in input().split()] for j in range(Q)]

    graph = [[INF] * N for _ in range(N)]
    for k in range(N):
        graph[k][k] = 0
    fuel = deepcopy(graph)

    for a, b, c in Roads:
        graph[a - 1][b - 1] = graph[b - 1][a - 1] = c
    dist = floyd_warshall(graph)

    for i in range(N):
        for j in range(N):
            fuel[i][j] = int(dist[i][j] <= L)
    fuel = floyd_warshall(fuel)

    ans = [-1 if fuel[s - 1][t - 1] == INF else int(fuel[s - 1][t - 1]) - 1 for s, t in Queries]
    return ' '.join(map(str, ans))

print(e_travel_by_car())

Submission status: Wrong Answer

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 u in d and v in d[u] and 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: Wrong Answer

Solution code:
import heapq
from collections import deque

n, m, full = map(int, input().split())
edges = [[]*n for _ in range(n)]

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
                dist[new_node][start] = 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: Wrong Answer

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


class Node(object):

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

  def __repr__(self):
    return str(self)

  def __str__(self):
    return '{}/{}({})'.format(self.supply, self.tank, int(self.fixed))


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

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

  for start in range(len(nodes)):
    for node in nodes:
      node.fixed = False
      node.supply = 300
      node.tank = 0

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

    while True:
      targets = [n for n in nodes if not n.fixed ]

      if len(targets) == 0:
        break

      target = min(targets, key=lambda n: (n.supply, -n.tank))
      target.fixed = True

      for n, d in target.edges:
        if n.fixed or d > tank:
          continue

        if d > target.tank:
          new_supply = target.supply + 1
          new_tank = tank - d
        else:
          new_supply = target.supply
          new_tank = target.tank - d

        if (new_supply, -new_tank) < (n.supply, -n.tank):
          n.supply = new_supply
          n.tank = new_tank

    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: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

    for i in range(n):
        w[i][i] = 0
        
    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = float("inf")
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c
            
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = min(wl[i][j], 1)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = float("inf")
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        w[a - 1][b - 1] = c
        w[b - 1][a - 1] = c
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = min(wl[i][j], 1)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == float("inf"):
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    w = [[float("inf")] * n for _ in range(n)]
    wl = [[float("inf")] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        w[a - 1][b - 1] = c
        w[b - 1][a - 1] = c
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if i != j:
                if w[i][j] <= l:
                    wl[i][j] = min(wl[i][j], 1)
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == float("inf"):
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
import sys
imput = sys.stdin.readline
def func(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())
road = [[10**10]*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
    road[b-1][a-1] = c
road = func(road)
ans = [[10**5]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        if road[i][j] <= L:
            ans[i][j] = 1
ans = func(ans)
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: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    w = [[10 ** 20] * n for _ in range(n)]
    wl = [[10 ** 20] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        w[a - 1][b - 1] = c
        w[b - 1][a - 1] = c
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if i != j:
                if w[i][j] <= l:
                    wl[i][j] = min(wl[i][j], 1)
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == 10 ** 20:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    w = [[10 ** 20] * n for _ in range(n)]
    wl = [[10 ** 20] * n for _ in range(n)]

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        w[a - 1][b - 1] = c
        w[b - 1][a - 1] = c
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0

    for i in range(n):
        for j in range(n):
            if i != j:
                if w[i][j] <= l:
                    wl[i][j] = min(wl[i][j], 1)
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == 10 ** 10:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    w = [[10 ** 10] * n for _ in range(n)]
    wl = [[10 ** 10] * n for _ in range(n)]
    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        w[a - 1][b - 1] = c
        w[b - 1][a - 1] = c
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    w[i][j] = min(w[i][j], w[i][k] + w[k][j])
            else:
                w[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                if w[i][j] <= l:
                    wl[i][j] = min(wl[i][j], 1)
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == 10 ** 10:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

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

distance = [[float("inf")]*n for i in range(n)]
path = [[-1]*n for i in range(n)]

count_pairs = [[-1]*n for i in range(n)]

for _ in range(m):
	a, b, c = map(int, input().split())
	if c > l: c = float("inf")
	distance[a-1][b-1] = c 
	distance[b-1][a-1] = c 
	path[a-1][b-1] = a-1
	path[b-1][a-1] = b-1
	count_pairs[a-1][b-1] = -1 if c==float("inf") else 0
	count_pairs[b-1][a-1] = -1 if c==float("inf") else 0


for k in range(n):
	for i in range(n):
		for j in range(n):
			if distance[i][k] == float("inf") or distance[j][k] == float("inf"):
				continue
			added = distance[i][k] + distance[k][j]
			if added < distance[i][j] and i != j:
				count_pairs[i][j] = count_pairs[i][k] + count_pairs[k][j] + (1 if added > l else 0)
				count_pairs[j][i] = count_pairs[i][k] + count_pairs[k][j] + (1 if added > l else 0)

				distance[i][j] = added
				distance[j][i] = added
				path[i][j] = path[k][j]
				path[j][i] = path[k][i]


q = int(input())

for _ in range(q):
	src, dest = map(int, input().split())
	print(count_pairs[src-1][dest-1])