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
input = sys.stdin.readline

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

INF = float("INF")

d = [[INF] * n for _ in range(n)]
for i in range(n):
    d[i][i] = 0

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

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]

# print()
# print(*d, sep='\n')

for i in range(n):
    for j in range(n):
        if i == j:
            continue

        if d[i][j] <= l:
            d[i][j] = 1

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]

# print()
# print(*d, sep='\n')

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

    if d[s][t] == INF:
        print(-1)
    else:
        print(d[s][t]-1)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappop, heappush


def dijkstra(s, links):
    q = [(0, -l, s)]
    ret = [-1] * n
    visited = set()
    while q:
        count, remain, v = heappop(q)
        if v in visited:
            continue
        visited.add(v)
        ret[v] = count
        remain = -remain
        for u, c in links[v]:
            if remain < c:
                heappush(q, (count + 1, c - l, u))
            else:
                heappush(q, (count, c - remain, u))
    return ret


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

links = [set() for _ in range(n)]

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add((b, c))
    links[b].add((a, c))

ans = [dijkstra(v, links) for v in range(n)]
buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(ans[s - 1][t - 1])

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

Submission status: Wrong Answer

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

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

INF = 10 ** 10

d = [[INF] * n for _ in range(n)]
for i in range(n):
    d[i][i] = 0

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

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]

# print()
# print(*d, sep='\n')

for i in range(n):
    for j in range(n):
        if i == j:
            continue

        if d[i][j] <= l:
            d[i][j] = 1

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]

# print()
# print(*d, sep='\n')

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

    if d[s][t] == INF:
        print(-1)
    else:
        print(d[s][t]-1)

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()
    d = [[0 if i == j else float("inf") for j in range(n)] for i in range(n)]
    pre = [[None]*n for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        d[a][b] = c
        pre[a][b] = a
        d[b][a] = c
        pre[b][a] = b
    for k in range(n):
        for i in range(n):
            for j in range(n):
                nd = d[i][k]+d[k][j]
                if nd < d[i][j]:
                    d[i][j] = nd
                    pre[i][j] = pre[k][j]
    q = I()
    for _ in range(q):
        s,t = LI()
        s -= 1
        t -= 1
        ds = d[s][t]
        if ds == float("inf"):
            print(-1)
        else:
            x = s
            q = l
            ans = 0
            while x != t:
                y = pre[t][x]
                if d[x][y] > q:
                    if d[x][y] > l:
                        ans = -1
                        break
                    ans += 1
                    q = l
                q -= d[x][y]
                x = y
            print(ans)
    return

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

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()
    d = [[0 if i == j else float("inf") for j in range(n)] for i in range(n)]
    pre = [[None]*n for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        d[a][b] = c
        pre[a][b] = a
        d[b][a] = c
        pre[b][a] = b
    for k in range(n):
        for i in range(n):
            for j in range(n):
                nd = d[i][k]+d[k][j]
                if nd < d[i][j]:
                    d[i][j] = nd
                    pre[i][j] = pre[k][j]
    q = I()
    for _ in range(q):
        s,t = LI()
        s -= 1
        t -= 1
        ds = d[s][t]
        if ds == float("inf"):
            print(-1)
        else:
            x = t
            q = l
            ans = 0
            while x != s:
                y = pre[s][x]
                if d[x][y] > q:
                    if d[x][y] > l:
                        ans = -1
                        break
                    ans += 1
                    q = l
                q -= d[x][y]
                x = y
            print(ans)
    return

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

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappop, heappush


def dijkstra(s, links):
    q = [(0, -l, s)]
    ret = [-1] * n
    visited = set()
    while q:
        count, remain, v = heappop(q)
        if v in visited:
            continue
        visited.add(v)
        ret[v] = count
        remain = -remain
        for u, c in links[v]:
            if remain < c:
                heappush(q, (count + 1, c - l, u))
            else:
                heappush(q, (count, c - remain, u))
    return ret


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

links = [set() for _ in range(n)]

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add((b, c))
    links[b].add((a, c))

ans = [dijkstra(v, links) for v in range(n)]
buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(ans[s - 1][t - 1])

print(*buf)

Submission status: Time Limit Exceeded

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,d))
        G[t].append((s,d))

INF=V+5

res=[[(INF,0)]*(V+1) for _ in  [0]*(V+1)]

for start in range(1,V+1):
    q=[((0,0),start)]
    while q:
        c,town=heapq.heappop(q)
        if res[start][town]<c:
            continue
        h,cost=c
        for next_town,d in G[town]:
            D=cost+d
            if D<=L and (h,D)<res[start][next_town]:
                heapq.heappush(q,((h,D),next_town))
                res[start][next_town]=(h,D)
            elif D>L and (1+h,d)<res[start][next_town]:
                heapq.heappush(q,((1+h,d),next_town))
                res[start][next_town]=(1+h,d)

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

Submission status: Time Limit Exceeded

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,d))
        G[t].append((s,d))

INF=V+5

res=[[(INF,0)]*(V+1) for _ in  [0]*(V+1)]

for start in range(1,V+1):
    q=[((0,0),start)]
    while q:
        c,town=heapq.heappop(q)
        if c<res[start][town]:
            res[start][town]=c
        else:
            continue
        h,cost=c
        for next_town,d in G[town]:
            D=cost+d
            if D<=L and (h,D)<res[start][next_town]:
                heapq.heappush(q,((h,D),next_town))
            elif D>L and (1+h,d)<res[start][next_town]:
                heapq.heappush(q,((1+h,d),next_town))

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

Submission status: Time Limit Exceeded

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=V+5

res=[[(INF,0)]*(V+1) for _ in  [0]*(V+1)]

for s in range(V):
    # q[i]:点i+1の現状のコスト
    q=[((0,0),s+1)]
    heapq.heapify(q)
    while q:
        C,p=heapq.heappop(q)
        if C<res[s+1][p]:
            res[s+1][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[s+1][np],costB),np))



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

Submission status: Time Limit Exceeded

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=[(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]:
            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: Time Limit Exceeded

Solution code:
import heapq
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=[(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]:
            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: Time Limit Exceeded

Solution code:
import heapq
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=float('inf')

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

    res=[(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]:
            costA=res[np]
            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(costA,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: Time Limit Exceeded

Solution code:
import heapq
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=float('inf')

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

    res=[(INF,INF)]*(V+1)
    while q:
        C,p=heapq.heappop(q)
        if C<res[p]:
            res[p]=C
        else:
            continue
        if p==t:
            break
        for np,D in G[p]:
            costA=res[np]
            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(costA,costB),np))
    return res[t][0] if res[t][0]<INF else -1

Q=int(input())
for _ in [0]*Q:
    s,t=f()
    print(dijk(s,t))

Submission status: Time Limit Exceeded

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())
        if z >L:
            continue
            
        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 a ==10**14+7:
            print(-1)
        else:
            print(ans)


if __name__ == "__main__":
    main()

# \n

Submission status: Time Limit Exceeded

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, INF)] * N for _ in range(N)]
    for i in range(N):
        dist[i][i] = (0, 0)
        hq = [(0, 0, i)]
        while hq:
            refuel, used, v = heappop(hq)
            if dist[i][v] < (refuel, used):
                continue
            for nv, cost in G[v]:
                if used + cost <= L:
                    if dist[i][nv] > (refuel, used + cost):
                        dist[i][nv] = (refuel, used + cost)
                        heappush(hq, (refuel, used + cost, nv))
                else:
                    if dist[i][nv] > (refuel + 1, cost):
                        dist[i][nv] = (refuel + 1, cost)
                        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][0] if dist[s - 1][t - 1][0] != INF else -1

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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:
                rest[nex]=min(cost,rest[nex])
                hq.heappush(heap,(cost,fuel-w,nex))
            else:
                if l<w:
                    pass
                else:
                    rest[nex]=min(cost+1,rest[nex])
                    hq.heappush(heap,(cost+1,l-w,nex))
    #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: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq


def wf(d,n):
    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

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N,M,L = LI()
    road = [[INF] * N for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        if c <= L:
            road[a-1][b-1] = c
            road[b-1][a-1] = c

    road = wf(road,N)


    gas = [[INF] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if road[i][j] <= L:
                gas[i][j] = 1

    gas = wf(gas,N)

    Q = NI()
    for _ in range(Q):
        s,t = LI()
        if gas[s-1][t-1] == INF:
            print(-1)
        else:
            print(gas[s-1][t-1]-1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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())
dist = [[INF] * N for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    if c > L:
        continue
    a -= 1
    b -= 1
    dist[a][b] = c
    dist[b][a] = c
Q = int(input())

for k in range(N):
    for i in range(N):
        for j in range(N):
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
fuel = [[INF] * N for _ in range(N)]
for i in range(N):
    for j in range(N):
        fuel[i][j] = 1 if dist[i][j] <= L else INF
for k in range(N):
    for i in range(N):
        for j in range(N):
            fuel[i][j] = min(fuel[i][j], fuel[i][k] + fuel[k][j])
for i in range(Q):
    s,t = map(int, input().split())
    if fuel[s - 1][t - 1] != INF:
        print(fuel[s - 1][t - 1] - 1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify, heappop, heappush
from collections import deque
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split()); INF = float("inf")
G = [[] for _ in range(N)]
#P = [[] for _ in range(N)]
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #0index
  if c > L: #この道は通れない
    continue
  G[a].append((c,b));G[b].append((c,a))
base = 1000
#print(G)
R = [] #L以下でいける道のリスト
for i in range(N): #ダイクストラ法
  reach = [INF for _ in range(N)]
  reach[i] = 0
  Q = []; possible = []
  for e in G[i]:
    if e[0] <= L:
      possible.append(e[1])
      pseudo = e[0] * base + e[1]
      heappush(Q,pseudo) #始点iからのコスト*base+今いる点
  #print(Q)
  while Q:
    temp = heappop(Q)
    cost = temp//base
    v = temp%base
    if cost > L: #燃料Lを超えるならスキップ
      continue
    reach[v] = cost
    for x in G[v]:
      fuel, u = x
      if reach[u] < cost + fuel: #すでに到達済みならスキップ
        continue
      if cost + fuel > L: #燃料Lを超えるならスキップ
        continue
      pseudo = (cost+fuel)*base+u
      possible.append(u)
      heappush(Q,pseudo)
  #possible.sort()
  #possible = set(possible)
  R.append(possible)
#print(R)
Query = int(input())
for i in range(Query): #BFS
  start,goal = map(int,input().split())
  start-=1;goal-=1
  visit = [INF for _ in range(N)]
  visit[start] = -1 #最初は満タンで一回移動で0なので-1スタート
  HQ = deque([]); HQ.append(start)
  Flag = False
  while HQ and not Flag:
    now = HQ.popleft()
    step = visit[now]
    for nxt in R[now]:
      if visit[nxt] != INF:
        continue
      visit[nxt] = step+1
      if nxt == goal:
        ans = visit[nxt];Flag = True
        print(ans)
        break
      HQ.append(nxt)
  if visit[goal] == INF:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify, heappop, heappush
from collections import deque
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split()); INF = float("inf")
G = [[] for _ in range(N)]
#P = [[] for _ in range(N)]
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #0index
  if c > L: #この道は通れない
    continue
  G[a].append((c,b));G[b].append((c,a))
base = 1000
#print(G)
R = [] #L以下でいける道のリスト
for i in range(N): #ダイクストラ法
  reach = [INF for _ in range(N)]
  reach[i] = 0
  Q = []; possible = []
  for e in G[i]:
    if e[0] <= L:
      possible.append(e[1])
      pseudo = e[0] * base + e[1]
      heappush(Q,pseudo) #始点iからのコスト*base+今いる点
  #print(Q)
  while Q:
    temp = heappop(Q)
    cost = temp//base
    v = temp%base
    if cost > L: #燃料Lを超えるならスキップ
      continue
    reach[v] = cost
    for x in G[v]:
      fuel, u = x
      if reach[u] < cost + fuel: #すでに到達済みならスキップ
        continue
      if cost + fuel > L: #燃料Lを超えるならスキップ
        continue
      pseudo = (cost+fuel)*base+u
      possible.append(u)
      heappush(Q,pseudo)
  possible.sort()
  #possible = set(possible)
  R.append(possible)
#print(R)
Query = int(input())
for i in range(Query): #BFS
  start,goal = map(int,input().split())
  start-=1;goal-=1
  visit = [INF for _ in range(N)]
  visit[start] = -1 #最初は満タンで一回移動で0なので-1スタート
  HQ = deque([]); HQ.append(start)
  Flag = False
  while HQ and not Flag:
    now = HQ.popleft()
    step = visit[now]
    for nxt in R[now]:
      if visit[nxt] != INF:
        continue
      visit[nxt] = step+1
      if nxt == goal:
        ans = visit[nxt];Flag = True
        print(ans)
        break
      HQ.append(nxt)
  if visit[goal] == INF:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import copy
from heapq import heapify, heappop, heappush
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split()); INF = float("inf")
G = [[INF]*N for _ in range(N)]
#P = [[] for _ in range(N)]
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #0index
  if c > L: #この道は通れない
    continue
  G[a][b]=c; G[b][a]=c
  
#print(G)
#R = copy.copy(G) #L以下でいける道のリスト
for k in range(N):
  for i in range(N):
    for j in range(N):
      G[i][j] = min(G[i][j], G[i][k] + G[k][j])
R = [[INF]*N for _ in range(N)]
for i in range(N):
  for j in range(N):
    if G[i][j] <= L:
      R[i][j] = 1
      
#print(R)
Query = int(input())
for _ in range(Query):
  start,goal = map(int,input().split())
  start-=1;goal-=1
  d = copy.copy(R)
  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])
  ans = d[start][goal]
  if ans == INF:
    print(-1)
  else:
    print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
import copy
from heapq import heapify, heappop, heappush
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split()); INF = float("inf")
G = [[] for _ in range(N)]
#P = [[] for _ in range(N)]
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #0index
  if c > L: #この道は通れない
    continue
  G[a].append((c,b));G[b].append((c,a))
  
#print(G)
R = [[INF]*N for _ in range(N)] #L以下でいける道のリスト
for i in range(N):
  reach = [INF for _ in range(N)]
  reach[i] = 0
  R[i][i] = 1
  Q = []
  heappush(Q,(0,i)) #始点iからのコストと今いる点
  possible = []
  while Q:
    cost, v = heappop(Q)
    if cost + reach[i] > L: #燃料Lを超えるならスキップ
      continue
    for x in G[v]:
      fuel, u = x
      if reach[u] != INF: #すでに到達済みならスキップ
        continue
      if cost + fuel > L: #燃料Lを超えるならスキップ
        continue
      R[i][u] = 1
      Q.append((cost+fuel,u))
  R.append(possible)
#print(R)
Query = int(input())
for _ in range(Query):
  start,goal = map(int,input().split())
  start-=1;goal-=1
  d = copy.copy(R)
  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])
  ans = d[start][goal]
  if ans == INF:
    print(-1)
  else:
    print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m,l = inpl()
d = [[INF]*n for _ in range(n)]
for _ in range(m):
    a,b,c = inpl()
    d[a-1][b-1] = c
    d[b-1][a-1] = c
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])
e = [[INF]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            e[i][j] = 1

for k in range(n):
    for i in range(n):
        for j in range(n):
            e[i][j] = min(e[i][j], e[i][k]+e[k][j])
q = inp()
for _ in range(q):
    a,b = inpl()
    ans = e[a-1][b-1]
    print(-1 if ans == INF else ans-1)

Submission status: Time Limit Exceeded

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

INF = 1 << 30
g = [[INF] * n for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    g[a][b] = c
    g[b][a] = c

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

h = [[INF] * n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if g[i][j] <= l:
            h[i][j] = 1

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

q = int(input())
for _ in range(q):
    s, t = map(lambda x: int(x) - 1, input().split())
    if h[s][t] == INF:
        print(-1)
    else:
        print(h[s][t] - 1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify, heappop, heappush
from collections import deque
N,M,L = map(int,input().split()); INF = float("inf")
G = [[] for _ in range(N)]
#P = [[] for _ in range(N)]
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #0index
  if c > L: #この道は通れない
    continue
  G[a].append((c,b));G[b].append((c,a))
  
#print(G)
R = [] #L以下でいける道のリスト
for i in range(N):
  reach = [INF for _ in range(N)]
  reach[i] = 0
  Q = []
  heappush(Q,(0,i)) #始点iからのコストと今いる点
  possible = []
  while Q:
    cost, v = heappop(Q)
    if cost + reach[i] > L: #燃料Lを超えるならスキップ
      continue
    for x in G[v]:
      fuel, u = x
      if reach[u] != INF: #すでに到達済みならスキップ
        continue
      if cost + fuel > L: #燃料Lを超えるならスキップ
        continue
      possible.append(u)
      Q.append((cost+fuel,u))
  R.append(possible)
#print(R)
Query = int(input())
for i in range(Query):
  start,goal = map(int,input().split())
  start-=1;goal-=1
  visit = [INF for _ in range(N)]
  visit[start] = -1 #最初は満タンで一回移動で0なので-1スタート
  HQ = deque([]); HQ.append(start)
  Flag = False
  while HQ and not Flag:
    now = HQ.popleft()
    for nxt in R[now]:
      if visit[nxt] == INF:
        visit[nxt] = visit[now]+1
        if nxt == goal:
          ans = visit[nxt];Flag = True
          break
        HQ.append(nxt)
  if visit[goal] == INF:
    ans = -1
  print(ans)