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 numpy as np
from scipy.sparse.csgraph import floyd_warshall

N, M, L = map(int, input().split())
Map = np.full((N, N), 10**12, dtype='int64')
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    Map[a][b] = c
    Map[b][a] = c
Q = int(input())
Query = [tuple(map(int, input().split())) for _ in range(Q)]
graph = floyd_warshall(Map).astype('int64')
graph[graph <= L] = 1
graph[graph > L] = 10**12
A = floyd_warshall(graph).astype('int64')
print(A)
for s, t in Query:
    if A[s - 1][t - 1] >= 10**12:
        print(-1)
    else:
        print(int(A[s - 1][t - 1] - 1))

Submission status: Wrong Answer

Solution code:
from collections import deque
import heapq
import sys
input = sys.stdin.readline

f=lambda:map(int,input().split())
V,E,L=f()
G=[[] for _ in [0]*(V+1)]
# G=[]

for _ in range(E):
    s,t,d=f()
    if d<=L:
        G[s].append((t,(0,d)))
        G[t].append((s,(0,d)))
    
INF=10**15

def dijk(s):
    # q[i]:点i+1の現状のコスト
    q=[((0,0),s)]
    heapq.heapify(q)

    res=[(V+5,0)]*(V+1)
    while q:
        C,p=heapq.heappop(q)
        if C<res[p]:
            res[p]=C
        else:
            continue
        for np,D in G[p]:
            d=D[1]+C[1]
            if d>L:
                costB=(1+C[0]+D[0],D[1])
            else:
                costB=(C[0]+D[0],d)
            heapq.heappush(q,(min(res[np],costB),np))
    return res

res=[0]+[dijk(i+1) for i in range(V)]

Q=int(input())
for _ in [0]*Q:
    s,t=f()
    r=res[s][t][0]
    print(r if r<INF else -1)

Submission status: Wrong Answer

Solution code:
import heapq
class Car:
    def __init__(self,h,d):
        self.h=h
        self.d=d
        
    def __add__(self,other):
        h1,d1=self.h,self.d
        h2,d2=other.h,other.d
        if d1+d2>L:
            h=1+h1+h2
            d=d2
        else:
            h=h1+h2
            d=d1+d2
        return Car(h,d)
    
    def __str__(self):
        return str((self.h,self.d))
    
    def __lt__(self,other):
        if self.h < other.h :
            return True
        else:
            return self.d < other.d
f=lambda:map(int,input().split())
V,E,L=f()
G=[[] for _ in [0]*(V+1)]
# G=[]

for _ in range(E):
    s,t,d=f()
    if d<=L:
        G[s].append((t,Car(0,d)))
        G[t].append((s,Car(0,d)))
    
INF=float('inf')

def dijk(s):
    q=[(Car(0,0),s)]
    heapq.heapify(q)

    res=[Car(INF,INF)]*(V+1)
    while q:
        C,p=heapq.heappop(q)
        if C<res[p]:
            res[p]=C
        else:
            continue
        for np,D in G[p]:
            heapq.heappush(q,(min(res[np],C+D),np))
    return res

res=[0]+[dijk(i+1) for i in range(V)]

Q=int(input())
for _ in [0]*Q:
    s,t=f()
    r=res[s][t].h
    print(r if r<INF else -1)

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq


def input():
    return sys.stdin.readline().rstrip()


def dijkstra(s, n, es, L):
    # n:頂点数, es: 辺uvのコスト
    d = [10 ** 14 + 7] * n
    # 探索リスト
    S = [(0, s)]
    # 優先度付きキューを使うと計算量が少なくなるよ
    heapq.heapify(S)
    used = [False] * n

    d[s] = 0

    while S:
        # 最小コストの頂点を取り出し
        dg, v = heapq.heappop(S)
        if used[v] == True:
            continue
        used[v] = True
        for u, w in es[v]:
            if d[v] % L + w > L:
                cost = d[v] - d[v] % L + L + w
            else:
                cost = d[v] + w

            if d[u] > cost:
                d[u] = cost
                heapq.heappush(S, (d[u], u))

        # print("d", d)
    return d


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

    dp = [[L+2]*N for _ in range(N)]
    for i in range(N):
        dp[i][i] =0
    for i in range(M):
        x, y, z = map(int, input().split())
        if z > L:
            continue

        x = x - 1
        y = y - 1
        dp[x][y] =z
        dp[y][x]=z



    def warshal(ws,n):
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    ws[i][j] =min(ws[i][j],ws[i][k]+ws[k][j])
        return ws

    ls =warshal(dp,N)
    for i in range(N):
        for j in range(N):
            if ls[i][j] <=L:
                ls[i][j] =1
            else:
                ls[i][j] =500
    vs = warshal(ls,N)

    Q =int(input())

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





if __name__ == "__main__":
    main()

# \n

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq

def input():
    return sys.stdin.readline().rstrip()



def dijkstra(s, n, es,L):
    #n:頂点数, es: 辺uvのコスト
    d = [10**14+7] * n
    #探索リスト
    S = [(0,s)]
    #優先度付きキューを使うと計算量が少なくなるよ
    heapq.heapify(S)
    used = [False] *n

    d[s] = 0

    while S:
        #最小コストの頂点を取り出し
        dg, v = heapq.heappop(S)
        if used[v] ==True:
            continue
        used[v] =True
        for u, w in es[v]:
            if d[v]%L + w >L:
                cost = d[v] - d[v]%L +L +w
            else:
                cost =d[v]+w

            if d[u] > cost:
                d[u] = cost
                heapq.heappush(S, (d[u],u))


        # print("d", d)
    return d




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

    es = [[] for _ in range(N)]

    for i in range(M):
        x, y, z = map(int, input().split())
        x = x - 1
        y = y - 1
        es[x].append((y, z))
        es[y].append((x, z))  # 有向グラフの場合はこの行を消す

    answer = [[] for _ in range(N)]


    for i in range(N):
        d = dijkstra(i,N,es,L)
        answer[i] =d


    Q =int(input())
    for j in range(Q):
        s,t =map(int,input().split())
        a = answer[s-1][t-1]
        ans = a//L
        if a %L ==0:
            ans -=1
        if ans >10**14+7:
            ans(-1)
        else:
            print(ans)


if __name__ == "__main__":
    main()

# \n

Submission status: Wrong Answer

Solution code:
from functools import lru_cache
from collections import deque
import sys
input = sys.stdin.readline
inf = 1000

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

inf = 1000


def warshall_floyd(d):
    for k in range(1, n+1):
        for i in range(1, n+1):
            for j in range(1, n+1):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])


warshall_floyd(graph)

ans = [[inf] * (n+1) for _ in range(n+1)]
for i in range(1, n+1):
    for j in range(1, n+1):
        if graph[i][j] <= l:
            ans[i][j] = 1

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

Submission status: Wrong Answer

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

n, m, l = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append((b, c))
    graph[b].append((a, c))

inf = 1000
ans = [[inf] * (n+1) for _ in range(n+1)]
visited = [[False] * (n+1) for _ in range(n+1)]
for start in range(1, n+1):
    heap = []
    heapq.heappush(heap, [0, -l, start])
    ans[start][start] = 0
    while heap:
        t, fuel, now = heapq.heappop(heap)
        fuel *= -1
        # print(t, fuel, now)
        visited[start][now] = True
        ans[start][now] = t
        for node, cost in graph[now]:
            if visited[start][node]:
                continue

            tmp_fuel = fuel - cost
            if tmp_fuel < 0 and l >= cost:
                if ans[start][node] > t + 1:
                    heapq.heappush(heap, [t+1, -(l - cost), node])
                    ans[start][node] = t+1
            elif tmp_fuel < 0:
                pass
            else:
                if ans[start][node] > t:
                    heapq.heappush(heap, [t, -tmp_fuel, node])
                    ans[start][node] = t + 1
        visited[start][now] = True

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

Submission status: Wrong Answer

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

n, m, l = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append((b, c))
    graph[b].append((a, c))

inf = 1000
ans = [[inf] * (n+1) for _ in range(n+1)]
visited = [[False] * (n+1) for _ in range(n+1)]
for start in range(1, n+1):
    heap = []
    heapq.heappush(heap, [0, -l, start])
    ans[start][start] = 0
    while heap:
        t, fuel, now = heapq.heappop(heap)
        fuel *= -1
        # print(t, fuel, now)
        visited[start][now] = True
        ans[start][now] = t
        for node, cost in graph[now]:
            if visited[start][node]:
                continue

            tmp_fuel = fuel - cost
            if tmp_fuel < 0 and l >= cost:
                if ans[start][node] > t + 1:
                    heapq.heappush(heap, [t+1, -(l - cost), node])
                    ans[start][node] = t+1
            else:
                if ans[start][node] > t:
                    heapq.heappush(heap, [t, -tmp_fuel, node])
                    ans[start][node] = t + 1
        visited[start][now] = True

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

Submission status: Wrong Answer

Solution code:
import heapq
n, m, l = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append([b, c])
    graph[b].append([a, c])

inf = 1000
ans = [[inf] * (n+1) for _ in range(n+1)]
visited = [[False] * (n+1) for _ in range(n+1)]
for start in range(1, n+1):
    heap = []
    heapq.heappush(heap, [0, -l, start])
    ans[start][start] = 0
    while heap:
        t, fuel, now = heapq.heappop(heap)
        fuel *= -1
        print(t, fuel, now)
        visited[start][now] = True
        ans[start][now] = t
        for node, cost in graph[now]:
            if visited[start][node]:
                continue

            tmp_fuel = fuel - cost
            if tmp_fuel < 0 and l >= cost:
                if ans[start][node] > t + 1:
                    heapq.heappush(heap, [t+1, -(l - cost), node])
                    ans[start][node] = t+1
            else:
                if ans[start][node] > t:
                    heapq.heappush(heap, [t, -tmp_fuel, node])
                    ans[start][node] = t + 1
        visited[start][now] = True

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

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappush, heappop

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, L = map(int, readline().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, readline().split())
        if c > L:
            continue
        G[a - 1].append((b - 1, c))
        G[b - 1].append((a - 1, c))
    Q, *ST = map(int, read().split())

    dist = [[INF] * N for _ in range(N)]
    for i in range(N):
        dist[i][i] = 0
        hq = [(0, 0, i)]
        while hq:
            refuel, used, v = heappop(hq)
            if dist[i][v] < refuel:
                continue
            for nv, cost in G[v]:
                if used + cost <= L:
                    if dist[i][nv] > refuel:
                        dist[i][nv] = refuel
                        heappush(hq, (refuel, used + cost, nv))
                else:
                    if dist[i][nv] > refuel + 1:
                        dist[i][nv] = refuel + 1
                        heappush(hq, (refuel + 1, cost, nv))

    ans = [0] * Q
    for i, (s, t) in enumerate(zip(*[iter(ST)] * 2)):
        ans[i] = dist[s - 1][t - 1] if dist[s - 1][t - 1] != INF else -1

    print(*ans, sep='\n')
    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,m,l = ma()
INF=10**15
cost = [[-1]*n for i in range(n)]
tree = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma();a-=1;b-=1
    tree[a].append((c,b))
    tree[b].append((c,a))

def Dijkstra(graph,s):
    heap = [(0,s)] #スタートから距離が近い順に訪問
    rest = [INF]*n #休憩回数
    rest[s]=0
    fuels = [0]*n
    fuels[s]=l #たどりついた時の燃料
    while heap:
        cost,node = hq.heappop(heap)
        fuel = fuels[node]
        if cost>rest[node]:continue
        for w,nex in graph[node]:
            if fuel>=w:
                d=cost
                f=fuel-w
            else:
                if l<w:
                    d=INF*2
                    f=0
                else:
                    d=cost+1
                    f=l-w
            if d<rest[nex]:
                hq.heappush(heap,(d,nex))
                rest[nex]=d
                fuels[nex]=f
            elif d==rest[nex]:
                fuels[nex]=max(fuels[nex],f)
    #print(s,rest)
    return rest
q = ni()
for i in range(q):
    s,t = ma();s-=1;t-=1
    if s>t:s,t=t,s
    if cost[s][t]==-1:
        cost[s] = Dijkstra(tree,s)
    print(cost[s][t]) if cost[s][t] !=INF else print(-1)

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,m,l = ma()
INF=10**15
cost = [[-1]*n for i in range(n)]
tree = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma();a-=1;b-=1
    tree[a].append((c,b))
    tree[b].append((c,a))

def Dijkstra(graph,s):
    heap = [(0,l,s)] #スタートから距離が近い順に訪問
    rest = [INF]*n
    rest[s]=0
    while heap:
        cost,fuel,node = hq.heappop(heap)
        if cost>rest[node]:continue
        for w,nex in graph[node]:
            if fuel>=w:
                d=cost
                f=fuel-w
            else:
                if l<w:
                    d=INF*2
                    f=0
                else:
                    d=cost+1
                    f=l-w
            if d<rest[nex]:
                hq.heappush(heap,(d,f,nex))
                rest[nex]=d
    #print(s,rest)
    return rest
q = ni()
for i in range(q):
    s,t = ma();s-=1;t-=1
    if s>t:s,t=t,s
    if cost[s][t]==-1:
        cost[s] = Dijkstra(tree,s)

    print(cost[s][t]) if cost[s][t] !=INF else print(-1)

Submission status: Wrong Answer

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

N,M,L=map(int,input().split())
INF = 1 << 31
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0
  
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(dist)

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

dist = floyd_warshall(dist)
#dist[dist==INF]=0
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

for a in ans:
  print(-1 if a==INF else a)

Submission status: Wrong Answer

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

N,M,L=map(int,input().split())
INF = 1 << 60
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0
  
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(csr_matrix(dist))

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

dist = floyd_warshall(dist, directed=False)
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

if max(ans)==INF:
  print(-1)
else:
  print(*ans,sep='\n')

Submission status: Wrong Answer

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

N,M,L=map(int,input().split())
INF = 1 << 60
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0
  
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(csr_matrix(dist))

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

dist = floyd_warshall(csr_matrix(dist))
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

if max(ans)==INF:
  print(-1)
else:
  print(*ans,sep='\n')

Submission status: Wrong Answer

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

N,M,L=map(int,input().split())
INF = 1 << 60
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0
  
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(csr_matrix(dist))

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

dist = floyd_warshall(csr_matrix(dist))
#dist=dist.astype(int)
#print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

print(*ans,sep='\n')

Submission status: Wrong Answer

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

N,M,L=map(int,input().split())
INF = 1 << 60
dist=np.array([[INF for _ in range(N)] for _ in range(N)])

for i in range(N):
  dist[i][i]=0
  
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  dist[a][b]=c
  dist[b][a]=c

dist = floyd_warshall(csr_matrix(dist))

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

dist = floyd_warshall(csr_matrix(dist))
#dist=dist.astype(int)
print(dist)

Q=int(input())
ans=[0]*Q
for q in range(Q):
  s,t=map(int,input().split())
  s-=1
  t-=1
  ans[q]=int(dist[s][t]-1)

print(*ans,sep='\n')

Submission status: Wrong Answer

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

class djkstra:
  def __init__(self, N, L):
    self.__N = N
    self.__L = L
    self.__path = [[] for i in range(N)]
    
  def add_path(self,a, b, c):
    a -= 1
    b -= 1
    self.__path[a].append([b,c])
    self.__path[b].append([a,c])
    
  def solve(self, s, t):
    s -= 1
    t -= 1
    prev = [-1] * self.__N
    total = [float('inf')] * self.__N
    total[s] = 0
    rem = [i for i in range(self.__N)]
    while len(rem) > 0:
      now = [-1,float('inf')]
      for i in rem:
        if total[i] < now[1]:
          now[0] = i
          now[1] = total[i]
      if now[0] == -1:
        break
      rem.remove(now[0])
      next = [0,float('inf')]
      for i in self.__path[now[0]]:
        if i[0] in rem:
          if now[1] + i[1] < total[i[0]]:
            total[i[0]] = now[1] + i[1]
            prev[i[0]] = now[0]
    if total[t] == float('inf'):
      return -1
    else:
      res = []
      while prev[t] != -1:
        res.append(total[t] - total[prev[t]])
        t = prev[t]
      return res
    
class floyd:
  def __init__(self, N):
    self.__N = N
    self.__t = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
      self.__t[i][i] = 0
      
  def add_path(self, a, b, c):
    self.__t[a][b] = c
    self.__t[b][a] = c
  
  def make_table(self):
    for i in range(self.__N):
      for j in range(self.__N):
        for k in range(self.__N):
          self.__t[j][k] = min(self.__t[j][k], self.__t[j][i] + self.__t[i][k])
  def get_table(self):
    return self.__t
  def get_shortest_path(self,s,t):
    return self.__t[s][t]
  
def ans1():
  global N
  global M
  global L
  dj = djkstra(N, L)    
  for _ in range(M):
    a, b, c = map(int, input().split())
  if L > c:
    dj.add_path(a, b, c)
  
  for _ in range(int(input())):
    s, t = map(int, input().split())
    cost = dj.solve(s,t)
    if cost == -1:
      print(-1)
    else:
      res = 0
      rem_L = L
      for i in cost:
        if rem_L - i < 0:
          rem_L = L
          res += 1
        rem_L -= i
      print(res)
      
def ans2():
  global N
  global M
  global L
  f = floyd(N)
  f2 = floyd(N)
  for i in range(M):
    a, b, c = map(int, input().split())
    if L > c:
      f.add_path(a-1,b-1,c)
  f.make_table()
  t = f.get_table()
  for i in range(N):
    for j in range(N):
      if t[i][j] <= L:
        f2.add_path(i,j,1)
  f2.make_table()
  Q = int(input())
  for i in range(Q):
    s, t = map(int, input().split())
    temp = f2.get_shortest_path(s-1,t-1) - 1
    if temp == float('inf'):
      temp = -1
    print(temp)
  
  
ans2()

Submission status: Wrong Answer

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

class djkstra:
  def __init__(self, N, L):
    self.__N = N
    self.__L = L
    self.__path = [[] for i in range(N)]
    
  def add_path(self,a, b, c):
    a -= 1
    b -= 1
    self.__path[a].append([b,c])
    self.__path[b].append([a,c])
    
  def solve(self, s, t):
    s -= 1
    t -= 1
    prev = [-1] * self.__N
    total = [float('inf')] * self.__N
    total[s] = 0
    rem = [i for i in range(self.__N)]
    while len(rem) > 0:
      now = [-1,float('inf')]
      for i in rem:
        if total[i] < now[1]:
          now[0] = i
          now[1] = total[i]
      if now[0] == -1:
        break
      rem.remove(now[0])
      next = [0,float('inf')]
      for i in self.__path[now[0]]:
        if i[0] in rem:
          if now[1] + i[1] < total[i[0]]:
            total[i[0]] = now[1] + i[1]
            prev[i[0]] = now[0]
    if total[t] == float('inf'):
      return -1
    else:
      res = []
      while prev[t] != -1:
        res.append(total[t] - total[prev[t]])
        t = prev[t]
      return res
    
class floyd:
  def __init__(self, N):
    self.__N = N
    self.__t = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
      self.__t[i][i] = 0
      
  def add_path(self, a, b, c):
    self.__t[a][b] = c
    self.__t[b][a] = c
  
  def make_table(self):
    for i in range(self.__N):
      for j in range(self.__N):
        for k in range(self.__N):
          self.__t[j][k] = min(self.__t[j][k], self.__t[j][i] + self.__t[i][k])
  def get_table(self):
    return self.__t
  def get_shortest_path(self,s,t):
    return self.__t[s][t]
  
def ans1():
  global N
  global M
  global L
  dj = djkstra(N, L)    
  for _ in range(M):
    a, b, c = map(int, input().split())
  if L > c:
    dj.add_path(a, b, c)
  
  for _ in range(int(input())):
    s, t = map(int, input().split())
    cost = dj.solve(s,t)
    if cost == -1:
      print(-1)
    else:
      res = 0
      rem_L = L
      for i in cost:
        if rem_L - i < 0:
          rem_L = L
          res += 1
        rem_L -= i
      print(res)
      
def ans2():
  global N
  global M
  global L
  f = floyd(N)
  f2 = floyd(N)
  for i in range(M):
    a, b, c = map(int, input().split())
    if L > c:
      f.add_path(a-1,b-1,c)
  f.make_table()
  t = f.get_table()
  for i in range(N):
    for j in range(N):
      if t[i][j] <= L:
        f2.add_path(i,j,1)
  f2.make_table()
  Q = int(input())
  for i in range(Q):
    s, t = map(int, input().split())
    print(f2.get_shortest_path(s-1,t-1) - 1)
  
  
ans2()

Submission status: Wrong Answer

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

class djkstra:
  def __init__(self, N, L):
    self.__N = N
    self.__L = L
    self.__path = [[] for i in range(N)]
    
  def add_path(self,a, b, c):
    a -= 1
    b -= 1
    self.__path[a].append([b,c])
    self.__path[b].append([a,c])
    
  def solve(self, s, t):
    s -= 1
    t -= 1
    prev = [-1] * self.__N
    total = [float('inf')] * self.__N
    total[s] = 0
    rem = [i for i in range(self.__N)]
    while len(rem) > 0:
      now = [-1,float('inf')]
      for i in rem:
        if total[i] < now[1]:
          now[0] = i
          now[1] = total[i]
      if now[0] == -1:
        break
      rem.remove(now[0])
      next = [0,float('inf')]
      for i in self.__path[now[0]]:
        if i[0] in rem:
          if now[1] + i[1] < total[i[0]]:
            total[i[0]] = now[1] + i[1]
            prev[i[0]] = now[0]
    if total[t] == float('inf'):
      return -1
    else:
      res = []
      while prev[t] != -1:
        res.append(total[t] - total[prev[t]])
        t = prev[t]
      return res

dj = djkstra(N, L)    
for _ in range(M):
  a, b, c = map(int, input().split())
  if L > c:
    dj.add_path(a, b, c)
  
for _ in range(int(input())):
  s, t = map(int, input().split())
  cost = dj.solve(s,t)
  if cost == -1:
    print(-1)
  else:
    res = 0
    rem_L = L
    for i in cost:
      if rem_L - i < 0:
        rem_L = L
        res += 1
      rem_L -= i
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
from heapq import heappop, heappush
from collections import defaultdict
from collections import Counter
from collections import deque
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
N, M, L = map(int, input().split())
adj = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    if c > L:
        continue
    a -= 1
    b -= 1
    adj[a].append((c, b))
    adj[b].append((c, a))
Q = int(input())

def dijkstra(start):
    dist = [INF for _ in range(N)]
    path = [-1 for _ in range(N)]
    visited = [False for _ in range(N)] 
    q = [(0, start)]
    dist[start] = 0
    while len(q) > 0:
        v = heappop(q)
        a = v[1]
        if visited[a]:
            continue
        visited[a] = True
        for u in adj[a]:
            w = u[0]
            b = u[1]
            if dist[a] + w < dist[b]: 
                dist[b] = dist[a] + w
                heappush(q, (dist[b], b))
                path[b] = (a, w)
    return path

ps = [0] * N
for i in range(N):
    ps[i] = dijkstra(i)

for i in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    nx = t
    cur_path = []
    ok = True
    while nx != s:
        if ps[s][nx] == -1:
            ok = False
            break
        nx, w = ps[s][nx]
        cur_path.append(w)
    if not ok:
        print(-1)
        continue

    cur_path = list(reversed(cur_path))
    cur = L
    ans = 0
    i = 0
    n = len(cur_path)
    while i < n:
        cur -= cur_path[i]
        if i + 1 < n and cur - cur_path[i + 1] < 0:
            ans += 1
            cur = L
        i += 1
    print(ans)

Submission status: Wrong Answer

Solution code:

def warshall_floyd_rp(n, d):
    relay = [[-1] * n for _ in range(n)]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
                    relay[i][j] = k
    return relay

from collections import deque
def get_path_of_warhall_floyd(s, g, relay):
    if s == g:
        return [s]
    stack = deque()
    stack.append((s, g))
    path = []
    while stack:
        i, j = stack.pop()
        k = relay[i][j]
        if k >= 0:
            stack.append((i, k))
            stack.append((k, j))
        else:
            path.append(j)
    path.append(i)
    path.reverse()
    return path

n, m, l = map(int, input().split())
edges = []
weight = dict()
wf = [[float('inf')] * n for _ in range(n)]
for i in range(n):
    wf[i][i] = 0
for _ in range(m):
    a, b, w = map(int, input().split())
    if w <= l:
        weight[(a-1, b-1)] = w
        weight[(b-1, a-1)] = w
        wf[a-1][b-1] = w
        wf[b-1][a-1] = w
      
relay = warshall_floyd_rp(n, wf)

q = int(input())
ans = [0] * q
for i in range(q):
    s, t = map(lambda x:int(x) - 1, input().split())
    if wf[s][t] == float('inf'):
        ans[i] = -1
        continue
    path = get_path_of_warhall_floyd(s, t, relay)
    x = l
    ans[i] = 0
    for j in range(len(path) - 1):
        w = weight[(path[j], path[j+1])]
        if x < w:
            x = l
            ans[i] += 1
        x -= w
for x in ans:
    print(x)