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:
N, M, L = map(int, input().split())
ABC = [tuple(map(int, input().split())) for _ in range(M)]
Q = int(input())
ST = [tuple(map(int, input().split())) for _ in range(Q)]
INF = float('inf')

dist = [[INF] * N for _ in range(N)]
fuel = [[INF] * N for _ in range(N)]

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

for fr, to, cost in ABC:
    if cost > L:
        continue
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

for k in range(N):
    for i in range(N):
        for j in range(N):
            d = dist[i][k] + dist[k][j]
            dist[i][j] = min(dist[i][j], d)
            if d <= L:
                fuel[i][j] = 1

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

ans = []
for start, end in ST:
    start -= 1
    end -= 1
    ans.append(fuel[start][end] - 1 if fuel[start][end] != INF else -1)

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = float('inf')

dist = [[INF] * N for _ in range(N)]
fuel = [[INF] * N for _ in range(N)]

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

for _ in range(M):
    fr, to, cost = map(int, input().split())
    if cost > L:
        continue
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

for k in range(N):
    for i in range(N):
        for j in range(N):
            d = dist[i][k] + dist[k][j]
            dist[i][j] = min(dist[i][j], d)
            if d <= L:
                fuel[i][j] = 1

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

Q = int(input())
ans = []
for _ in range(Q):
    start, end = map(int, input().split())
    start -= 1
    end -= 1

    ans.append(fuel[start][end] - 1 if fuel[start][end] != INF else -1)

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = float('inf')

dist = [[INF] * N for _ in range(N)]
fuel = [[INF] * N for _ in range(N)]

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

for _ in range(M):
    fr, to, cost = map(int, input().split())
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

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])
            if dist[i][j] <= L:
                fuel[i][j] = 1

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

Q = int(input())
ans = []
for _ in range(Q):
    start, end = map(int, input().split())
    start -= 1
    end -= 1

    ans.append(fuel[start][end] - 1 if fuel[start][end] != INF else -1)

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = float('inf')

dist = [[INF] * N for _ in range(N)]

for _ in range(M):
    fr, to, cost = map(int, input().split())
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

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

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

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

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

Q = int(input())
ans = []
for _ in range(Q):
    start, end = map(int, input().split())
    start -= 1
    end -= 1

    ans.append(fuel[start][end] - 1 if fuel[start][end] != INF else -1)

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

Submission status: Time Limit Exceeded

Solution code:
n, m, l = [int(x) for x in input().split()]
ws      = [None]
ds      = [None]

for i in range(1, n + 1):
	ws.append([10 ** 20] * (n + 1))
	ds.append([10 ** 20] * (n + 1))
	
 
for i in range(0, m):
	x, y, z  = [int(a) for a in input().split()]
	ws[x][y] = z
	ws[y][x] = z
	ds[x][y] = z
	ds[y][x] = z
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		for j in range(1, n + 1):
			if ds[i][k] + ds[k][j] < ds[i][j]:
				ds[i][j] = ds[i][k] + ds[k][j]

for i in range(1, n + 1):
	for j in range(1, n + 1):
		if ds[i][j] <= l:
			ds[i][j] = 1
		else:
			ds[i][j] = 10 ** 20
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		for j in range(1, n + 1):
			if ds[i][k] + ds[k][j] < ds[i][j]:
				ds[i][j] = ds[i][k] + ds[k][j]
 
q = int(input())
 
for _ in range(0, q):
	s, t = [int(x) for x in input().split()]
	d    = ds[s][t]
	
	print(d - 1 if d < n else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys

N, M, L = list(map(int, input().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
Q = int(input())
st = [list(map(int, sys.stdin.readline().split())) for _ in range(Q)]

D = [[0] * N for _ in range(N)]
R = {}

for a, b, c in ABC:
  a -= 1
  b -= 1
  D[a][b] = c
  D[b][a] = c
  if a not in R:
    R[a] = [[b, c]]
  else:
    R[a].append([b, c])
  if b not in R:
    R[b] = [[a, c]]
  else:
    R[b].append([a, c])

inf = 10 ** 10
T = [[inf] * N for _ in range(N)]
import copy
for i in range(N):
  if i not in R: continue
  S = copy.deepcopy(R[i])
  T[i][i] = 0
  while S:
    t = S.pop()
    if t[1] <= L:
      if t[1] < T[i][t[0]]:
        T[i][t[0]] = t[1]
        for j in R[t[0]]:
          if t[1] + j[1] <= L:
            S.append([j[0], t[1] + j[1]])

for i in range(N):
  for j in range(N):
    if i == j:
      T[i][j] = 0
      continue
    if T[i][j] <= L:
      T[i][j] = 1
    else:
      T[i][j] = inf

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

for s, t in st:
  s -= 1
  t -= 1
  if T[s][t] == inf:
    print(-1)
  else:
    print(T[s][t] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
	input = sys.stdin.readline
	N, M, L = list(map(int,input().split()))
	P = [list(map(int,input().split())) for i in range(M)]
	Q = int(input())
	st = [list(map(int,input().split())) for i in range(Q)]

	neighbor = [[10**10]*N for i in range(N)]
	for s,e,d in P:
		# if d<=L:
		# 	neighbor[s-1].append((e-1,d))
		# 	neighbor[e-1].append((s-1,d))
		if d<=L:
			neighbor[s-1][e-1] = neighbor[e-1][s-1] = d

	# start, end = 2,1

	fuellist = [0]*N
	def bfs(start, end):
		fuel = [[10000000,L+1] for i in range(N)]
		fuel[start][0] = 0
		fuel[start][1] = L
		queue = [start]
		while len(queue)>0:
			nq = []						# next target node
			nq_append = nq.append
			for i in queue:				# target node
				oc, om = fuel[i]
				for j, d in enumerate(neighbor[i]):	# next node
					if d==10**10: continue
					if om<d:
						nc = oc+1
						nm = L-d
					else:
						nc = oc
						nm = om-d

					# print(i,j,nc,nm)

					if (nc<fuel[j][0]) or (nc==fuel[j][0] and nm>fuel[j][1]):
						fuel[j][0], fuel[j][1] = nc, nm
						nq_append(j)

			queue = nq					# update target node

		ans = fuel[end][0]
		if ans==10000000: ans = -1

		fuellist[start] = fuel

		print(ans)


	for s, t in st:
		start, end = s-1, t-1
		if fuellist[start]==0:
			bfs(start,end)
		else:
			ans = fuellist[start][end][0]
			if ans==10000000: ans = -1
			print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
n,m,l = map(int,input().split())
d = [[float("inf")]*n for _ in [0]*n]
for i in range(m):
    a,b,c = map(int,input().split())
    if l >= c:
        d[a-1][b-1] = d[b-1][a-1] = c
for i in range(n):
    d[i][i] = 0

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

edge = [[float("inf")]*n for _ in [0]*n]
for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            edge[i][j] = 1

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

q = int(input())
for _ in [0]*q:
    s,t = map(int,input().split())
    if edge[s-1][t-1] == float("inf"):
        print(-1)
    else:
        print(edge[s-1][t-1]-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

N, M, L = [int(v) for v in input().split(' ')]

cost = [[-1] * N for i in range(N)]
link = [[] for i in range(N)]

for i in range(M):
    A, B, C = [int(v) for v in input().split()]
    a = A - 1
    b = B - 1
    if C > L:
        continue
    cost[a][b] = C
    cost[b][a] = C
    link[a].append(b)
    link[b].append(a)

def search(s, t):
    h = []
    heapq.heappush(h, (0, 0, L, s))

    closed = 0
    while len(h) > 0:
        _, c, f, n = heapq.heappop(h)
        closed |= (1 << n)

        if n == t:
            return c

        for n2 in link[n]:
            if (closed & (1 << n2)) != 0:
                continue

            f2 = f
            c2 = c
            cst = cost[n][n2]
            if cst < 0:
                raise
            if f2 < cst:
                if f2 == L:
                    continue
                else:
                    f2 = L
                    c2 += 1

            if f2 >= cst:
                f2 -= cst
            else:
                f2 = L
                c2 += 1
            heapq.heappush(h, (c2 * L + (L - f2 / 2), c2, f2, n2))

    return -1

Q = int(input())
for i in range(Q):
    s, t = [int(v) - 1 for v in input().split()]
    c = search(s, t)
    print(c)

Submission status: Time Limit Exceeded

Solution code:

inf = 10**10


def resolve():
    n, m, gas = map(int, input().split())

    costs = [[inf for i in range(n)] for i in range(n)]

    for i in range(len(costs)):
        costs[i][i] = 0
    for i in range(m):
        v1, v2, cost = map(int, input().split())
        costs[v1 - 1][v2 - 1] = cost
        costs[v2 - 1][v1 - 1] = cost

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

    cost_with_gas = [[inf for i in range(n)] for i in range(n)]

    for i in range(len(cost_with_gas)):
        cost_with_gas[i][i] = 0
    for i in range(len(cost_with_gas)):
        for j in range(i+1, len(cost_with_gas)):
            if gas - costs[i][j] >= 0:
                cost_with_gas[i][j] = 1
                cost_with_gas[j][i] = 1

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

    q = int(input())

    for i in range(q):
        from_city, destination = map(int, input().split())
        ans = cost_with_gas[from_city-1][destination-1] -1 if cost_with_gas[from_city-1][destination-1] != inf else -1
        print(ans)
        
resolve()

Submission status: Time Limit Exceeded

Solution code:
N,M,L = list(map(int,input().split()))
from collections import defaultdict

graph = defaultdict(set)
weight = dict()

for m in range(M):
  a,b,c = list(map(int,input().split()))
  
  weight[(a,b)]=c
  weight[(b,a)]=c
  graph[a] |= {b}
  graph[b] |= {a}


available_path = defaultdict(set)


for i in range(N):
  # ある街を出発して無補給でたどり着ける町のリストを作成する
  start_node = i+1
  query =[(start_node,set(),L)]
  index = 0
  while index != len(query):
    now_node, prevs, fuel = query[index]
    # 最後のノードから接続されるノードを考える
    
    for next_node in graph[now_node]:
      nokori = fuel - weight[(now_node,next_node)]
      #print(now_node,next_node,prevs,nokori) 
      if next_node not in prevs and nokori >= 0:
        query.append((next_node, prevs|{now_node}, nokori))
        available_path[start_node]|={next_node}
        available_path[next_node]|={start_node}
    index += 1
#print(available_path)
    
  
from heapq import heappush, heappop

for q in range(int(input())):
  start,end = list(map(int,input().split()))
  #print("query",start,end)
  query = []
  heappush(query, (0,start,set()) )
  while len(query)>0:
    cnt,now_node, prevs  = heappop(query)
    # 最後のノードから接続されるノードを考える
    #print(start,"->",end,":",cnt,now_node, prevs)
    if  end in available_path[now_node]:
        print(cnt)
        break
    else:
      for next_node in available_path[now_node]:
        if next_node not in prevs:
          heappush(query, (cnt+1, next_node, prevs|{now_node}) )
  else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]


g = Graph()
N, M, L = [int(i) for i in input().split()]

for i in range(M):
    u, v, c = [int(i) for i in input().split()]
    g.add_edge(u - 1, v - 1, c)
    g.add_edge(v - 1, u - 1, c)


g2 = Graph()
for i in range(N):
    d = Dijkstra(g, i)
    for j in range(N):
        dist = d.dist[j]
        if dist <= L and i != j:
            g2.add_edge(i, j, 1)
            g2.add_edge(j, i, 1)


s_0 = -1
ans = []
Q = int(input())
s_t_index = []
for i in range(Q):
    s, t = [int(i) for i in input().split()]
    s_t_index.append([s, t, i])

s_t_index.sort()
# print(s_t_index)

for i in range(Q):
    if s_t_index[i][0] != s_0:
        s_0 = s_t_index[i][0]
        d = Dijkstra(g2, s_0-1)
        length = len(d.shortest_path(s_t_index[i][1]-1))
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1]])
    else:
        length = len(d.shortest_path(s_t_index[i][1]-1))
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1]])


ans.sort()
[print([ans[i][1]-1, -1][ans[i][1] == float("inf")]) for i in range(Q)]

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N, M, L = map(int, input().split())
V = {i: [] for i in range(1,N+1)}
for _ in range(M):
    a, b, c = map(int, input().split())
    V[a].append((b, c))
    V[b].append((a, c))
INF = float('inf')
VD = {i: {i: INF for i in range(1,N+1)} for i in range(1,N+1)}
for i, e in V.items():
    for (j, c) in e:
        VD[i][j] = c
        VD[j][i] = c
for i in range(1,N+1):
    VD[i][i] = 0

for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if VD[i][j] > VD[i][k] + VD[k][j]:
                VD[i][j] = VD[i][k] + VD[k][j]

W = {i: [] for i in range(1,N+1)}
for i, v in VD.items():
    for j, d in v.items():
        if d <= L:
            W[i].append(j)
            W[j].append(i)

WD = {i: {i: INF for i in range(1,N+1)} for i in range(1,N+1)}
for i, e in W.items():
    for j in e:
        WD[i][j] = 1
        WD[j][i] = 1
for i in range(1,N+1):
    WD[i][i] = 0

for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if WD[i][j] > WD[i][k] + WD[k][j]:
                WD[i][j] = WD[i][k] + WD[k][j]

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = [int(i) for i in input().split()]

d = [[1e+10]*N for i in range(N)]
for i in range(M):
    A, B, C = [int(i) for i in input().split()]
    d[A-1][B-1] = C
    d[B-1][A-1] = C
for i in range(N):
    for j in range(N):
        for k in range(N):
            d[j][k] = min(d[j][k], d[j][i] + d[i][k])

d2 = [[1 if j <= L else 1e+10 for j in d[i]] for i in range(N)]
for i in range(N):
    for j in range(N):
        for k in range(N):
            d2[j][k] = min(d2[j][k], d2[j][i] + d2[i][k])

Q = int(input())
for i in range(Q):
    s, t = [int(i) for i in input().split()]
    ans = d2[s-1][t-1]
    if ans >= 1e+10:
        print(-1)
    else:
        print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
	input = sys.stdin.readline
	N, M, L = list(map(int,input().split()))
	P = [list(map(int,input().split())) for i in range(M)]
	Q = int(input())
	st = [list(map(int,input().split())) for i in range(Q)]

	neighbor = [[] for i in range(N)]
	for s,e,d in P:
		if d<=L:
			neighbor[s-1].append((e-1,d))
			neighbor[e-1].append((s-1,d))

	fuellist = [0]*N
	def bfs(start, end):
		# fuel = [[10000000,L+1] for i in range(N)]
		fuel = [100000*(10**10)+L+1]*N
		# fuel[start][0] = 0
		# fuel[start][1] = L
		fuel[start] = L
		queue = [start]
		while len(queue)>0:
			nq = []						# next target node
			nq_append = nq.append
			for i in queue:				# target node
				# oc, om = fuel[i]
				oc = fuel[i]//(10**10)
				om = fuel[i]%(10**10)
				for j, d in neighbor[i]:	# next node
					if om<d:
						nc = oc+1
						nm = L-d
					else:
						nc = oc
						nm = om-d

					# print(i,j,nc,nm)

					fc = fuel[j]//(10**10)
					fm = fuel[j]%10**10
					# if (nc<fuel[j][0]) or (nc==fuel[j][0] and nm>fuel[j][1]):
					if nc<fc or (nc==fc and nm>fm):
						# fuel[j][0], fuel[j][1] = nc, nm
						nf = nc*(10**10)+nm
						fuel[j] = nf
						nq_append(j)

			queue = nq					# update target node

		# ans = fuel[end][0]
		ans = fuel[end]//(10**10)
		# if fuel[end][0]==10000000: ans = -1
		if ans==100000: ans = -1

		fuellist[start] = fuel

		print(ans)

	for s, t in st:
		start, end = s-1, t-1
		if fuellist[start]==0:
			bfs(start,end)
		else:
			# ans = fuellist[start][end][0]
			ans = fuellist[start][end]//(10**10)
			if ans==100000: ans = -1
			print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(V, E):
    dist = [[INF for _ in V] for _ in V]
    for v in V:
        dist[v][v] = 0
        for u, c in E[v]: dist[v][u] = c
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

N, M, L = map(int, input().split())
V = list(range(N))
E = [[] for _ in V]
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((b-1, c))
    E[b-1].append((a-1, c))

dist = floyd_warshall(V, E)
E_charge = [[] for _ in V]
for u, v in combinations(V, 2):
    if dist[u][v] <= L:
        E_charge[u].append((v, 1))
        E_charge[v].append((u, 1))
charge = floyd_warshall(V, E_charge)

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

Submission status: Time Limit Exceeded

Solution code:
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(V, E):
    dist = {u: {v: INF for v in V} for u in V}
    for v in V:
        dist[v][v] = 0
        for u, c in E[v].items(): dist[v][u] = c
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    return dist

N, M, L = map(int, input().split())
V = list(range(N))
E = {v: {} for v in V}
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1][b-1] = c
    E[b-1][a-1] = c

dist = floyd_warshall(V, E)
E_charge = {v: {} for v in V}
for u, v in combinations(V, 2):
    if dist[u][v] <= L: E_charge[u][v] = 1; E_charge[v][u] = 1;
charge = floyd_warshall(V, E_charge)

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
V = {i: [] for i in range(1,N+1)}
for _ in range(M):
    a, b, c = map(int, input().split())
    V[a].append((b, c))
    V[b].append((a, c))
INF = float('inf')
VD = {i: {i: INF for i in range(1,N+1)} for i in range(1,N+1)}
for i, e in V.items():
    for (j, c) in e:
        VD[i][j] = c
        VD[j][i] = c
for i in range(1,N+1):
    VD[i][i] = 0

for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if VD[i][j] > VD[i][k] + VD[k][j]:
                VD[i][j] = VD[i][k] + VD[k][j]

W = {i: [] for i in range(1,N+1)}
for i, v in VD.items():
    for j, d in v.items():
        if d <= L:
            W[i].append(j)
            W[j].append(i)

WD = {i: {i: INF for i in range(1,N+1)} for i in range(1,N+1)}
for i, e in W.items():
    for j in e:
        WD[i][j] = 1
        WD[j][i] = 1
for i in range(1,N+1):
    WD[i][i] = 0

for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if WD[i][j] > WD[i][k] + WD[k][j]:
                WD[i][j] = WD[i][k] + WD[k][j]

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

Submission status: Time Limit Exceeded

Solution code:
import collections
import heapq
def main():

    N, M, L = map(int, input().split())
    d = [[float("inf") for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        if c <= L:
            d[a-1][b-1] = c
            d[b-1][a-1] = c
    Q = int(input())

    # d = [[float("inf") for _ in range(N)] for _ in range(N)]
    for i in range(N): d[i][i] = 0

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

    graph = [[float("inf") for _ in range(N)] for _ in range(N)]

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

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

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

    # print(graph)

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from itertools import product, combinations

INF = float('inf')
def floyd_warshall(V, E):
    '''
    Input:
        V = list(range(N))
        E = defaultdict(dict)
    Output:
        If there exists a negative cycle, return (None, prev), where prev is
        the table, whose (i, j)-element is the previous vertices in the shortest (i, j)-path
        Otherwise return (dist, prev), where dist is the table of the minimum cost
        between arbitrary vertex u, v in the given graph
    '''
    dist = {u: {v: INF for v in V} for u in V}
    prev = {u: {v: None for v in V} for u in V}
    for v in V:
        dist[v][v] = 0; prev[v][v] = -1
        for u, c in E[v].items(): dist[v][u] = c; prev[v][u] = v;
    for k in V:        
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
                prev[i][j] = prev[k][j]
    for v in V:
        if dist[v][v] < 0: return None, prev
    return dist, prev

N, M, L = map(int, input().split())
V = list(range(N))
E = defaultdict(dict)
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1][b-1] = c
    E[b-1][a-1] = c

dist, _ = floyd_warshall(V, E)
E_charge = defaultdict(dict)
for u, v in combinations(V, 2):
    if dist[u][v] <= L: E_charge[u][v] = 1; E_charge[v][u] = 1;
charge, _ = floyd_warshall(V, E_charge)

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

Submission status: Time Limit Exceeded

Solution code:
import queue
N, M, L = map(int, input().split())
to = [[] for _ in range(N)]
dist = [[float('inf')] * N for _ in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    to[A-1].append((B,C))
    to[B-1].append((A,C))
    dist[A-1][B-1] = C
    dist[B-1][A-1] = C

for k in range(N):
    for i in range(N):
        for j in range(N):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]

near = [[] for _ in range(N)]
for i in range(N-1):
    for j in range(i,N):
        if dist[i][j] <= L:
            near[i].append(j)
            near[j].append(i)

def serch(s, t):
    q = queue.Queue()
    q.put((s, -1))
    visited[s] = True
    while not q.empty():
        src, charge = q.get()
        if src == t:
            return charge
        for i in near[src]:
            if visited[i] == False:
                visited[i] = True
                q.put((i, charge+1))
    return -1

for i in range(int(input())):
    visited = [False] * N
    s, t = map(int, input().split())
    print(serch(s-1, t-1))

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = float('inf')

dist = [[INF] * N for _ in range(N)]

for _ in range(M):
    fr, to, cost = map(int, input().split())
    fr -= 1
    to -= 1
    dist[fr][to] = cost
    dist[to][fr] = cost

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

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

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

Q = int(input())
ans = []
for _ in range(Q):
    start, end = map(int, input().split())
    start -= 1
    end -= 1

    ans.append(fuel[start][end] - 1 if fuel[start][end] != INF else -1)

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

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 = float('inf')
dist1 = [[INF]*N for i in range(N)]
dist2 = [[INF]*N for i in range(N)]
for a,b,c in ABC:
    if c > L: continue
    a,b = a-1,b-1
    dist1[a][b] = dist1[b][a] = c
for i in range(N):
    dist1[i][i] = 0
    dist2[i][i] = 0

for k in range(N):
    for i in range(N):
        for j in range(N):
            dist1[i][j] = min(dist1[i][j], dist1[i][k] + dist1[k][j])
for i in range(N):
    for j in range(N):
        if i==j: continue
        if dist1[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])

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

Submission status: Time Limit Exceeded

Solution code:
import bisect
def main():
    n,m,l=map(int,input().split(' '))
    g=[[float('inf')if i != j  else 0  for i in range(n)] for j in range(n)]
    for i in range(m):
        a,b,c=map(int,input().split(' '))
        if c <=l:
            g[a-1][b-1]=c
            g[b-1][a-1]=c
    q=int(input())
    q_list=[tuple(map(int,input().split(' '))) for i in range(q)]
    for k in range(n):
        for i in range(n):
            for j in range(i,n):
                g[i][j]= min(g[i][j],g[i][k]+g[k][j])
                g[j][i]=g[i][j]

    for i in range(n):
        for j in range(n):
            if g[i][j]<=l:
                if g[i][j] != 0:
                    g[i][j] = 1
                else:
                    g[i][j] = 0
            else:
                g[i][j] = float('inf')

    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])
    for i,j in q_list:
        if g[i-1][j-1] != float('inf'):
            print(g[i-1][j-1]-1)
        else:
            print(-1)


if __name__ == '__main__':
    main()