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: Time Limit Exceeded

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

def main():
    INF = float("Inf")
    n,m,l = map(int, input().split())
    G = [[INF]*n for i in range(n)]
    for i in range(n):
        G[i][i] = 0
    for i in range(m):
        a,b,c = map(int, input().split())
        a,b = a-1,b-1
        if c <= l:
            G[a][b] = G[b][a] = c

    for k in range(n):
        for i in range(n):
            for j in range(n):
                if G[i][k]!=INF and G[k][j]!=INF:
                    G[i][j] = min(G[i][j], G[i][k] + G[k][j])

    #最短経路がL以下の部分について、edgeをつなぐ
    GG = [[INF]*n for i in range(n)]
    for i in range(n):
        for j in range(n):
            if i == j:
                GG[i][j] = 0
            else:
                if G[i][j] <= l:
                    GG[i][j] = 1

    for k in range(n):
        for i in range(n):
            for j in range(n):
                if GG[i][k]!=INF and GG[k][j]!=INF:
                    GG[i][j] = min(GG[i][j], GG[i][k] + GG[k][j])

    q = int(input())
    ans = []
    for i in range(q):
        s,t = map(int, input().split())
        a = GG[s-1][t-1]
        if a == INF:
            a = 0
        ans.append(a-1)
    print(*ans, sep="\n")

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

A=[[10**12 for i in range(N+1)]for j in range(N+1)]
B=[[10**12 for i in range(N+1)]for j in range(N+1)]
for i in range(M):
    a,b,c=map(int,input().split())
    if c<=L:
        A[a][b]=c
        A[b][a]=c
        B[a][b]=1
        B[b][a]=1
for i in range(N+1):
    A[i][i]=0
    B[i][i]=0   
#print(A)

for c in range(1,N+1):
    for a in range(1,N+1):
        for b in range(1,N+1):
            A[a][b]=min(A[a][b],A[a][c]+A[c][b])
            if A[a][b]<=L:
                B[a][b]=1
#print(A)
for c in range(1,N+1):
    for a in range(1,N+1):
        for b in range(1,N+1):
            B[a][b]=min(B[a][b],B[a][c]+B[c][b])

#print(B)
Q=int(input())
for i in range(Q):
    s,t=map(int,input().split())
    if B[s][t]==10**12:
        print(-1)
    else:
        print(B[s][t]-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq,sys
input = sys.stdin.readline
N,M,L = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
Q = int(input())
ST = [tuple(map(int,input().split())) for i in range(Q)]

es = [[] for i in range(N)]
for a,b,c in ABC:
    if c > L: continue
    a,b = a-1,b-1
    es[a].append((b,c))
    es[b].append((a,c))

INF = float('inf')
dist = [[INF]*N for i in range(N)]
for i in range(N):
    dist[i][i] = 0

for i in range(N):
    hq = [i]
    heapq.heapify(hq)
    while hq:
        v = heapq.heappop(hq)
        k,j = divmod(v,N)
        k,l = divmod(k,L)
        for to,c in es[j]:
            if l+c > L:
                newcost = (k+1)*L + c
            else:
                newcost = k*L + l + c
            if newcost < dist[i][to]:
                dist[i][to] = newcost
                heapq.heappush(hq, newcost*N + to)

ans = []
for s,t in ST:
    s,t = s-1,t-1
    if dist[s][t] == INF:
        ans.append(-1)
    else:
        ans.append((dist[s][t]-1)//L)
print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from heapq import heapify, heappush as hpush, heappop as hpop
N, M, L = map(int, input().split())
X = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    X[a-1].append([b-1, c])
    X[b-1].append([a-1, c])

def dijkstra(n, E, i0=0):
    h = [[0, i0]]
    D = [-1] * n
    done = [0] * n
    D[i0] = 0
    
    while h:
        d, i = hpop(h)
        done[i] = 1
        for j, w in E[i]:
            nd = d + w
            if D[j] < 0 or D[j] >= nd:
                if done[j] == 0:
                    hpush(h, [nd, j])
                    D[j] = nd
    return [d if d >= 0 else 1<<100 for d in D]
def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return [d if d >= 0 else 1<<100 for d in D]

Y = [[] for _ in range(N)]
for i in range(N):
    D1 = dijkstra(N, X, i)
    for j in range(N):
        if i == j: continue
        if D1[j] <= L:
            Y[i].append((j, 1))

# print("X =", X)
# print("Y =", Y)
D2 = []
for i in range(N):
    D2.append(dijkstra(N, Y, i))

ans = []
for _ in range(int(input())):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    a = D2[s][t]-1
    ans.append(str(a if a < 1 << 50 else -1))

print("\n".join(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M, L = map(int, input().split())
routes = [[] for i in range(N+1)]

for i in range(M):
    a, b, c = map(int, input().split())
    routes[a].append([b, c])
    routes[b].append([a, c])


def bfs(start, goal, full_energy):
    todo = deque([])
    for to, cost in routes[start]:
        if full_energy - cost >= 0:
            todo.append([to, full_energy-cost, 0])

    while todo:
        now, power, charge = todo.popleft()
        if now == goal:
            return charge

        for nex, cost in routes[now]:
            if power - cost >= 0:
                todo.appendleft([nex, power-cost, charge])
            todo.append([nex, full_energy-cost, charge+1])
    return -1


memo = [[-2]*(N+1) for i in range(N+1)]
Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    if memo[s][t] == -2:
        count = bfs(s, t, L)
        memo[s][t], memo[t][s] = count, count
    print(memo[s][t])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
import heapq
from collections import defaultdict
def main():
    N, M, L = map( int, input().split())
    d = defaultdict( int)
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        if c > L:
            continue
        a, b = a-1, b-1
        d[(a,b)] = c
        d[(b,a)] = c
        E[a].append(b)
        E[b].append(a)

    V = []
    for i in range(N):
        W = [-1]*N
        h = [(0,-L,i)]
        while h:
            t, g, v = heapq.heappop(h)
            if W[v] == -1:
                W[v] = t
                for w in E[v]:
                    if W[w] == -1:
                        if d[(v,w)] <= -g:
                            heapq.heappush(h, (t, g+d[(v,w)], w))
                        else:
                            heapq.heappush(h, (t+1, -L+d[(v,w)], w))
        V.append(W)
    Q = int( input())
    for _ in range(Q):
        s, t = map( int, input().split())
        print( V[s-1][t-1])
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from heapq import heapify, heappush as hpush, heappop as hpop
N, M, L = map(int, input().split())
X = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    X[a-1].append([b-1, c])
    X[b-1].append([a-1, c])

def dijkstra(n, E, i0=0):
    h = [[0, i0]]
    D = [-1] * n
    done = [0] * n
    D[i0] = 0
    
    while h:
        d, i = hpop(h)
        done[i] = 1
        for j, w in E[i]:
            nd = d + w
            if D[j] < 0 or D[j] >= nd:
                if done[j] == 0:
                    hpush(h, [nd, j])
                    D[j] = nd
    return [d if d >= 0 else 1<<100 for d in D]
def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return [d if d >= 0 else 1<<100 for d in D]

Y = [[] for _ in range(N)]
for i in range(N):
    D1 = dijkstra(N, X, i)
    for j in range(N):
        if i == j: continue
        if D1[j] <= L:
            Y[i].append(j)

D2 = []
for i in range(N):
    D2.append(BFS(N, Y, i))

ans = []
for _ in range(int(input())):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    a = D2[s][t]-1
    ans.append(str(a if a < 1 << 50 else -1))

print("\n".join(ans))

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int,input().split())
INF = (500, 10**9)
dist = [[INF for i in range(N)] for j in range(N)]
edge = [[] for i in range(N)]
for i in range(M):
	A,B,C = map(int,input().split())
	if C <= L:
		edge[A-1].append((B-1, C))
		edge[B-1].append((A-1, C))

import heapq as hq
for i in range(N):
	searched = [False for j in range(N)]
	search = [((0,0), i)]
	hq.heapify(search)
	while len(search) > 0:
		s = hq.heappop(search)
		d = s[0]
		n = s[1]
		if searched[n]:
			continue
		searched[n] = True
		dist[i][n] = d
		for e in edge[n]:
			n2 = e[0]
			d2 = e[1]
			if searched[n2]:
				continue
			if d[1] + d2 > L:
				new_d = (d[0] + 1, d2)
			else:
				new_d = (d[0], d[1] + d2)
			hq.heappush(search, (new_d, n2))

Q = int(input())
for q in range(Q):
	s,t = map(int,input().split())
	print(dist[s-1][t-1][0] if dist[s-1][t-1] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N,M,L = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
Q = int(input())
ST = [tuple(map(int,input().split())) for i in range(Q)]

es = [[] for i in range(N)]
for a,b,c in ABC:
    if c > L: continue
    a,b = a-1,b-1
    es[a].append((b,c))
    es[b].append((a,c))

INF = float('inf')
dist = [[INF]*N for i in range(N)]
for i in range(N):
    dist[i][i] = 0

for i in range(N):
    hq = [i]
    heapq.heapify(hq)
    while hq:
        v = heapq.heappop(hq)
        k,j = divmod(v,N)
        k,l = divmod(k,L)
        for to,c in es[j]:
            if l+c > L:
                newcost = (k+1)*L + c
            else:
                newcost = k*L + l + c
            if newcost < dist[i][to]:
                dist[i][to] = newcost
                heapq.heappush(hq, newcost*N + to)

for s,t in ST:
    s,t = s-1,t-1
    if dist[s][t] == INF:
        print(-1)
    else:
        print((dist[s][t]-1)//L)

Submission status: Time Limit Exceeded

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


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]

for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))

    
def dfs(start):
    INF = float("inf")
    visited_t = [INF]*n # 回数, 残り燃料
    visited_l = [0]*n
    visited_t[start] = 0
    prev = -1
    q = deque([(start, prev)])
    while q:
        pos, prev = q.popleft()
        for next_pos, cost in graph[pos]:
            if prev == next_pos:
                continue
            tmp = cost + visited_l[pos]
            times = visited_t[pos]
            next_times = visited_t[next_pos]
            if tmp <= l:
                if next_times > times:
                    q.append((next_pos, pos))
                    visited_t[next_pos] = times
                    visited_l[next_pos] = tmp
                elif next_times == times:
                    if visited_l[next_pos] > tmp:
                        q.append((next_pos, pos))
                        visited_t[next_pos] = times
                        visited_l[next_pos] = tmp
                else:
                    continue
            else:
                tmp = cost
                if next_times > times + 1:
                    q.append((next_pos, pos))
                    visited_t[next_pos] = times + 1
                    visited_l[next_pos] = tmp
                elif next_times == times + 1:
                    if visited_l[next_pos] > tmp:
                        q.append((next_pos, pos))
                        visited_t[next_pos] = times + 1
                        visited_l[next_pos] = tmp
                else:
                    continue
    return visited_t

ans = [None]*n
for i in range(n):
    ans[i] = dfs(i)

INF = float("inf")
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    tmp = ans[a][b]
    if tmp == INF:
        print(-1)
    else:
        print(tmp)

Submission status: Time Limit Exceeded

Solution code:
INF = float("Inf")
n,m,l = map(int, input().split())
G = [[INF]*n for i in range(n)]
for i in range(n):
    G[i][i] = 0
for i in range(m):
    a,b,c = map(int, input().split())
    a,b = a-1,b-1
    if c <= l:
        G[a][b] = G[b][a] = c

for k in range(n):
    for i in range(n):
        for j in range(n):
            if G[i][k]!=INF and G[k][j]!=INF:
                G[i][j] = min(G[i][j], G[i][k] + G[k][j])

#最短経路がL以下の部分について、edgeをつなぐ
GG = [[INF]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        if i == j:
            GG[i][j] = 0
        else:
            if G[i][j] <= l:
                GG[i][j] = 1

for k in range(n):
    for i in range(n):
        for j in range(n):
            if GG[i][k]!=INF and GG[k][j]!=INF:
                GG[i][j] = min(GG[i][j], GG[i][k] + GG[k][j])

q = int(input())
ans = []
for i in range(q):
    s,t = map(int, input().split())
    a = GG[s-1][t-1]
    if a == INF:
        a = 0
    ans.append(a-1)
print(*ans, sep="\n")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

input = sys.stdin.readline

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

g = tuple(set() for _ in range(n))
for _ in range(m):
    a, b, c = map(int, input().split())
    if c > max_tank:
        continue
    # 燃料不足で通過できない

    a -= 1
    b -= 1
    g[a].add((b, c))
    g[b].add((a, c))
    # 隣接リスト、(行き先、コスト)

inf = n + 10

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

    if not g[t]:
        print(-1)
        continue
    # ゴールに接続する辺がない場合

    d = [inf] * n
    remains = [0] * n

    d[s] = 0
    remains[s] = max_tank

    dq = deque()
    dq.append((s, max_tank, 0, -1))
    while dq:
        v, tank, take, parent = dq.popleft()
        if (d[v] < take) or (d[v] == take and remains[v] > tank):
            continue

        if v == t:
            break
            
        for u, c in g[v]:
            if u == parent:
                continue
            if c > tank:
                if (d[u] > take + 1) or (d[u] == take + 1 and remains[u] < max_tank - c):
                    d[u] = take + 1
                    remains[u] = max_tank - c
                    dq.append((u, max_tank - c, take + 1, v))
            else:
                if (d[u] > take) or (d[u] == take and remains[u] < tank - c):
                    d[u] = take
                    remains[u] = tank - c
                    dq.appendleft((u, tank - c, take, v))

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

Submission status: Time Limit Exceeded

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


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]

for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))

    
def dfs(start):
    INF = float("inf")
    visited_t = [INF]*n # 回数, 残り燃料
    visited_l = [0]*n
    visited_t[start] = 0
    q = deque([start])
    while q:
        pos = q.pop()
        for next_pos, cost in graph[pos]:
            tmp = cost + visited_l[pos]
            times = visited_t[pos]
            next_times = visited_t[next_pos]
            if tmp <= l:
                if next_times > times:
                    q.append(next_pos)
                    visited_t[next_pos] = times
                    visited_l[next_pos] = tmp
                elif next_times == times:
                    if visited_l[next_pos] > tmp:
                        q.append(next_pos)
                        visited_t[next_pos] = times
                        visited_l[next_pos] = tmp
                else:
                    continue
            else:
                tmp = cost
                if next_times > times + 1:
                    q.append(next_pos)
                    visited_t[next_pos] = times + 1
                    visited_l[next_pos] = tmp
                elif next_times == times + 1:
                    if visited_l[next_pos] > tmp:
                        q.append(next_pos)
                        visited_t[next_pos] = times + 1
                        visited_l[next_pos] = tmp
                else:
                    continue
    return visited_t

ans = [None]*n
for i in range(n):
    ans[i] = dfs(i)

INF = float("inf")
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    tmp = ans[a][b]
    if tmp == INF:
        print(-1)
    else:
        print(tmp)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N,M,L = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
Q = int(input())
ST = [tuple(map(int,input().split())) for i in range(Q)]

es = [[] for i in range(N)]
for a,b,c in ABC:
    if c > L: continue
    a,b = a-1,b-1
    es[a].append((b,c))
    es[b].append((a,c))

INF = float('inf')
dist = [[INF]*N for i in range(N)]
for i in range(N):
    dist[i][i] = 0

for i in range(N):
    hq = [(0,i)]
    heapq.heapify(hq)
    while hq:
        k,j = heapq.heappop(hq)
        k,l = divmod(k,L)
        for to,c in es[j]:
            if l+c > L:
                newcost = (k+1)*L + c
            else:
                newcost = k*L + l + c
            if newcost < dist[i][to]:
                dist[i][to] = newcost
                heapq.heappush(hq, (newcost, to))

for s,t in ST:
    s,t = s-1,t-1
    if dist[s][t] == INF:
        print(-1)
    else:
        print((dist[s][t]-1)//L)

Submission status: Time Limit Exceeded

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


def main():
    N, M, L = map(int, input().split())
    INF = 10**13
    dis = [[INF for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        dis[a-1][b-1] = c
        dis[b-1][a-1] = c
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    for k in range(N):
        for i in range(N):
            for j in range(N):
                dis[i][j] = min(dis[i][j], dis[i][k]+dis[k][j])
    
    movable = [[] for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if i != j and dis[i][j] <= L:
                movable[i].append(j)
    

    for s, t in Query:
        s, t = s-1, t-1
        q = movable[s]
        checked = [False]*N
        ok = False
        for p in q:
            if p == t:
                ok = True
            checked[p] = True
        checked[s] = True
        
        if ok:
            print(0)
            continue
        c = 0
        while q:
            c += 1
            qq = []
            for p in q:
                for np in movable[p]:
                    if np == t:
                        ok = True
                        break
                    if not checked[np]:
                        qq.append(np)
                        checked[np] = True
            if ok: break
            q = qq
        if ok:
            print(c)
        else:
            print(-1)



            



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]

for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))

    
def dfs(start):
    INF = float("inf")
    visited_t = [INF]*n # 回数, 残り燃料
    visited_l = [0]*n
    visited_t[start] = 0
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, cost in graph[pos]:
            tmp = cost + visited_l[pos]
            times = visited_t[pos]
            next_times = visited_t[next_pos]
            if tmp <= l:
                if next_times > times:
                    q.append(next_pos)
                    visited_t[next_pos] = times
                    visited_l[next_pos] = tmp
                elif next_times == times:
                    if visited_l[next_pos] > tmp:
                        q.append(next_pos)
                        visited_t[next_pos] = times
                        visited_l[next_pos] = tmp
                else:
                    continue
            else:
                tmp = cost
                if next_times > times + 1:
                    q.append(next_pos)
                    visited_t[next_pos] = times + 1
                    visited_l[next_pos] = tmp
                elif next_times == times + 1:
                    if visited_l[next_pos] > tmp:
                        q.append(next_pos)
                        visited_t[next_pos] = times + 1
                        visited_l[next_pos] = tmp
                else:
                    continue
    return visited_t

ans = [None]*n
for i in range(n):
    ans[i] = dfs(i)

INF = float("inf")
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    tmp = ans[a][b]
    if tmp == INF:
        print(-1)
    else:
        print(tmp)

Submission status: Time Limit Exceeded

Solution code:
nm = lambda : map(int,input().split())
nl = lambda : list(nm())
import heapq as h

n,m,l = nm()
se = set()
g = [list() for _ in range(n+1)]
ans = dict()
for _ in range(m):
    a,b,c = nm()
    g[a].append((b,c))
    g[b].append((a,c))
q = int(input())
query = list()
for _ in range(q):
  s,t = nm()
  if s > t:
    s,t = t,s
  se.add(s)
  query.append((s,t))
  


def move(tup,cost):
    if tup[1] + cost > 0:
        if l < cost:
            return -1
        return (tup[0]+1,cost-l)
    return (tup[0],tup[1]+cost)

for st in se:
    dist = [-1]*(n+1)
    que = [((0,-l),st)]
    while que:
        tup,v = h.heappop(que)
        if dist[v] != -1 and dist[v] < tup:
            continue
        dist[v] = tup
        for x,c in g[v]:
            if dist[x] != -1:
               continue
            new = move(tup,c)
            if new != -1:
                h.heappush(que,(new,x))
    ans[st] = dist

for s,t in query:
    if ans[s][t] == -1:
        print(-1)
    else:
        print(ans[s][t][0])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M, L = map(int, input().split())
routes = [[] for i in range(N+1)]

for i in range(M):
    a, b, c = map(int, input().split())
    routes[a].append([b, c])
    routes[b].append([a, c])


def bfs(start, goal, full_energy):
    todo = deque([])
    for to, cost in routes[start]:
        if full_energy - cost >= 0:
            todo.append([to, full_energy-cost, 0])

    while todo:
        now, power, charge = todo.popleft()
        if now == goal:
            return charge

        for nex, cost in routes[now]:
            if power - cost >= 0:
                todo.appendleft([nex, power-cost, charge])
            todo.append([nex, full_energy-cost, charge+1])
    return -1


Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    print(bfs(s, t, L))

Submission status: Time Limit Exceeded

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

roads = [[None] * N for _ in range(N)]
for _ in range(M):
	a, b, c = map(int, input().strip().split())
	a -= 1
	b -= 1
	roads[a][b] = c
	roads[b][a] = c

reachable = []
def find_reachable(t):
	queue = [t]
	dists = [None] * N
	dists[t] = 0
	while queue:
		cur = queue.pop()
		dist = dists[cur]
		for nxt in range(N):
			d = roads[cur][nxt]
			if d != None:
				d += dist
				if d <= L:
					if dists[nxt] == None or dists[nxt] > d:
						dists[nxt] = d
						queue.append(nxt)
	col = []
	for i in range(N):
		if i != t and dists[i] != None:
			col.append(True)
		else:
			col.append(False)
	reachable.append(col)

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

Q = int(input())

def find_route(s, t):
	queue = [s]
	dists = [None] * N
	dists[s] = 0
	while queue:
		cur = queue.pop(0)
		dist = dists[cur] + 1
		col = reachable[cur]
		for nxt in range(N):
			if col[nxt]:
				if nxt == t:
					return dist - 1
				if dists[nxt] == None:
					dists[nxt] = dist
					queue.append(nxt)
	return None

for _ in range(Q):
	s, t = map(int, input().strip().split())
	s -= 1
	t -= 1
	dist = find_route(s, t)
	if dist != None:
		print(dist)
	else:
		print("-1")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M,L = map(int,input().split())
load = [[]for i in range(N)]
for i in range(M):
    a,b,c = map(int,input().split())
    if c > L:
        continue
    load[a-1].append([b-1,c])
    load[b-1].append([a-1,c])
cost =[[float('inf')]*N for i in range(N)]
for i in range(N):
    queue = deque([i])
    cost[i][i] = 0
    while(queue):
        q = queue.popleft()
        gas = cost[i][q]
        for t,c in load[q]:
            if gas//L < (gas+c-1)//L :
                if (gas//L+1)*L+c < cost[i][t]:
                    cost[i][t] = (gas//L+1)*L+c
                    queue.append(t)
            else:
                if gas+c < cost[i][t]:
                    cost[i][t] = gas+c
                    queue.append(t)
Q = int(input())
for i in range(Q):
    s,t = map(int,input().split())
    ans = cost[s-1][t-1]
    if ans == float('inf'):
        print(-1)
    else:
        print((ans-1)//L)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from heapq import heapify, heappush as hpush, heappop as hpop
N, M, L = map(int, input().split())
X = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    X[a-1].append([b-1, c])
    X[b-1].append([a-1, c])

def dijkstra(n, E, i0=0):
    h = [[0, i0]]
    D = [-1] * n
    done = [0] * n
    D[i0] = 0
    
    while h:
        d, i = hpop(h)
        done[i] = 1
        for j, w in E[i]:
            nd = d + w
            if D[j] < 0 or D[j] >= nd:
                if done[j] == 0:
                    hpush(h, [nd, j])
                    D[j] = nd
    return [d if d >= 0 else 1<<100 for d in D]
def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return [d if d >= 0 else 1<<100 for d in D]

Y = [[] for _ in range(N)]
for i in range(N):
    D1 = dijkstra(N, X, i)
    for j in range(N):
        if i == j: continue
        if D1[j] <= L:
            Y[i].append(j)

ans = []
for _ in range(int(input())):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    a = BFS(N, Y, s)[t]-1
    ans.append(str(a if a < 1 << 50 else -1))

print("\n".join(ans))

Submission status: Time Limit Exceeded

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


n, m, l = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]

for i in range(m):
    a, b, cost = info[i]
    if cost > l:
        continue
    a -= 1
    b -= 1
    graph[a].append((b, cost))
    graph[b].append((a, cost))

    
def dfs(start):
    INF = float("inf")
    visited = [[INF, 0] for i in range(n)] # 回数, 残り燃料
    visited[start] = [0, 0]
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, cost in graph[pos]:
            tmp = cost + visited[pos][1]
            times = visited[pos][0]
            next_times = visited[next_pos][0]
            if tmp <= l:
                if next_times > times:
                    q.append(next_pos)
                    visited[next_pos] = [times, tmp]
                elif next_times == times:
                    if visited[next_pos][1] > tmp:
                        q.append(next_pos)
                        visited[next_pos] = [times, tmp]
                else:
                    continue
            else:
                tmp = cost
                if next_times > times + 1:
                    q.append(next_pos)
                    visited[next_pos] = [times + 1, tmp]
                elif next_times == times + 1:
                    if visited[next_pos][1] > tmp:
                        q.append(next_pos)
                        visited[next_pos] = [times + 1, tmp]
                else:
                    continue
    res = [0] * n
    for i in range(n):
        res[i] = visited[i][0]
    return res

ans = [None]*n
for i in range(n):
    ans[i] = dfs(i)

INF = float("inf")
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]
for i in range(q):
    a, b = query[i]
    a -= 1
    b -= 1
    tmp = ans[a][b]
    if tmp == INF:
        print(-1)
    else:
        print(tmp)