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:
from heapq import *
INF = 1e10
respostas = []

def floyd(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])

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

d = [[INF]*N for i in range(N)]

for x in range(M):
    a,b,w = map(int,input().split())
    d[a-1][b-1] = w
    d[b-1][a-1] = w
    d[a-1][a-1] = 0
    d[b-1][b-1] = 0


floyd(N)
grafo2 = [[INF] * N for i in range(N)]

for x in range(len(d)):
    for y in range(len(d[x])) :
        if d[x][y] <= L:
            grafo2[x][y] = 1
            grafo2[y][x] = 1



for k in range(N):
    for i in range(N):
        for j in range(N):
            grafo2[i][j] = min(grafo2[i][j], grafo2[i][k] + grafo2[k][j])

query = int(input())

for x in range(query):
    s,t = map(int,input().split())
    if grafo2[s-1][t-1] == INF:
        respostas.append(-1)
    else:
        respostas.append(grafo2[s-1][t-1] - 1)

for x in respostas:
    print(x)

Submission status: Time Limit Exceeded

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

inf=10**10

d=[[inf]*n for _ in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split(' '))
    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):
            if d[i][j] > d[i][k] + d[k][j]:
                d[i][j] = d[i][k] + d[k][j]
                
dl=[[inf]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= L:
            dl[i][j]=1

for k in range(n):
    for i in range(n):
        for j in range(n):
            if dl[i][j] > dl[i][k] + dl[k][j]:
                dl[i][j] = dl[i][k] + dl[k][j]

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

Submission status: Time Limit Exceeded

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

d=[[float('inf')]*n for _ in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split(' '))
    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):
            if d[i][j] > d[i][k] + d[k][j]:
                d[i][j] = d[i][k] + d[k][j]
                
dl=[[float('inf')]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if d[i][j] <= L:
            dl[i][j]=1

for k in range(n):
    for i in range(n):
        for j in range(n):
            if dl[i][j] > dl[i][k] + dl[k][j]:
                dl[i][j] = dl[i][k] + dl[k][j]

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

Submission status: Time Limit Exceeded

Solution code:
INF=10**15

class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self,s):

        import heapq
        que=[]
        D=[INF*(L+1)+L] * self.V
        D[s]=0
        heapq.heappush(que,(0,s))

        while len(que)!=0:
            cost,v=heapq.heappop(que)

            if cost>D[v]:
                continue

            for i in range(len(self.G[v])):
                e=self.G[v][i]
                a=D[e.to]
                nokori=L-cost%(L+1)
                if nokori>=e.cost:
                    new=cost+e.cost
                else:
                    new=(cost//(L+1)+1)*(L+1)+e.cost
                if a>new:
                    D[e.to]=new
                    heapq.heappush(que,(D[e.to],e.to))

        return D

import sys

input=sys.stdin.readline

N,M,L=map(int,input().split())
city=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    if L>=c:
        city.add(a-1,b-1,c)
        city.add(b-1,a-1,c)

ans=[city.shortest_path(i) for i in range(0,N)]

Q=int(input())
for i in range(0,Q):
    s,t=map(int,input().split())
    if ans[s-1][t-1]!=INF*(L+1)+L:
        print(ans[s-1][t-1]//(L+1))
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
INF = 10**10

def warshall_floyd(d):
    # d[i][j]: ij間の最小コスト
    # i=jのとき0, i!=jのときINFで初期化
    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

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

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

Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1; t -= 1
    if dist2[s][t] == INF:
        print(-1)
    else:
        print(dist2[s][t]-1)

Submission status: Time Limit Exceeded

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


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める"""
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    q = deque([start])
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    while q:
        v = q.popleft()
        d = dist[v]
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                q.append(nxt_v)
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

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


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    q = [start]
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    while q:
        v = q.pop()
        d = dist[v]
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                q.append(nxt_v)
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

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


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    q = [(0, start)] # q = [(d, 現在地)]
    while q:
        d, v = q.pop()
        if dist[v] < d:
            continue
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                q.append((dist[nxt_v], nxt_v))
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

    n,m,l = map(int, input().split())
    edge = [[] for i in range(n)]
    #edge[i] : iから出る道の[重み,行先]の配列
    for _ in range(m):
        x,y,z = map(int,input().split())
        edge[x-1].append((z,y-1))
        edge[y-1].append((z,x-1))

    def bfs(start):
        d = [inf]*n
        d[start] = 0
        f = [-1]*n
        f[start] = l
        dq = deque([[start, l, 0]])
        while dq:
            v, nl, dist = dq.popleft()
            if d[v] != dist or f[v] != nl:
                continue
            for c, nv in edge[v]:
                if l - c < 0:
                    continue
                if nl - c >= 0:
                    if dist < d[nv] or (dist==d[nv]and f[nv] < nl - c):
                        f[nv] = nl - c
                        d[nv] = dist
                        dq.append((nv, nl - c, dist))
                else:
                    if dist + 1 < d[nv] or (dist+1==d[nv] and f[nv] < l-c):
                        f[nv] = l - c
                        d[nv] = dist + 1
                        dq.append((nv, l - c, dist + 1))
        return d

    res = []
    for i in range(n):
        res.append(bfs(i))

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

    n,m,l = map(int, input().split())
    edge = [[] for i in range(n)]
    #edge[i] : iから出る道の[重み,行先]の配列
    for _ in range(m):
        x,y,z = map(int,input().split())
        edge[x-1].append((z,y-1))
        edge[y-1].append((z,x-1))

    def dfs(start):
        d = [inf]*n
        d[start] = 0
        f = [-1]*n
        f[start] = l
        dq = deque([start])
        while dq:
            v = dq.pop()
            nl = f[v]
            for c, nv in edge[v]:
                if l - c < 0:
                    continue
                if nl - c >= 0:
                    if d[v] < d[nv] or (d[v]==d[nv]and f[nv] < nl - c):
                        f[nv] = nl - c
                        d[nv] = d[v]
                        dq.append(nv)
                else:
                    if d[v]+1 < d[nv] or (d[v]+1==d[nv] and f[nv] < l-c):
                        f[nv] = l - c
                        d[nv] = d[v] + 1
                        dq.append(nv)
        return d

    res = []
    for i in range(n):
        res.append(dfs(i))

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

    n,m,l = map(int, input().split())
    edge = [[] for i in range(n)]
    #edge[i] : iから出る道の[重み,行先]の配列
    for _ in range(m):
        x,y,z = map(int,input().split())
        edge[x-1].append((z,y-1))
        edge[y-1].append((z,x-1))

    def bfs(start):
        d = [inf]*n
        d[start] = 0
        f = [-1]*n
        f[start] = l
        dq = deque([[start, l, 0]])
        while dq:
            v, nl, dist = dq.popleft()
            for c, nv in edge[v]:
                if l - c < 0:
                    continue
                if nl - c >= 0:
                    if dist < d[nv] or (dist==d[nv]and f[nv] < nl - c):
                        f[nv] = nl - c
                        d[nv] = dist
                        dq.append((nv, nl - c, dist))
                else:
                    if dist + 1 < d[nv] or (dist+1==d[nv] and f[nv] < l-c):
                        f[nv] = l - c
                        d[nv] = dist + 1
                        dq.append((nv, l - c, dist + 1))
        return d

    res = []
    for i in range(n):
        res.append(bfs(i))

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    q = [(0, start)] # q = [(d, 現在地)]
    while q:
        d, v = heapq.heappop(q)
        if dist[v] < d:
            continue
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                heapq.heappush(q, (dist[nxt_v], nxt_v))
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int,input().split())
INF = 10**18
d = [[INF for j in range(N)] for i in range(N)]

# 入力
for _ in range(M):
    A,B,C = map(int,input().split())
    if L < C:
        continue
    d[A-1][B-1] = C
    d[B-1][A-1] = C

# 初期化
for i in range(N):
    d[i][i] = 0

# ワーシャルフロイド1回目
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])

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

# 初期化
for i in range(N):
    d[i][i] = 0

# ワーシャルフロイド2回目
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])

Q = int(input())

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

Submission status: Time Limit Exceeded

Solution code:
INFTY = 10**12
N,M,L = map(int,input().split())
G = {i:[] for i in range(1,N+1)}
for _ in range(M):
    a,b,c = map(int,input().split())
    G[a].append((b,c))
    G[b].append((a,c))
dist = [[INFTY for _ in range(N+1)] for _ in range(N+1)]
for i in range(1,N+1):
    for j,d in G[i]:
        dist[i][j] = d
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j])
F = {i:[] for i in range(1,N+1)}
for i in range(1,N+1):
    for j in range(1,N+1):
        if dist[i][j]<=L:
            F[i].append(j)
dist2 = [[INFTY for _ in range(N+1)] for _ in range(N+1)]
for i in range(1,N+1):
    for j in F[i]:
        dist2[i][j] = 1
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            dist2[i][j] = min(dist2[i][j],dist2[i][k]+dist2[k][j])
Q = int(input())
for _ in range(Q):
    s,t = map(int,input().split())
    if dist2[s][t]>=INFTY:
        print(-1)
    else:
        print(dist2[s][t]-1)

Submission status: Time Limit Exceeded

Solution code:
import 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)]

INF = 10**20
g = [[INF]*N for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    g[a][b] = g[b][a] = c
for i in range(N):
    g[i][i] = 0
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 = [[N]*N for _ in range(N)]
for i in range(N-1):
    for j in range(i+1,N):
        if g[i][j] <= L:
            h[i][j] = h[j][i] = 1
for i in range(N):
    h[i][i] = 0
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])

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

    inf = 1 << 60

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

    dist = [[inf] * N for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        dist[A][B] = dist[B][A] = C

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

    g = [[inf] * N for _ in range(N)]  # 到達に必要な補充回数
    for A in range(N):
        for B in range(N):
            if dist[A][B] <= L:
                g[A][B] = 1

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

    Q = int(input())
    for _ in range(Q):
        s, t = (int(x) - 1 for x in input().split())
        d = g[s][t]
        if d == inf:
            print(-1)
        else:
            print(d - 1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    q = [(0, start)] # q = [(d, 現在地)]
    while q:
        d, v = heapq.heappop(q)
        if dist[v] < d:
            continue
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                heapq.heappush(q, (dist[nxt_v], nxt_v))
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

Solution code:
import heapq


def dijkstra(start: int, graph: list) -> list:
    """dijkstra法: 始点startから各頂点への最短距離を求める
    計算量: O((E+V)logV)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    # 補給回数: 少ないほうがいい
    # 使用燃料: 少ないほうがいい
    # 補給回数が少ないほうがより嬉しい
    # d = 補給回数 * 10 ** 15 + 使用燃料
    q = [(0, start)] # q = [(d, 現在地)]
    while q:
        d, v = heapq.heappop(q)
        #if dist[v] < d:
        #    continue
        for nxt_v, cost in graph[v]:
            div_d, mod_d = divmod(d + cost, 10 ** 15)
            if mod_d > l:
                new_d = (div_d + 1) * 10 ** 15 + cost
            else:
                new_d = d + cost
            if new_d < dist[nxt_v]:
                dist[nxt_v] = new_d
                heapq.heappush(q, (dist[nxt_v], nxt_v))
    return dist


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

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

for i in range(n):
    tmp = dijkstra(i, graph)
    for j in range(n):
        ans[i][j] = tmp[j] // (10 ** 15)

for a, b in query:
    a -= 1
    b -= 1
    if ans[a][b] == 1000:
        print(-1)
    else:
        print(ans[a][b])

Submission status: Time Limit Exceeded

Solution code:
N, M, L = list(map(int, input().split()))
dist = [[float('inf') for i in range(N)] for j in range(N)]

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

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

dist2 = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N):
    for j in range(N):
        if dist[i][j] <= L:
            dist2[i][j] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            dist2[i][j] = min(dist2[i][j], dist2[i][k] + dist2[k][j])

for i in range(int(input())):
    s, t = list(map(int, input().split()))
    d = dist2[s-1][t-1]

    if d == float('inf'): d = -1
    else: d -= 1
    print(d)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
n,m,L=map(int,input().split())
edge=[[] for i in range(n+1)]
for i in range(m):
    a,b,c=map(int,input().split())
    if c>L:
        continue
    edge[a].append((b,c))
    edge[b].append((a,c))
ans=[0 for i in range(n+1)]

from heapq import *
def dijkstra(s,n):
    d = [(300,1000) for i in range(n+1)]
    pq = []
    heappush(pq,((0,0),s))
    while pq:
        dist,u = heappop(pq)
        if dist<d[u]:
            d[u]=dist
            for v,cost in edge[u]:
                if dist[1]+cost>L:
                    tmp=(dist[0]+1,cost)
                else:
                    tmp=(dist[0],dist[1]+cost)
                if d[v]<=tmp:
                    continue
                heappush(pq,(tmp,v))
    return d
for i in range(1,n+1):
    ans[i]=dijkstra(i,n)
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    if ans[s][t][0]==300:
        print(-1)
    else:
        print(ans[s][t][0])

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
n,m,L=map(int,input().split())
edge=[[] for i in range(n+1)]
for i in range(m):
    a,b,c=map(int,input().split())
    if c>L:
        continue
    edge[a].append((b,c))
    edge[b].append((a,c))
ans=[0 for i in range(n+1)]

from heapq import *
def dijkstra(s,n):
    d = [(300,1000) for i in range(n+1)]
    pq = []
    d[s]=(0,0)
    heappush(pq,((0,0),s))
    while pq:
        dist,u = heappop(pq)
        for v,cost in edge[u]:
            if dist[1]+cost>L:
                tmp=(dist[0]+1,cost)
            else:
                tmp=(dist[0],dist[1]+cost)
            if d[v]<=tmp:
                continue
            d[v]=tmp
            heappush(pq,(tmp,v))
    return d
for i in range(1,n+1):
    ans[i]=dijkstra(i,n)
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    if ans[s][t][0]==300:
        print(-1)
    else:
        print(ans[s][t][0])

Submission status: Time Limit Exceeded

Solution code:
n,m,L=map(int,input().split())
edge=[[] for i in range(n+1)]
for i in range(m):
    a,b,c=map(int,input().split())
    if c>L:
        continue
    edge[a].append((b,c))
    edge[b].append((a,c))
ans=[0 for i in range(n+1)]

from heapq import *
def dijkstra(s,n):
    d = [(float('inf'),float('inf')) for i in range(n+1)]
    pq = []
    d[s]=(0,0)
    heappush(pq,((0,0),s))
    while pq:
        dist,u = heappop(pq)
        for v,cost in edge[u]:
            if dist[1]+cost>L:
                tmp=(dist[0]+1,cost)
            else:
                tmp=(dist[0],dist[1]+cost)
            if d[v]<=tmp:
                continue
            d[v]=tmp
            heappush(pq,(tmp,v))
    return d
for i in range(1,n+1):
    ans[i]=dijkstra(i,n)
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    if ans[s][t][0]==float('inf'):
        print(-1)
    else:
        print(ans[s][t][0])

Submission status: Time Limit Exceeded

Solution code:
def warshall_floid(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])
    return d

n,m,l = map(int,input().split())
d = [[float('inf')]*(n+1) for i in range(n+1)]
for i in range(m):
    a,b,c = map(int,input().split())
    d[a][b] = c
    d[b][a] = c
for i in range(1,n+1):
    d[i][i] = 0
d = warshall_floid(d)
for i in range(1,n+1):
    for j in range(1,n+1):
        if d[i][j] <= l:
            d[i][j] = 1
        else:
            d[i][j] = float('inf')
d = warshall_floid(d)
q = int(input())
for i in range(q):
    s,t = map(int,input().split())
    if d[s][t] == float('inf'):
        print(-1)
    else:
        print(d[s][t]-1)

Submission status: Time Limit Exceeded

Solution code:
N,M,L,*X = map(int, open(0).read().split())
ls = X[:3*M]
INF = 10**9
Els = [[INF]*N for i in range(N)]
Q = X[3*M]
query = X[3*M+1:]
for a,b,c in zip(*[iter(ls)]*3):
  if c<=L:
    Els[a-1][b-1] = c
    Els[b-1][a-1] = c
for i in range(N):
  Els[i][i] = 0
for k in range(N):
  for i in range(N):
    for j in range(N):
      Els[i][j] = min(Els[i][j], Els[i][k]+Els[k][j])
      
dist = [[INF]*N for i in range(N)]
for i in range(N):
  for j in range(N):
    if Els[i][j]<=L:
      dist[i][j] = 1
for i in range(N):
  dist[i][i] = 0
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])

for s,t in zip(*[iter(query)]*2):
  if dist[s-1][t-1]>=INF:
    print(-1)
    continue
  print(dist[s-1][t-1]-1)