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:
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):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    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:
import sys


def main():
	input = sys.stdin.readline
	N, M, L = list(map(int,input().split()))
	P = [list(map(int,input().split())) for i in range(M)]
	Q = int(input())
	st = [list(map(int,input().split())) for i in range(Q)]

	neighbor = [[10**10]*N for i in range(N)]
	for s,e,d in P:
		# if d<=L:
		# 	neighbor[s-1].append((e-1,d))
		# 	neighbor[e-1].append((s-1,d))
		neighbor[s-1][e-1] = neighbor[e-1][s-1] = d

	# start, end = 2,1

	fuellist = [0]*N
	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
			nq_append = nq.append
			for i in queue:				# target node
				oc, om = fuel[i]
				for j, d in enumerate(neighbor[i]):	# next node
					if d==10**10: continue
					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
						nq_append(j)

			queue = nq					# update target node

		ans = fuel[end][0]
		if ans==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: Wrong Answer

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

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


G = csr_matrix(G)
G_shortest, G_rev = shortest_path(G, return_predecessors=True)


def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])


def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


Q = int(input())
for q in range(Q):
    s, t = map(int, input().split())
    s, t = s - 1, t - 1
    path = get_path(s, t, G_rev)

    if not path:
        print(-1)
        continue

    ans = 0
    tank = L

    for i in range(len(path) - 1):
        cost = G_shortest[path[i]][path[i + 1]]
        if cost > L:
            print(-1)
            break

        if cost > tank:
            ans += 1
            tank = L

        tank -= cost

    print(ans)

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
                todo.append([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)

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

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

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

        for new_node in L_edges[node]:
            if distance[start][new_node] > d + 1:
                distance[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 = distance[s-1][t-1]-1
    if ans == float('INF'):
        ans = -1
    print(ans)

Submission status: Wrong Answer

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
    road[b-1][a-1] = c


for k in range(N):
    for i in range(N):
        for j 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 k in range(N):
    for j in range(N):
        if road[i][j] <= L:
            ans[i][j] = 1
for k in range(N):
    for i in range(N):
        for j 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: 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)]

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

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:
				distance[i][j] = added
				distance[j][i] = added
				path[i][j] = path[k][j]
				path[j][i] = path[k][i]

def print_path(start, end):
	stack = [end]
	while True:
		end = path[start][end]
		if end == -1:
			break
		stack.append(end)
		if end == start: break

	return stack[::-1]

def solve(ppath):
	count = 0
	rem_fuel = l 
	for i in range(1, len(ppath)):
		if distance[ppath[i]][ppath[i-1]] > l:
			return -1
		if rem_fuel < distance[ppath[i]][ppath[i-1]]:
			count += 1
			rem_fuel = l
		rem_fuel -= distance[ppath[i]][ppath[i-1]]
	return count 

q = int(input())

for _ in range(q):
	src, dest = map(int, input().split())
	ret = print_path(src-1, dest-1)
	if len(ret)==1:
		print(-1)
	else:
		ans = solve(ret)
		print(ans)

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] = 1
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    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())

l1 = [[10 ** 15 for i in range(n)] for i in range(n)]
for i in range(n):
    l1[i][i] = 0

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

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

l2 = [[10 ** 4 for i in range(n)] for i in range(n)]
for i in range(n):
    l2[i][i] = 0

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

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

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

for sq in lq:
    res = l2[sq[0] - 1][sq[1] - 1]
    if res == 10 ** 4:
        print(-1)
    else:
        print(res - 1)

Submission status: Wrong Answer

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
    road[b-1][a-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):
    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: 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)]

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

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:
				distance[i][j] = added
				distance[j][i] = added
				path[i][j] = path[k][j]
				path[j][i] = path[k][i]

def print_path(start, end):
	stack = [end]
	while True:
		end = path[start][end]
		if end == -1:
			break
		stack.append(end)
		if end == start: break

	return stack[::-1]

def solve(ppath):
	count = 0
	rem_fuel = l 
	for i in range(1, len(ppath)):
		if distance[ppath[i]][ppath[i-1]] > l:
			return -1
		if rem_fuel < distance[ppath[i]][ppath[i-1]]:
			count += 1
			rem_fuel = l
		rem_fuel -= distance[ppath[i]][ppath[i-1]]
	return count 

q = int(input())

for _ in range(q):
	src, dest = map(int, input().split())
	ret = print_path(src-1, dest-1)
	ans = solve(ret)
	print(ans)

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()))
        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 i != j:
                if w[i][j] <= l:
                    wl[i][j] = 1
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    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()))
        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 i != j:
                if w[i][j] <= l:
                    wl[i][j] = 1
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    q = int(input().rstrip('\n'))
    print(w)
    print(wl)
    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:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

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


G = np.array(G)
G_shortest, G_rev = shortest_path(G, return_predecessors=True)


def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])


def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


Q = int(input())
for q in range(Q):
    s, t = map(int, input().split())
    s, t = s - 1, t - 1
    path = get_path(s, t, G_rev)

    if not path:
        print(-1)
        continue

    ans = 0
    tank = L

    for i in range(len(path) - 1):
        if G_shortest[path[i]][path[i + 1]] > tank:
            ans += 1
            tank = L

        tank -= G_shortest[path[i]][path[i + 1]]

    print(ans)

Submission status: Wrong Answer

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

l1 = [[10 ** 15 for i in range(n)] for i in range(n)]
for i in range(n):
    l1[i][i] = 0

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

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

l2 = [[10 ** 4 for i in range(n)] for i in range(n)]
for i in range(n):
    l2[i][i] = 0

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

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

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

for sq in lq:
    res = l2[sq[0] - 1][sq[1] - 1]
    if res == 10 ** 4:
        print(-1)
    else:
        print(res - 1)

Submission status: Wrong Answer

Solution code:
import heapq

N, M, L = [int(v) for v in input().split(' ')]

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

for i in range(M):
    A, B, C = [int(v) for v in input().split()]
    a = A - 1
    b = B - 1
    cost[a][b] = C
    cost[b][a] = C
    link[a].append(b)
    link[b].append(a)

def search(s, t):
    h = []
    heapq.heappush(h, (0, 0, L, s))

    closed = 0
    while len(h) > 0:
        _, c, f, n = heapq.heappop(h)
        closed |= (1 << n)

        if n == t:
            return c

        for n2 in link[n]:
            if (closed & (1 << n2)) != 0:
                continue

            f2 = f
            c2 = c
            cst = cost[n][n2]
            if cst < 0:
                raise
            if f2 < cst:
                if f2 == L:
                    continue
                else:
                    f2 = L
                    c2 += 1

            if f2 >= cst:
                f2 -= cst
            else:
                f2 = L
                c2 += 1
            heapq.heappush(h, (c2 * L + (L - f2 / 2), c2, f2, n2))

    return -1

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

Submission status: Wrong Answer

Solution code:
import heapq

N, M, L = [int(v) for v in input().split(' ')]

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

for i in range(M):
    A, B, C = [int(v) for v in input().split()]
    a = A - 1
    b = B - 1
    cost[a][b] = C
    cost[b][a] = C
    link[a].append(b)
    link[b].append(a)

def search(s, t):
    h = []
    heapq.heappush(h, (0, 0, L, -1, s))

    closed = 0
    while len(h) > 0:
        _, c, f, n0, n = heapq.heappop(h)
        closed |= (1 << n)

        if n == t:
            return c

        for n2 in link[n]:
            if (closed & (1 << n2)) != 0:
                continue

            f2 = f
            c2 = c
            cst = cost[n][n2]
            if cst < 0:
                raise
            if f2 < cst:
                if f2 == L:
                    continue
                else:
                    f2 = L - cost[n0][n]
                    c2 += 1

            if f2 >= cst:
                f2 -= cst
            else:
                f2 = L
                c2 += 1
            heapq.heappush(h, (c2 * L + (L - f2), c2, f2, n, n2))

    return -1

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

Submission status: Wrong Answer

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

l1 = [[10 ** 14 for i in range(n)] for i in range(n)]
for i in range(n):
    l1[i][i] = 0

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

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

l2 = [[10 ** 4 for i in range(n)] for i in range(n)]

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

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

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

for sq in lq:
    res = l2[sq[0] - 1][sq[1] - 1] - 1
    if res == 10 ** 4 - 1:
        print(-1)
    else:
        print(res)

Submission status: Wrong Answer

Solution code:
N,M,L = list(map(int,input().split()))
from collections import defaultdict

graph = defaultdict(set)
weight = dict()

for m in range(M):
  a,b,c = list(map(int,input().split()))
  
  weight[(a,b)]=c
  weight[(b,a)]=c
  graph[a] |= {b}
  graph[b] |= {a}


available_path = defaultdict(set)


for i in range(N):
  # ある街を出発して無補給でたどり着ける町のリストを作成する
  start_node = i+1
  query =[(start_node,set(),L)]
  index = 0
  while index != len(query):
    now_node, prevs, fuel = query[index]
    # 最後のノードから接続されるノードを考える
    
    for next_node in graph[now_node]:
      nokori = fuel - weight[(now_node,next_node)]
      #print(now_node,next_node,prevs,nokori) 
      if next_node not in prevs and nokori >= 0:
        query.append((next_node, prevs|{now_node}, nokori))
        available_path[start_node]|={next_node}
        available_path[next_node]|={start_node}
    index += 1
#print(available_path)
    
  
from heapq import heappush, heappop

for q in range(int(input())):
  start,end = list(map(int,input().split()))
  #print("query",start,end)
  query = []
  heappush(query, (0,start,set()) )
  while len(query)>0:
    cnt,now_node, prevs  = heappop(query)
    # 最後のノードから接続されるノードを考える
    #print(start,"->",end,":",cnt,now_node, prevs)
    if  end in available_path[now_node]:
        print(cnt)
        break
    else:
      for next_node in available_path[now_node]:
        if next_node not in prevs:
          heappush(query, (cnt+1, next_node, prevs|{now_node}) )

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()))
        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 i != j:
                if w[i][j] <= l:
                    wl[i][j] = 1
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        print(wl[s-1][t-1]-1)


if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]


g = Graph()
N, M, L = [int(i) for i in input().split()]

for i in range(M):
    u, v, c = [int(i) for i in input().split()]
    if c >= L:
        c = float("inf")

    g.add_edge(u - 1, v - 1, c)
    g.add_edge(v - 1, u - 1, c)


g2 = Graph()
for i in range(N):
    d = Dijkstra(g, i)
    for j in range(N):
        dist = d.dist[j]
        if dist <= L and i != j:
            g2.add_edge(i, j, 1)
            g2.add_edge(j, i, 1)


s_0 = -1
ans = []
Q = int(input())
s_t_index = []
for i in range(Q):
    s, t = [int(i) for i in input().split()]
    s_t_index.append([s, t, i])

s_t_index.sort()
# print(s_t_index)

for i in range(Q):
    if s_t_index[i][0] != s_0:
        s_0 = s_t_index[i][0]
        d = Dijkstra(g2, s_0-1)
        length = len(d.shortest_path(s_t_index[i][1]-1))
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1], length])
    else:
        length = len(d.shortest_path(s_t_index[i][1]-1))
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1], length])


ans.sort()
[print([ans[i][1]-1, -1][ans[i][1] == float("inf")]) for i in range(Q)]

Submission status: Wrong Answer

Solution code:
import heapq

N, M, L = [int(v) for v in input().split(' ')]

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

for i in range(M):
    A, B, C = [int(v) for v in input().split()]
    a = A - 1
    b = B - 1
    cost[a][b] = C
    cost[b][a] = C
    link[a].append(b)
    link[b].append(a)

def search(s, t):
    h = []
    closed = 0

    heapq.heappush(h, (0, 0, L, s))

    while len(h) > 0:
        _, c, f, n = heapq.heappop(h)
        closed |= (1 << n)

        if n == t:
            return c

        for n2 in link[n]:
            if (closed & (1 << n2)) != 0:
                continue

            f2 = f
            c2 = c
            cst = cost[n][n2]
            if cst < 0:
                raise
            if f2 < cst:
                if f2 == L:
                    continue
                else:
                    f2 = L
                    c2 += 1

            if f2 >= cst:
                f2 -= cst
            else:
                f2 = L
                c2 += 1
                
            heapq.heappush(h, (c2 * L + (L - f2), c2, f2, n2))

    return -1

def main():

    Q = int(input())

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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, L = [int(i) for i in input().split()]

d = [[1e+10]*N for i in range(N)]
for i in range(M):
    A, B, C = [int(i) for i in input().split()]
    d[A-1][B-1] = C
    d[B-1][A-1] = C
for i in range(N):
    for j in range(N):
        for k in range(N):
            d[j][k] = min(d[j][k], d[j][i] + d[i][k])

d2 = [[1 if j <= L else 1e+10 for j in d[i]] for i in range(N)]
for i in range(N):
    for j in range(N):
        for k in range(N):
            d2[j][k] = min(d2[j][k], d2[j][i] + d2[i][k])

Q = int(input())
for i in range(Q):
    s, t = [int(i) for i in input().split()]
    ans = d2[s-1][t-1]
    if ans >= 1e+10:
        print(-1)
    else:
        print(ans)

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()))
        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 i != j:
                if w[i][j] <= l:
                    wl[i][j] = 1
            else:
                wl[i][j] = 0
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(n):
                    wl[i][j] = min(wl[i][j], wl[i][k] + wl[k][j])
            else:
                wl[i][j] = 0
    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        print(wl[s-1][t-1]-1)



if __name__ == '__main__':
    slove()

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import floyd_warshall as f
from scipy.sparse import csr_matrix
import numpy as np
n,m,l,*L=map(int,open(0).read().split())
abc=L[:3*m];st=L[3*m+1:]
a,b,c=abc[::3],abc[1::3],abc[2::3]
s,t=st[::2],st[1::2]
fw=f(csr_matrix((c,(a,b)),(n+1,n+1)),0)
fw2=f(np.where(fw<=l,1,fw),0)-1
res=np.where(fw2<np.inf,fw2,-1)
ans=res[s,t].astype(int)
print(*ans,sep="\n")