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:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]

    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        for i in range(n):
            if i == k:
                continue
            for j in range(i+1,n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
                if dist[k][i] + dist[j][k] < dist[j][i]:
                    dist[j][i] = dist[k][i] + dist[j][k]

    lis = [[] for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if dist[i][j] <= l:
                supply[i][j] = 0
                supply[j][i] = 0
                lis[i].append(j)
                lis[j].append(i)

    for i in range(n):
        q = []
        for k in lis[i]:
            heappush(q, (0, k))

        while q:
            time, p = heappop(q)
            for k in lis[p]:
                if dist[p][k] <= l and supply[i][k] > time:
                    supply[i][k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]

    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        distk = dist[k]
        for i in range(n):
            if i == k:
                continue
            disti = dist[i]
            for j in range(n):
                if disti[k] + distk[j] < disti[j]:
                    disti[j] = disti[k] + distk[j]

    lis = [[] for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if dist[i][j] <= l:
                supply[i][j] = 0
                supply[j][i] = 0
                lis[i].append(j)
                lis[j].append(i)

    for i in range(n):
        q = []
        for k in lis[i]:
            heappush(q, (0, k))

        while q:
            time, p = heappop(q)
            for k in lis[p]:
                if dist[p][k] <= l and supply[i][k] > time:
                    supply[i][k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]

    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
    lis = [[] for i in range(n)]
    for i in range(n):
        for j in range(i+1,n):
            if dist[i][j] <= l:
                supply[i][j] = 0
                supply[j][i] = 0
                lis[i].append(j)
                lis[j].append(i)

    for i in range(n):
        q = []
        for k in lis[i]:
            heappush(q, (0, k))

        while q:
            time, p = heappop(q)
            for k in lis[p]:
                if dist[p][k] <= l and supply[i][k] > time:
                    supply[i][k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]
    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c

    supply = [[n] * n for i in range(n)]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]

    for i in range(n):
        for j in range(n):
            if dist[i][j] <= l:
                supply[i][j] = 0

    for i in range(n):
        q = []
        for k in range(n):
            if i == k:
                continue
            if supply[i][k] == 0:
                heappush(q, (0, k))
        while q:
            time, p = heappop(q)
            for k in range(n):
                if dist[p][k] <= l and supply[i][k] > time:
                    supply[i][k] = time + 1
                    heappush(q, (time + 1, k))

    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    return

#B
def B():
    return

#C
def C():
    return

#D
def D():
    return

#E
def E():
    n, m, l = LI()
    dist = [[inf] * n for i in range(n)]
    for _ in range(m):
        a, b, c = LI_()
        c += 1
        if c > l:
            continue
        dist[a][b] = c
        dist[b][a] = c
    for i in range(n):
        dist[i][i] = 0
    supply = [[n for j in range(n)] for i in range(n)]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
                if dist[i][j] <= l:
                    supply[i][j] = 0
    for i in range(n):
        q = []
        for k in range(n):
            if supply[i][k] == 0:
                heappush(q, (0, k))
        while q:
            time, p = heappop(q)
            for k in range(n):
                if dist[p][k] <= l and supply[i][k] > time:
                    supply[i][k] = time + 1
                    heappush(q, (time + 1, k))
    q = II()
    for _ in range(q):
        s, t = LI_()
        if dist[s][t] == inf:
            print(-1)
            continue
        else:
            print(supply[s][t])
    return


#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == '__main__':
    E()

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = float("inf")

def s_in():
    return input()

def n_in():
    return int(input())

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

def warshall_floyd(n, d):
    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 = l_in()
first_matrix = [[INF for _ in range(N)] for _ in range(N)]

for i in range(N):
    first_matrix[i][i] = 0

for _ in range(M):
    A, B, C = l_in()
    first_matrix[A-1][B-1] = C
    first_matrix[B-1][A-1] = C

warshall_floyd(N, first_matrix)
second_matrix = [[INF for _ in range(N)] for _ in range(N)]

for i in range(N):
    for j in range(N):
        if first_matrix[i][j] <= L:
            second_matrix[i][j] = 1

warshall_floyd(N, second_matrix)
Q = n_in()

for _ in range(Q):
    s, t = l_in()
    v = second_matrix[s-1][t-1]
    if v == INF:
        print(-1)
    else:
        print(v-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = float("inf")

def s_in():
    return input()

def n_in():
    return int(input())

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


N, M, L = l_in()
edges = [[] for _ in range(N)]

for i in range(M):
    A, B, C = l_in()
    edges[A-1].append((C, B-1))
    edges[B-1].append((C, A-1))


new_graph = []

for i in range(N):
    q = [(0,i)]
    visited = set()
    while len(q) != 0:
        c, j = heapq.heappop(q)
        visited.add(j)
        for c2, j2 in edges[j]:
            if c + c2 <= L and j2 not in visited:
                heapq.heappush(q, (c+c2, j2))

    new_graph.append(visited)

# print(new_graph)

res = []

for i in range(N):
    q = [(0,i)]

    tmp = [2*N for _ in range(N)]
    tmp[i] = 0

    while len(q) != 0:
        c, j = heapq.heappop(q)

        for j2 in new_graph[j]:
            if c + 1 < tmp[j2]:
                tmp[j2] = c + 1
                heapq.heappush(q, (c+1, j2))
    res.append(tmp)

# print(res)

Q = n_in()

for _ in range(Q):
    s, t = l_in()
    v = res[s-1][t-1]
    if v == 2*N:
        print(-1)
    else:
        print(v-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = float("inf")

def s_in():
    return input()

def n_in():
    return int(input())

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


N, M, L = l_in()
edges = [[] for _ in range(N)]

for i in range(M):
    A, B, C = l_in()
    edges[A-1].append((C, B-1))
    edges[B-1].append((C, A-1))


new_graph = []

for i in range(N):
    q = [(0,i)]
    visited = set()
    while len(q) != 0:
        c, j = heapq.heappop(q)
        if j in visited:
            continue
        visited.add(j)
        for c2, j2 in edges[j]:
            if c + c2 <= L:
                heapq.heappush(q, (c+c2, j2))

    new_graph.append(visited)

# print(new_graph)

res = []

for i in range(N):
    q = [(0,i)]

    tmp = [INF for _ in range(N)]
    tmp[i] = 0

    while len(q) != 0:
        c, j = heapq.heappop(q)

        for j2 in new_graph[j]:
            if c + 1 <= tmp[j2]:
                tmp[j2] = c + 1
                heapq.heappush(q, (c+1, j2))
    res.append(tmp)

# print(res)

Q = n_in()

for _ in range(Q):
    s, t = l_in()
    v = res[s-1][t-1]
    if v == INF:
        print(-1)
    else:
        print(v-1)

Submission status: Time Limit Exceeded

Solution code:
n,m,l=map(int,input().split())
abcs=[list(map(int,input().split())) for _ in range(m)]
for i in range(m):
	abcs[i][0]-=1
	abcs[i][1]-=1
inf =1234567890123456
dist = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
	dist[i][i] = 0

for i in range(m):
	a=abcs[i][0]
	b=abcs[i][1]
	c=abcs[i][2]
	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])

ans = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
	ans[i][i]=0
for i in range(n):
	for j in range(i+1,n):
		if dist[i][j]<=l:
			ans[i][j]=ans[j][i]=1
for k in range(n):
	for i in range(n):
		for j in range(n):
			ans[i][j] = min(ans[i][j],ans[i][k]+ans[k][j])


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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

# 64bitのint最大値
INT_MAX = 2**63 - 1

def warshall_floyd(n, ad_table):
    """
    ワーシャルフロイド法
    :param n: 頂点の数
    :param ad_table: 隣接行列
    :return ad_table: 各頂点間の最短経路行列
    """
    for k in range(n):            # 経由する頂点
        for i in range(n):        # 始点
            for j in range(n):    # 終点
                ad_table[i][j] = min(ad_table[i][j], ad_table[i][k] + ad_table[k][j])

    return ad_table


def main():
    # N: 街の数
    # M: 道の数
    # L: ガソリンタンクの容量
    N, M, L = map(int, input().split(' '))

    # ad_table: 隣接行列
    # 初期化
    ad_table = [[INT_MAX for _ in range(N)] for _ in range(N)]
    # 経路コストの入力
    for i in range(N):
        ad_table[i][i] = 0
    for i in range(M):
        A, B, C = map(int, input().split(' '))
        if ad_table[A-1][B-1] > C and ad_table[B-1][A-1] > C:
            ad_table[A-1][B-1] = ad_table[B-1][A-1] = C

    # movable_table: 給油行列
    # 初期化
    movable_table = [[INT_MAX for _ in range(N)] for _ in range(N)]

    # 最小燃料補給回数を求める
    # 各ノード間の最短経路を算出
    ad_table = warshall_floyd(N, ad_table)
    # 給油行列の作成
    for i in range(N):
        for j in range(N):
            if ad_table[i][j] <= L:
                movable_table[i][j] = movable_table[j][i] = 1
    # 給油行列にワーシャルフロイド法を適用
    gas_table = warshall_floyd(N, movable_table)

    # Q: クエリ数
    Q = int(input())
    # output: 出力のリスト
    output = [-1 for _ in range(Q)]
    # 頂点情報の取得と解の格納
    for i in range(Q):
        s, t = map(int, input().split(' '))
        if gas_table[s-1][t-1] != INT_MAX:
            output[i] = gas_table[s-1][t-1] - 1

    #出力
    for num in output:
        print(num)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int,input().split())
MAX=999999999
A=[]
B=[]
C=[]
D=[[MAX for _ in range(N)] for _ in range(N)]
F=[[MAX for _ in range(N)] for _ in range(N)]
s=[]
t=[]

for i in range(M):
    l=list(map(int,input().split()))
    A.append(l[0]-1)
    B.append(l[1]-1)
    C.append(l[2])



Q=int(input())

for i in range(Q):
    m=list(map(int,input().split()))
    s.append(m[0]-1)
    t.append(m[1]-1)


for i in range(M):
    if C[i]>L : continue
    D[A[i]][B[i]]=C[i]
    D[B[i]][A[i]]=C[i]

for i in range(N):  D[i][i]=0

for k in range(N):
    for i in range(N):
        for j in range(N):
            if (D[i][k]+D[k][j])<D[i][j] :
                D[i][j]=D[i][k]+D[k][j]

for i in range(N):
    for j in range(N):
        if i==j : continue
        if D[i][j]<=L: F[i][j]=1


for i in range(N):  F[i][i]=0

for k in range(N):
    for i in range(N):
        for j in range(N):
            if (F[i][k]+F[k][j])<F[i][j] :
                F[i][j]=F[i][k]+F[k][j]


for p in range(Q) :
    if F[s[p]][t[p]] < MAX :
        print(F[s[p]][t[p]]-1)
    else :
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
ii0 = lambda: ii() - 1
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')

def main():
    N,M,L = mis()
    d = [[INF]*N for _ in range(N)]
    from scipy.sparse.csgraph import floyd_warshall
    for i in range(N):
        d[i][i] = 0
    #
    for _ in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        if c <= L:
            d[a][b] = c
            d[b][a] = c
    #
    '''
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] = min(d[i][k]+d[k][j], d[i][j])    
    '''
    d = floyd_warshall(d)
    #
    d2 = [[INF]*N for _ in range(N)]
    for i in range(N):
        d2[i][i] = 0
    for i in range(N):
        for j in range(N):
            if d[i][j] <= L:
                d2[i][j] = 1
    #
    '''
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d2[i][j] = min(d2[i][k]+d2[k][j], d2[i][j])    
    '''
    d2 = floyd_warshall(d2)
    #
    Q = ii()
    for _ in range(Q):
        s,t = mis()
        s -= 1
        t -= 1
        dist = d2[s][t]
        if dist == INF:
            print(-1)
        else:
            print(dist-1)


main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
ii0 = lambda: ii() - 1
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')

def main():
    N,M,L = mis()
    d = [[INF]*N for _ in range(N)]
    for i in range(N):
        d[i][i] = 0
    #
    for _ in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        if c <= L:
            d[a][b] = c
            d[b][a] = c
    #
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] = min(d[i][k]+d[k][j], d[i][j])    
    #
    d2 = [[INF]*N for _ in range(N)]
    for i in range(N):
        d2[i][i] = 0
    for i in range(N):
        for j in range(N):
            if d[i][j] <= L:
                d2[i][j] = 1
    #
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d2[i][j] = min(d2[i][k]+d2[k][j], d2[i][j])    
    #
    Q = ii()
    for _ in range(Q):
        s,t = mis()
        s -= 1
        t -= 1
        dist = d2[s][t]
        if dist == INF:
            print(-1)
        else:
            print(dist-1)




main()

Submission status: Time Limit Exceeded

Solution code:
inf=10**9+1
n,m,l=map(int,input().split())
adj=[[inf]*(n) for j in range(n)]

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

for k in range(n):
    for i in range(n):
        for j in range(n):
            adj[i][j]=min(adj[i][j],adj[i][k]+adj[k][j])
            
for i in range(n):
    for j in range(n):
        if adj[i][j]<=l:
            adj[i][j]=1
        else:
            adj[i][j]=inf
        if i==j:
            adj[i][j]=0

for k in range(n):
    for i in range(n):
        for j in range(n):
            adj[i][j]=min(adj[i][j],adj[i][k]+adj[k][j])
            
q=int(input())
for w in range(q):
    a,b=map(int,input().split())
    if adj[a-1][b-1]==inf:
        print(-1)
    else:
        print(adj[a-1][b-1]-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
ii0 = lambda: ii() - 1
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')

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




main()

Submission status: Time Limit Exceeded

Solution code:
inf=10**9+1
n,m,l=map(int,input().split())
adj=[[inf for i in range(n+1)] for j in range(n+1)]

for i in range(1,n+1):
    adj[i][i]=0
            
for w in range(m):
    a,b,c=map(int,input().split())
    adj[a][b]=adj[b][a]=c

for k in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            adj[i][j]=min(adj[i][j],adj[i][k]+adj[k][j])
            
for i in range(1,n+1):
    for j in range(1,n+1):
        if adj[i][j]<=l:
            adj[i][j]=1
        else:
            adj[i][j]=inf
        if i==j:
            adj[i][j]=0

for k in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            adj[i][j]=min(adj[i][j],adj[i][k]+adj[k][j])
            
q=int(input())
for w in range(q):
    a,b=map(int,input().split())
    if adj[a][b]==inf:
        print(-1)
    else:
        print(adj[a][b]-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
ii0 = lambda: ii() - 1
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')

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




main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

# 64bitのint最大値
INT_MAX = 2**63 - 1

def warshall_floyd(n, ad_table):
    """
    ワーシャルフロイド法
    :param n: 頂点の数
    :param ad_table: 隣接行列
    :return ad_table: 各頂点間の最短経路行列
    """
    for k in range(n):            # 経由する頂点
        for i in range(n):        # 始点
            for j in range(n):    # 終点
                ad_table[i][j] = min(ad_table[i][j], ad_table[i][k] + ad_table[k][j])

    return ad_table


def main():
    # N: 街の数
    # M: 道の数
    # L: ガソリンタンクの容量
    N, M, L = map(int, input().split(' '))

    # ad_table: 隣接行列
    # 初期化
    ad_table = [[INT_MAX for _ in range(N)] for _ in range(N)]
    # 経路コストの入力
    for i in range(N):
        ad_table[i][i] = 0
    for i in range(M):
        A, B, C = map(int, input().split(' '))
        if ad_table[A-1][B-1] > C and ad_table[B-1][A-1] > C:
            ad_table[A-1][B-1] = ad_table[B-1][A-1] = C

    # aaa
    ad_table_ans = [[INT_MAX for _ in range(N)] for _ in range(N)]

    # 最小燃料補給回数を求める
    # 各ノード間の最短経路を算出
    ad_table = warshall_floyd(N, ad_table)
    # aaa
    for i in range(N):
        for j in range(N):
            if ad_table[i][j] <= L:
                ad_table_ans[i][j] = ad_table_ans[j][i] = 1
    # aaa
    ans_matrix = warshall_floyd(N, ad_table_ans)

    # Q: クエリ数
    Q = int(input())
    # output: 出力のリスト
    output = [-1 for _ in range(Q)]
    # 頂点情報の取得と解の格納
    for i in range(Q):
        s, t = map(int, input().split(' '))
        if ans_matrix[s-1][t-1] != INT_MAX:
            output[i] = ans_matrix[s-1][t-1] - 1

    #出力
    for num in output:
        print(num)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
dp = [[float('inf')] * N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
for i in range(N):
    dp[i][i] = 0

for k in range(N):
    for i in range(N):
        for j in range(N):
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
#print('distance={}'.format(dp))


dp2 = [[float('inf')] * N for _ in range(N)]
for a in range(N - 1):
    for b in range(a+1, N):
        if dp[a][b] <= L:
            dp2[a][b] = 1
            dp2[b][a] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k] + dp2[k][j])
#print('times={}'.format(dp2))


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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
dp = [[float('inf')] * N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])
#rint('distance={}'.format(dp))


dp2 = [[float('inf')] * N for _ in range(N)]
for a in range(N - 1):
    for b in range(a+1, N):
        if dp[a][b] <= L:
            dp2[a][b] = 1
            dp2[b][a] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k] + dp2[k][j])
#print('times={}'.format(dp2))


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