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:
import sys
from heapq import heappop, heappush
from math import ceil

n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()
INF = 10 ** 18

dists = [[(INF, INF)] * n for _ in range(n)]

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

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if c > l:
        continue
    dists[a][b] = (0, c)
    dists[b][a] = (0, c)

for k in range(n):
    dk = dists[k]
    for i in range(n):
        di = dists[i]
        cik, uik = di[k]
        if cik == INF:
            continue
        for j in range(n):
            ckj, ukj = dk[j]
            if uik + ukj <= l:
                new_dist = (cik + ckj, uik + ukj)
            else:
                new_dist = (cik + ckj + 1, ukj)
            if di[j] > new_dist:
                di[j] = new_dist
# print(*dists, sep='\n')

buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    dist, _ = dists[s - 1][t - 1]
    buf.append(-1 if dist == INF else dist)

print('\n'.join(map(str, buf)))

Submission status: Wrong Answer

Solution code:
from collections import deque

def ans(s,t):
    global L
    global d
    oil=[-1 for i in range(N+1)];oil[s]=L # sからその街にたどり着いた時の燃料の残量
    cnt=[-1 for i in range(N+1)];cnt[s]=0 # sからの最少給油回数
    
    q=deque()
    q.append(s)
    while q:
        u=q.popleft()
        for v in out[u]:
            if cnt[v]==-1:
                duv=d[u][v]
                if duv<=L:
                    if duv>oil[u]:
                        cnt[v]=cnt[u]+1
                        oil[v]=L-duv
                    else:
                        cnt[v]=cnt[u]
                        oil[v]=oil[u]-duv
                    q.append(v)
    return cnt[t]

N,M,L=map(int,input().split())
d=[[0 for j in range(N+1)] for i in range(N+1)] # 街の番号は1-initial
out=[set() for i in range(N+1)] # 街iから道の続く街
for  _ in range(M):
    A,B,C=map(int,input().split())
    d[A][B]=d[B][A]=C
    out[A].add(B)
    out[B].add(A)

for _ in range(int(input())):
    s,t=map(int,input().split())
    print(ans(s,t))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
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]


def query(src, dst, d_list, d_dict, l):
    count = 0
    now_l = l
    d = d_list[src-1]
    path = d.shortest_path(dst-1)

    if(len(path) == 1):
        print(-1)
        return

    now_s = path[0]

    for item in path[1:]:
        length = d_dict[str(now_s)+":"+str(item)]
        if length > l:
            print(-1)
            return
        elif length > now_l:
            count += 1
            now_l = l - length
        else:
            now_l = now_l - length
        now_s = item
    print(count)


n, m, l = map(int, input().split())
inputs = []
d_dict = dict()

for i in range(m):
    a, b, c = map(int, input().split())
    inputs.append((a-1, b-1, c))
    d_dict[str(a-1)+":"+str(b-1)] = c
    d_dict[str(b-1)+":"+str(a-1)] = c

g = Graph()
for src, dst, weight in inputs:
    g.add_edge(src, dst, weight)
    g.add_edge(dst, src, weight)

d_list = []

for i in range(n):
    d_list.append(Dijkstra(g, i))

q = int(input())

for i in range(q):
    s, t = map(int, input().split())
    query(s, t, d_list, d_dict, l)

Submission status: Wrong Answer

Solution code:
import sys, math

def input():
    return sys.stdin.readline()[:-1]

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



def main():
    N, M, L = map(int,input().split())
    cost = [[float("inf") for k in range(N)] for j in range(N)]
    for k in range(M):
        A, B, C = map(int,input().split())
        cost[A-1][B-1] = C
        cost[B-1][A-1] = C
    Q = int(input())
    ans = []
    for q in range(Q):
        s, t = map(int,input().split())
        d = dijkstra_back(s-1,t-1,N,M,cost)
        temp = L
        u = 0
#        print(d)
        for k in range(len(d)-1):
#            print(temp,cost[d[k]][d[k+1]])
            if cost[d[k]][d[k+1]] == float("inf"):
                u = -1
                break
            elif cost[d[k]][d[k+1]] > temp:
                u += 1
                temp = L - cost[d[k]][d[k+1]]
                if temp < 0:
                    u =- 1
                    break
            else:
                temp -= cost[d[k]][d[k+1]]
        ans.append(u)
    print(*ans,sep="\n")


if __name__ == '__main__':
    main()

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


@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
    
    dd = defaultdict(lambda: -1)
    def f(s, t):
        if (s, t) in dd:
            return dd[(s, t)]
        q = [(0, s)]
        done = set([s])
        d = 0
        while q:
            d, u = heapq.heappop(q)
            qq = [(-L, u)]
            cand = set()
            while qq:
                rem, uu = heapq.heappop(qq)
                rem = -rem
                for vv in g[uu]:
                    if rem-g[uu][vv] < 0:
                        continue
                    if vv in done:
                        continue
                    qq.append((-(rem-g[uu][vv]), vv))
                    cand.add(vv)
            
            done |= cand
            for v in cand:
                dd[(s, v)] = d
                heapq.heappush(q, (d+1, v))

        for i in range(1, N+1):
            if i not in done:
                dd[(s, i)] = -1

        return dd[(s, t)]

    for s, t in ST:
        print(f(s, t))



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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, L = map(int, input().split())
edges = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    A, B = A-1, B-1
    edges[A][B] = C
    edges[B][A] = C

data = [[None for i in range(N)] for j in range(N)]

# Build up data
def dijkstra(start):
    distances = [(float('inf'), float('inf')) for i in range(N)]
    visited = [False for i in range(N)]
    
    distances[start] = (0, 0)
    while True:
        curVertex = min(range(N), key=lambda n:(visited[n], distances[n]))
        refill, left = distances[curVertex]
        
        if visited[curVertex] or distances[curVertex][0] == float('inf'): break
        visited[curVertex] = True
        
        for neighbour in range(N):
            cost = edges[curVertex][neighbour]
            if cost == float('inf'): continue

            if cost > left and L >= cost:
                distances[neighbour] = min(distances[neighbour], (refill + 1, L - cost))
            elif left >= cost:
                distances[neighbour] = min(distances[neighbour], (refill, left - cost))

    for i in range(N):
        if visited[i]:
            data[start][i] = distances[i][0]
        else:
            data[start][i] = -1

for i in range(N): dijkstra(i)

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

Submission status: Wrong Answer

Solution code:
mod = 10**10
N, M, L = map(int, input().split())
dist = [[float('inf') for _ in range(N+1)] for _ in range(N+1)]
ans = [[10**10 for _ in range(N+1)] for _ in range(N+1)]
for i in range(1, N+1):
    dist[i][i] = 0
for _ in range(M):
    a, b, c = map(int, input().split())
    if c <= L:
        dist[a][b] = c
        dist[b][a] = c


def WF(dist, ans):
    for i in range(1, N+1):
        for j in range(1, N+1):
            for k in range(1, N+1):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    for i in range(1, N+1):
        for j in range(N+1):
            if dist[i][j] <= L:
                ans[i][j] = 1
    for i in range(1, N+1):
        for j in range(1, N+1):
            for k in range(1, N+1):
                ans[i][j] = min(ans[i][j], ans[i][k] + ans[k][j])
    return ans


ans = WF(dist, ans)

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

Submission status: Wrong Answer

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

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

def main():
    N, M, L = map(int, input().split())
    d = [[float("inf") for i in range(N)] for i in range(N)] 

    for _ in range(M):
        A, B, M = map(int, input().split())
        A -= 1
        B -= 1
        d[A][B] = M
        d[B][A] = M

    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        cnt = 0
        life = copy.deepcopy(L)
        route = dijkstra_back(s,t,N,M,d)
        for i in range(len(route)-1):
            if life >= d[route[i]][route[i+1]]:
                life -= d[route[i]][route[i+1]]
            else:
                life = copy.deepcopy(L)
                cnt += 1
                if life < d[route[i]][route[i+1]]:
                    print(-1)
                    break
                else:
                    life -= d[route[i]][route[i+1]]
        else:
            print(cnt)



    

    

main()

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


@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
    
    dd = defaultdict(lambda: -1)
    def f(s, t):
        if (s, t) in dd:
            return dd[(s, t)]
        q = [(0, s)]
        done = set([s])
        d = 0
        while q:
            d, u = heapq.heappop(q)
            qq = [(-L, u)]
            cand = set()
            while qq:
                rem, uu = heapq.heappop(qq)
                rem = -rem
                for vv in g[uu]:
                    if rem-g[uu][vv] < 0:
                        continue
                    if vv in cand or vv in done:
                        continue
                    qq.append((-(rem-g[uu][vv]), vv))
                    cand.add(vv)
            
            done |= cand
            for v in cand:
                dd[(s, v)] = d
                heapq.heappush(q, (d+1, v))

        for i in range(1, N+1):
            if i not in done:
                dd[(s, i)] = -1

        return dd[(s, t)]

    for s, t in ST:
        print(f(s, t))



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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections
import heapq


# https://qiita.com/kazukazukazukazu/items/e5db00a3aefb1f5ed72f 2019/08/18
class Dijkstra():
    def __init__(self):
        self.e = collections.defaultdict(list)

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

    def delete(self, u, v):
        self.e[u] = [_ for _ in self.e[u] if _[0] != v]
        self.e[v] = [_ for _ in self.e[v] if _[0] != u]

    def search(self, s):
        """
        #0-indexedでなくてもよいことに注意
        #:param s: 始点
        #:return: 始点から各点までの最短経路と最短経路を求めるのに必要なprev
        """
        d = collections.defaultdict(lambda: float('inf'))
        prev = collections.defaultdict(lambda: None)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv, ud in self.e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] > vd:
                    d[uv] = vd
                    prev[uv] = u
                    heapq.heappush(q, (vd, uv))

        return d, prev

    def getShortestPath(self, start, goal):

        _, prev = self.search(start)
        shortestPath = []
        node = goal
        while node is not None:
            shortestPath.append(node)
            node = prev[node]
        return shortestPath[::-1]


N, M, L = map(int, input().split())
graph = Dijkstra()
cost = [[0 for _ in range(301)] for __ in range(301)]

for _ in range(M):
    a, b, c = map(int, input().split())
    if c <= L:
        graph.add(a, b, c)
        cost[a][b] = c
        cost[b][a] = c

Q = int(input())
for _ in range(Q):
    ans = 0
    s, t = map(int, input().split())
    path = graph.getShortestPath(s, t)
    F = L
    for i in range(len(path) - 1):
        if F >= cost[path[i]][path[i + 1]]:
            F -= cost[path[i]][path[i + 1]]
        else:
            F = L
            F -= cost[path[i]][path[i + 1]]
            ans += 1
    if len(path) == 1:
        print(-1)
    else:
        print(ans)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import numpy as np
n,m,l,*L=map(int,open(0).read().split())
abc=L[:3*m];st=L[3*m+1:]
town=[[float("inf")]*n for _ in range(n)]
for a,b,c in zip(*[iter(abc)]*3):
	if c<=l:
		town[a-1][b-1]=c
fw=floyd_warshall(town,0)
ti=floyd_warshall(np.where(fw<=l,1,100),0)
for s,t in zip(*[iter(st)]*2):
	if ti[s-1,t-1]==float("inf"):
		print(-1)
	else:
		print(int(ti[s-1,t-1]-1))

Submission status: Wrong Answer

Solution code:
import heapq
n, m, l = list(map(int, raw_input().split(" ")))

roads = [[-1 for _ in range(n)] for _ in range(n)]
for _ in range(m):
	a, b, c = list(map(int, raw_input().split(" ")))
	roads[a-1][b-1] = c
	roads[b-1][a-1] = c


def solve(s):
	dp = [None for _ in range(n)]
	h = [(0, -l, s)]

	while h:
		val, cur_cap, v = heapq.heappop(h)
		cur_cap = cur_cap*-1
		if dp[v] is not None:
			continue

		dp[v] = (val, cur_cap)
		for t in range(n):
			if v == t or roads[v][t] == -1 or dp[t] is not None:
				continue

			if roads[v][t] <= cur_cap:
				ex_ans, ex_cap = val, cur_cap-roads[v][t]
			else:
				ex_ans, ex_cap = val+1, l-roads[v][t]

			heapq.heappush(h, (ex_ans, ex_cap*-1, t))
	return dp

ans = [solve(i) for i in range(n)]
print(ans)

k = int(raw_input())
for _ in range(k):
	s, t = list(map(int, raw_input().split(" ")))
	print(ans[s-1][t-1][0] if ans[s-1][t-1] is not None else -1)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for _ in range(m)]
q=int(input())
st=[list(map(int,input().split())) for _ in range(q)]

d = [[float("inf") for i in range(n)] for i in range(n)]

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

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

warshall_floyd(d)

for i in range(q):
    s,t=st[i]
    x=d[s-1][t-1]
    print((x-1)//l)

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m,l = LI()
    v = [[] for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        v[a].append((b,c))
        v[b].append((a,c))
    ans = [[float("inf")]*n for i in range(n)]
    q = []
    for s in range(n):
        ans[s][s] = 0
        heappush(q,(0,0,s))
        while q:
            da,dx,x = heappop(q)
            for y,w in v[x]:
                if w > l:
                    continue
                nd = dx+w
                if nd <= l:
                    na_ = da
                    nd_ = nd
                else:
                    na_ = da+1
                    nd_ = w
                if na_ < ans[s][y]:
                    ans[s][y] = na_
                    heappush(q,(na_,nd_,y))
    q = I()
    for _ in range(q):
        s,t = LI()
        s -= 1
        t -= 1
        ds = ans[s][t]
        if ds == float("inf"):
            print(-1)
        else:
            print(ds)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

from collections import deque
import copy

N,M,L = II()
A,B,C = Line(M,3)
Q = I()
s,t = Line(Q,2)

E = [[float('inf')]*N for _ in range(N)]
for i in range(N):
    E[i][i] = 0
for i in range(M):
    E[A[i]-1][B[i]-1] = C[i]
    E[B[i]-1][A[i]-1] = C[i]

E2 = copy.deepcopy(E)

d = [[-1]*N for _ in range(N)]
for k in range(N):
    for i in range(N):
        for j in range(N):
            if E[i][j] > E[i][k]+E[k][j]:
                E[i][j] = E[i][k]+E[k][j]
                d[i][j] = k


path = [[deque([]) for _ in range(N)] for _ in range(N)]
for i in range(N):
    for j in range(N):
        k = j
        while d[i][k]!=-1:
            k = d[i][k]
            path[i][j].appendleft(k)
        path[i][j].append(j)

ans = [[0]*N for _ in range(N)]
for i in range(N):
    for j in range(N):
        l = L
        now = i
        p = 0
        if path[i][j]:
            ne = path[i][j][p]
        else:
            ne = j
        while now != j:
            if E[now][ne]>L:
                ans[i][j] = -1
                break
            elif l < E[now][ne]:
                ans[i][j] += 1
                l = L-E[now][ne]
                if ne!=j:
                    now = ne
                    p += 1
                    ne = path[i][j][p]
                else:
                    break
            else:
                l -= E[now][ne]
                now = ne
                if ne!=j:
                    p += 1
                    ne = path[i][j][p]
                else:
                    break      

for i in range(Q):
    print(ans[s[i]-1][t[i]-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

def main():
    N,M,L = mis()
    import numpy as np
    INF = np.iinfo(np.int64).max
    d = np.full((N,N), INF, dtype=np.uint64)
    for i in range(N):
        d[i,i] = 0
    #
    for _ in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        if c <= L:
            d[a,b] = c
            d[b,a] = c
    #
    for k in range(N):
        for i in range(N):
            dik = d[i,k]
            np.minimum(d[i,:], dik+d[k,:], out=d[i,:])
    #
    Q = ii()
    for _ in range(Q):
        s,t = mis()
        s -= 1
        t -= 1
        dist = d[s,t]
        if dist == INF:
            print(-1)
        else:
            print(int(dist)//L)




main()

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline


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


def read_is(n=1):
    return [read_i() for _ in range(n)]


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[] for _ in range(n_nodes)]

    def add_edge(self, s, t, d=None, undirected=False):
        if d is not None:
            self.edges[s].append((t, d))
        else:
            self.edges[s].append(t)
        if undirected:
            self.add_edge(t, s, d)

    def add_edges(self, edges, undirected=False):
        for edge in edges:
            self.add_edge(*edge, undirected=undirected)


class FloydWarshall:
    def __init__(self, graph):
        self.graph = graph
        self.distances = [[float('inf')] * graph.n_nodes
                          for _ in range(graph.n_nodes)]
        self.nexts = [[None] * graph.n_nodes for _ in range(graph.n_nodes)]
        self._init()

    def _init(self):
        for x in range(self.graph.n_nodes):
            self.distances[x][x] = 0
        for source in range(self.graph.n_nodes):
            for destination, distance in self.graph.edges[source]:
                self.distances[source][destination] = distance
                self.nexts[source][destination] = destination

    def compute_shortest_path_lengths(self):
        for k in range(self.graph.n_nodes):
            for i in range(self.graph.n_nodes):
                for j in range(self.graph.n_nodes):
                    s = self.distances[i][k] + self.distances[k][j]
                    if s < self.distances[i][j]:
                        self.distances[i][j] = s
                        self.nexts[i][j] = self.nexts[i][k]

    def get_shortest_path_cost(self, x, y):
        if self.nexts[x][y] is None:
            return []
        costs = []
        prev = x
        while prev != y:
            s = prev
            t = self.nexts[s][y]
            costs.append(self.distances[s][t])
            prev = t
        return costs


n, m, l = read_i()
graph = Graph(n)
for _ in range(m):
    a, b, c = read_i()
    if c > l:
        continue
    if a > b:
        a, b = b, a
    graph.add_edge(a - 1, b - 1, d=c, undirected=True)
fw = FloydWarshall(graph)
fw.compute_shortest_path_lengths()

q = int(input())
for _ in range(q):
    s, t = read_i()
    s -= 1
    t -= 1
    costs = fw.get_shortest_path_cost(s, t)
    if len(costs) == 0:
        print(-1)
        continue

    count = 0
    r = l
    for x in costs:
        if x > l:
            print(-1)
            break
        r -= x
        if r < 0:
            count += 1
            r = l - x
    else:
        print(count)

Submission status: Wrong Answer

Solution code:
import sys
N, M, L = map(int, input().split())

# cook your dish here
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


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

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

Q = int(input())
for q in range(Q):
    s, t = map(int, input().split())

    lis = dijkstra_back(s - 1, t - 1, N, M, cost)
    ans = 0
    tmp_L = L
    for n in range(len(lis) - 1):
        if L < cost[lis[n]][lis[n + 1]]:
            print(-1)
            sys.exit()
        if tmp_L >= cost[lis[n]][lis[n + 1]]:
            tmp_L -= cost[lis[n]][lis[n + 1]]
        else:
            tmp_L = L
            tmp_L -= cost[lis[n]][lis[n + 1]]
            ans += 1
    print(ans)