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:

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = g
    N = len(g)
    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

@mt
def slv(N, M, L, ABC, Q, ST):
    g = [[sys.maxsize]*(N+1) for _ in range(N+1)]
    for a, b, c in ABC:
        g[a][b] = c
        g[b][a] = c
    
    d = warshall_floyd(g)
    gg = [[sys.maxsize]*(N+1) for _ in range(N+1)]
    for u in range(1, N+1):
        for v in range(1, N+1):
            if d[u][v] <= L:
                gg[u][v] = 1
    dd = warshall_floyd(gg)

    for s, t in ST:
        if dd[s][t] != sys.maxsize:
            print(dd[s][t]-1)
        else:
            print(-1)



def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]
    (slv(N, M, L, ABC, Q, ST))

    # N = 300
    # M = (N*(N-1))//2
    # L = random.randint(1, 10**9)
    # ABC = []
    # for i in range(1, N+1):
    #     for j in range(i+1, N+1):
    #         ABC.append([i, j, random.randint(1, 10**9)])
    
    # ST = []
    # for i in range(1, N+1):
    #     for j in range(1, N+1):
    #         if i == j:
    #             continue
    #         ST.append([i, j])
    # Q = len(ST)
    # (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int,input().split(' '))
Ms=[]
inf = 10**11
for i in range(N+1):
    #for j in range(N):
    Ms.append([inf]*(N+1) )
#print(d)
#print(d[1][1])
for i in range(M):
    a,b,c = map(int,input().split(' '))
    #print(a,b,c)
    Ms[a][b] = c
    Ms[b][a] = c
    #print(Ms)
Q = int(input())

def warshall_floyd(Ms):
    for k in range(1,len(Ms)):
        for i in range(1,len(Ms)):
            for j in range(1,len(Ms)):
                Ms[i][j]=min(Ms[i][j],Ms[i][k]+Ms[k][j])
    return Ms

Ms = warshall_floyd(Ms)
#print(Ms)
#print("Ms",Ms[3][2],Ms[2][3])
Ls = Ms.copy()
for i in range(N+1):
    for j in range(N+1):
        if Ls[i][j] <= L:
            Ls[i][j] = 1
        else:
            Ls[i][j]=inf
#print("Ls",Ls[3][2])
Ls = warshall_floyd(Ls)
#print(Ls)
for i in range(Q):
    s,t = map(int,input().split(' '))
    if Ls[s][t] == inf:
        print(-1)
    else:
        print(Ls[s][t]-1)

Submission status: Time Limit Exceeded

Solution code:

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g):
    d = [[None]*(len(g)) for _ in range(len(g))]
    V = list(range(len(g)))
    for i in V:
        for j in V:
            if g[i][j]:
                d[i][j] = g[i][j]
            else:
                d[i][j] = sys.maxsize
    for k in V:
        for i in V:
            for j in V:
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    return d

@mt
def slv(N, M, L, ABC, Q, ST):
    g = [[None]*(N+1) for _ in range(N+1)]
    for a, b, c in ABC:
        g[a][b] = c
        g[b][a] = c
    
    d = warshall_floyd(g)
    gg = [[None]*(N+1) for _ in range(N+1)]
    for u in range(1, N+1):
        for v in range(1, N+1):
            if d[u][v] <= L:
                gg[u][v] = 1
    dd = warshall_floyd(gg)

    for s, t in ST:
        if dd[s][t] != sys.maxsize:
            print(dd[s][t]-1)
        else:
            print(-1)



def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]
    (slv(N, M, L, ABC, Q, ST))

    # N = 300
    # M = (N*(N-1))//2
    # L = random.randint(1, 10**9)
    # ABC = []
    # for i in range(1, N+1):
    #     for j in range(i+1, N+1):
    #         ABC.append([i, j, random.randint(1, 10**9)])
    
    # ST = []
    # for i in range(1, N+1):
    #     for j in range(1, N+1):
    #         if i == j:
    #             continue
    #         ST.append([i, j])
    # Q = len(ST)
    # (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

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))
		# if d<=L:
		# 	neighbor[s-1][e-1] = neighbor[e-1][s-1] = d

	# print(neighbor)
	# 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 neighbor[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:
			ans = fuellist[start][end][0]
			if ans==10000000: ans = -1
			print(ans)
		elif fuellist[end]!=0:
			ans = fuellist[end][start][0]
			if ans==10000000: ans = -1
			print(ans)
		else:
			bfs(start,end)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

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

class Graph():
    def __init__(self, N):
        self.graph = [[INF for _ in range(N)] for _ in range(N)]
        for i in range(N):
            self.graph[i][i] = 0

    def add_path(self, a, b, c):
        self.graph[a][b] = c
        self.graph[b][a] = c

    def get(self, a, b):
        return self.graph[a][b]

    def warshall_floyd(self):
        N = len(self.graph)
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    self.graph[i][j] = min(self.graph[i][j], self.graph[i][k]+self.graph[k][j])

path = Graph(N)
for _ in range(M):
    A, B, C = map(int, input().split())
    path.add_path(A-1, B-1, C)
path.warshall_floyd()
aid = Graph(N)
for i in range(N):
    for j in range(i+1, N):
        if path.get(i, j) <= L:
            aid.add_path(i, j, 1)
aid.warshall_floyd()
Q = int(input())
for _ in range(Q):
    s, t = map(int, input().split())
    ans = aid.get(s-1, t-1)
    if ans == INF:
        print(-1)
    else:
        print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq
from collections import deque

n, m, full = map(int, input().split())
edges = [[]*n for _ in range(n)]

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


def dijkstra(num_of_node, edge, start, limit):
    distance = [float('INF')] * num_of_node
    reachable = []
    distance[start] = 0
    todo = []
    heapq.heapify(todo)
    heapq.heappush(todo, [0, start])

    while todo:
        d, node = heapq.heappop(todo)
        if d > limit:
            break
        reachable.append(node)
        for new_node, cost in edge[node]:
            if distance[new_node] > d + cost:
                distance[new_node] = d + cost
                heapq.heappush(todo, [d+cost, new_node])

            else:
                continue
    return reachable


L_edges = [[]*n for _ in range(n)]

for i in range(n):
    L_edges[i] = dijkstra(n, edges, i, full)

dist = [[float('INF')] * n for _ in range(n)]

for start in range(n):
    dist[start][start] = 0
    todo = deque([])
    todo.append([-1, start])

    while todo:
        d, node = todo.popleft()

        for new_node in L_edges[node]:
            if dist[start][new_node] > d + 1:
                dist[start][new_node] = d + 1
                todo.append([d+1, new_node])

            else:
                continue

Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    ans = dist[s-1][t-1]
    if ans == float('INF'):
        ans = -1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,M,L=map(int,input().split())
inf=float("inf")
distance=[[inf for n in range(N)] for n in range(N)]

for n in range(N):
    distance[n][n]=0

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

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

distance2=[[inf for n in range(N)] for n in range(N)]

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

for n in range(N):
    distance2[n][n]=0

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

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


class Node(object):

  def __init__(self):
    self.fixed = False
    self.supply = 300
    self.tank = 0
    self.edges = []

  def __repr__(self):
    return str(self)

  def __str__(self):
    return '{}/{}({})'.format(self.supply, self.tank, int(self.fixed))


def main():
  n, m, tank = map(int, input().split())
  nodes = [Node() for _ in range(n)]

  for _ in range(m):
    a, b, c = map(int, input().split())

    nodes[a - 1].edges.append((nodes[b - 1], c))
    nodes[b - 1].edges.append((nodes[a - 1], c))

  results = [[None] * len(nodes) for _ in range(len(nodes))]

  for start in range(len(nodes)):
    for node in nodes:
      node.fixed = False
      node.supply = 300
      node.tank = 0

    nodes[start].supply = 0
    nodes[start].tank = tank

    while True:
      targets = [n for n in nodes if not n.fixed ]

      if len(targets) == 0:
        break

      target = min(targets, key=lambda n: (n.supply, -n.tank))
      target.fixed = True

      for n, d in target.edges:
        if n.fixed or d > tank:
          continue

        if d > target.tank:
          new_supply = target.supply + 1
          new_tank = tank - d
        else:
          new_supply = target.supply
          new_tank = target.tank - d

        if (new_supply, -new_tank) < (n.supply, -n.tank):
          n.supply = new_supply
          n.tank = new_tank

    for end in range(len(nodes)):
      results[start][end] = nodes[end].supply

  for _ in range(int(input())):
    start, end = map(int, input().split())

    if results[start - 1][end - 1] == 300:
      print(-1)
    else:
      print(results[start - 1][end - 1])


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
def slove():
    import sys
    input = sys.stdin.readline
    n, m, l = list(map(int, input().rstrip('\n').split()))
    INF = 10 ** 11
    w = [[INF] * n for _ in range(n)]
    wl = [[INF] * n for _ in range(n)]

    for i in range(n):
        w[i][i] = 0

    for i in range(m):
        a, b, c = list(map(int, input().rstrip('\n').split()))
        if c <= l:
            w[a - 1][b - 1] = c
            w[b - 1][a - 1] = c

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

    for i in range(n):
        for j in range(n):
            if w[i][j] <= l:
                wl[i][j] = 1
    for i in range(n):
        for j in range(n):
            for k in range(n):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        if wl[s-1][t-1] == INF:
            print(-1)
        else:
            print(wl[s-1][t-1] - 1)


if __name__ == '__main__':
    slove()

Submission status: Time Limit Exceeded

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

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

INF = 10 ** 10

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

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

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

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

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

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

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

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

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

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

Submission status: 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([None] * (n + 1))
	ds.append([None] * (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):
		if ds[i][k] is None:
			continue
		for j in range(1, n + 1):
			if ds[k][j] is None:
				continue
			if ds[i][j] is None or 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] is None or l < ds[i][j]:
			ds[i][j] = None
		else:
			ds[i][j] = 1
		
for k in range(1, n + 1):
	for i in range(1, n + 1):
		if ds[i][k] is None:
			continue
		for j in range(1, n + 1):
			if ds[k][j] is None:
				continue
			if ds[i][j] is None or 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]
	
	if d is None:
		print(-1)
	else:
		print(d - 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()

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)
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1]])
    else:
        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:
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()

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)
        ans.append([s_t_index[i][2], d.dist[s_t_index[i][1]-1]])
    else:
        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:
from collections import deque
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split())
load = [[]for i in range(N)]
for _ in range(M):
    a,b,c = map(int,input().split())
    if c <= L:
        load[a-1].append([b-1,c])
        load[b-1].append([a-1,c])
cost =[[L*N+1]*N for i in range(N)]
for i in range(N):
    queue = deque([i])
    cost[i][i] = 0
    while(queue):
        q = queue.popleft()
        gas = cost[i][q]
        for t,c in load[q]:
            if gas//L < (gas+c-1)//L :
                newc = (gas//L+1)*L+c
            else:
                newc = gas+c
            if newc < cost[i][t]:
                cost[i][t] = newc
                queue.append(t)
Q = int(input())
for _ in range(Q):
    s,t = map(int,input().split())
    ans = cost[s-1][t-1]
    if ans > L*N:
        print(-1)
    else:
        print((ans-1)//L)

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):
		if ds[i][k] == 10 ** 20:
			continue
		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):
		if ds[i][k] == 10 ** 20:
			continue
		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
input=sys.stdin.readline
n,m,l=map(int,input().split())
INF=10**10
graph=[[INF for i in range(n)] for j in range(n)]
fuel=[[INF for i in range(n)] for j in range(n)]
for i in range(n):
    graph[i][i]=0
for i in range(m):
    a,b,c=map(int,input().split())
    a-=1;b-=1
    if c>l:continue
    graph[a][b],graph[b][a]=c,c
for i in range(n):
  for j in range(n):
    for k in range(n):
      graph[j][k]=min(graph[j][k],graph[j][i]+graph[i][k])
for i in range(n):
    for j in range(n):
        if graph[i][j]<=l:
            fuel[i][j]=1
for i in range(n):
  for j in range(n):
    for k in range(n):
      fuel[j][k]=min(fuel[j][k],fuel[j][i]+fuel[i][k])
q=int(input())
for i in range(q):
    s,t=map(int,input().split())
    s-=1;t-=1
    if fuel[s][t]==INF:print(-1)
    else:print(fuel[s][t]-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
INF = float('inf')

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

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

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

sol()

Submission status: Time Limit Exceeded

Solution code:
import sys
imput = sys.stdin.readline
def func(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])
    return d
N,M,L = map(int,input().split())
road = [[float('inf')]*N for i in range(N)]
for i in range(N):
    road[i][i] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    road[a-1][b-1] = c
    road[b-1][a-1] = c
road = func(road)
ans = [[float("inf")]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        if road[i][j] <= L:
            ans[i][j] = 1
ans = func(ans)
for i in range(int(input())):
    a,b = map(int,input().split())
    o = ans[a-1][b-1]
    if o == float('inf'):
        print(-1)
    else:
        print(o-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
INF = float('inf')

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

    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 = [fuel[start - 1][end - 1] - 1 if fuel[start - 1][end - 1] != INF else -1 for start, end in ST]
    for a in ans:
        print(a)

sol()

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
from operator import itemgetter
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10**9 + 7
INF = float('inf')

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

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


sol()