Problem:


Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

3 2 5
1 2 3
2 3 3
2
3 2
1 3

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

5 4 4
1 2 2
2 3 2
3 4 3
4 5 2
20
2 1
3 1
4 1
5 1
1 2
3 2
4 2
5 2
1 3
2 3
4 3
5 3
1 4
2 4
3 4
5 4
1 5
2 5
3 5
4 5

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0



Sample input:
3 2 5
1 2 3
2 3 3
2
3 2
1 3


Sample output:
0
1

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq as h

stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
nl = lambda: list(map(int, stdin.readline().split()))
nm = lambda: map(int, stdin.readline().split())

def main():
    n,m,l = nm()
    g = [list() for _ in range(n+1)]
    ans = [0]
    for _ in range(m):
        a,b,c = nm()
        if c > l:
            continue
        g[a].append((b,c))
        g[b].append((a,c))
    q = int(input())
    
    def move(tup,cost):
        if tup[1] + cost > 0:
            return (tup[0]+1,cost-l)
        return (tup[0],tup[1]+cost)
    
    for st in range(1,n+1):
        dist = [-1]*(n+1)
        que = [([0,-l],st)]
        while que:
            tup,v = h.heappop(que)
            if dist[v] != -1 and dist[v] < tup:
                continue
            dist[v] = tup
            for x,c in g[v]:
                new = move(tup,c)
                if new != -1 and dist[x] == -1:
                    h.heappush(que,(new,x))
        ans.append(dist)
    
    for _ in range(q):
        s,t = nm()
        if ans[s][t] == -1:
            print(-1)
        else:
            print(ans[s][t][0])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

input = sys.stdin.readline

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

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

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

inf = n + 10

memo = [None] * n

q = int(input())

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

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

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

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

    if memo[s] is not None:
        if memo[s][t] >= inf:
            print(-1)
        else:
            print(memo[s][t])

    else:
        dq = deque()
        dq.append((s, max_tank, 0, -1))

        ans = inf
        while dq:
            v, tank, take, parent = dq.popleft()
            if (d[v] < take) or (d[v] == take and remains[v] > tank):
                continue

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

        memo[s] = d

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,M,L = inpl()
cost = [[INF]*N for _ in range(N)]
for i in range(N):
    cost[i][i] = 0

for _ in range(M):
    a,b,c = inpl()
    a,b = a-1,b-1
    cost[a][b] = c
    cost[b][a] = c

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

# print(cost)

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


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


Q = inp()
ans = []
for _ in range(Q):
    s,t = inpl()
    tmp = cost[s-1][t-1]
    if tmp == INF:
        print(-1)
    else:
        print(tmp-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

def main():
	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 pi in P:
		if pi[2]<=L:
			neighbor[pi[0]-1].append((pi[1]-1,pi[2]))
			neighbor[pi[1]-1].append((pi[0]-1,pi[2]))

	start = 0
	end = 2

	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
			for i in queue:				# target node
				oc, om = fuel[i]
				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)

					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 fuel[end][0]==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:
import heapq as hq

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

out_link = {i: set() for i in range(N)}
min_length = {(i, j): -1 for i in range(N) for j in range(N)}


for _ in range(M):
    A, B, C = map(int, input().split())
    if C > L:
        continue

    A -= 1
    B -= 1
    out_link[A].add((B, C))
    out_link[B].add((A, C))


def should_supply(now_cost, next_cost):
    if now_cost % L == 0:
        return False

    return (now_cost - 1) // L != (next_cost - 1) // L


def search(S):
    already = set()
    H = [(0, S)]
    while H:
        c, p = hq.heappop(H)
        if p in already:
            continue

        already.add(p)
        min_length[(S, p)] = (c - 1) // L
        min_length[(p, S)] = (c - 1) // L

        for q, add_cost in out_link[p]:
            if q in already:
                continue
            next_cost = c + add_cost
            if should_supply(c, next_cost):
                next_cost = (c // L + 1) * L + add_cost

            hq.heappush(H, (next_cost, q))


calced_s = set()
Q = int(input())
ans = ""
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    if s not in calced_s:
        search(s)
        calced_s.add(s)
    res = min_length[(s, t)]
    ans += str(res) + "\n"

print(ans)

Submission status: Time Limit Exceeded

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

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

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

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

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

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

Submission status: Time Limit Exceeded

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

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

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

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

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

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

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int, input().strip().split(' '))
G = [[float('inf') for _ in range(N)] for _ in range(N)]
for _ in range(M):
  A,B,C = map(int, input().strip().split(' '))
  if C > L: continue
  A,B = A-1,B-1
  G[A][B] = C
  G[B][A] = C
  
def DFS(state, T, visited):  # 今の状態(町、残燃料、給油回数)、目的地、訪問済み
  now, now_fuel, now_ref = state
  if G[now][T] != float('inf'):  # １hopで行けるなら、その方が良い
    if G[now][T] > now_fuel:
      return now_ref+1
    else:
      return now_ref
  res = []
  
  for next_ in set(range(N))-visited-{T}:
    if G[now][next_] != float('inf'):
      if G[now][next_] > now_fuel:  # 給油する
        next_fuel = L-G[now][next_]
        next_ref = now_ref+1
      else:  # 給油しない
        next_fuel = now_fuel-G[now][next_]
        next_ref = now_ref
      next_visited = visited|{next_}
      res.append(DFS((next_, next_fuel, next_ref), T, next_visited))
  if len(res) > 0:
    return min(res)
  else:
    return float('inf')

  
Q = int(input().strip())
for _ in range(Q):
  S,T = map(int, input().strip().split(' '))
  S,T = S-1,T-1
  ans = DFS((S, L, 0),T,{S})
  print(-1 if ans == float('inf') else ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

N, M, L = map(int, input().split())
adj = [set() for _ in range(N)]
roads = [[-1]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    if c <= L:  # 移動出来ない経路は消す
        roads[a-1][b-1] = c
        roads[b-1][a-1] = c
        adj[a-1].add(b-1)
        adj[b-1].add(a-1)


def calc_ans(start, end):
    dist = [[-1]*(N+1) for _ in range(N)]  # dist[i][j] iまで給油j会で行った時の残りの最大値
    dist[start][0] = L
    Q = [[0, start]]  # (給油回数、current node)
    while Q:
        kyuyu, cur_node = heapq.heappop(Q)
        if cur_node == end:
            return kyuyu
        remain = dist[cur_node][kyuyu]
        assert remain != -1
        for next in adj[cur_node]:
            # 給油せずにいく
            to_next = roads[cur_node][next]
            if dist[next][kyuyu] == -1:
                if to_next <= remain:  # 給油なしでいける
                    dist[next][kyuyu] = remain-to_next
                    heapq.heappush(Q, [kyuyu, next])
            else:
                cur_cost = dist[next][kyuyu]
                if to_next-remain > cur_cost:
                    dist[next][kyuyu] = to_next-cur_cost
                    Q.append([kyuyu, next])
                    heapq.heappush(Q, [kyuyu, next])
            #　給油していく
            if kyuyu+1 <= N and dist[next][kyuyu+1] == -1:
                dist[next][kyuyu+1] = L-to_next
                heapq.heappush(Q, [kyuyu+1, next])
            elif kyuyu+1 <= N:
                cur_cost = dist[next][kyuyu+1]
                if L-to_next > cur_cost:
                    dist[next][kyuyu] = L-to_next
                    heapq.heappush(Q, [kyuyu+1, next])

    return -1


Q = int(input())
query = [list(map(lambda x:int(x)-1, input().split())) for _ in range(Q)]

for s, t in query:
    print(calc_ans(s, t))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
N, M, L = inpl()
road = [[] for _ in range(N)]
for i in range(M):
    A, B, C = inpl()
    if C <= L:
        road[A-1].append((B-1,C))
        road[B-1].append((A-1,C))
minimum = [ [(-1,0)]*N for _ in range(N)]
for i in range(N):
    minimum[i][i] = (0,0)

Q = int(input())
ST = [inpl() for _ in range(Q)]
starts = set([ s-1 for s,t in ST])
for start in starts:
    prev = {start}
    while prev:
        cur = set()
        for p in prev:
            for q, c in road[p]:
                pn, pred = minimum[start][p]
                qn, qred = minimum[start][q]
                if pred + c > L:
                    qn2, qred2 = pn + 1, c
                else:
                    qn2, qred2 = pn, pred + c
                if qn < 0 or qn2 < qn or (qn2==qn and qred2 < qred):
                    minimum[start][q] = qn2, qred2
                    cur.add(q)
        prev = cur

for s,t in ST:
    print(minimum[s-1][t-1][0])

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq

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

out_link = {i: set() for i in range(N)}
cost = {}
min_length = {(i, j): -1 for i in range(N) for j in range(N)}


for _ in range(M):
    A, B, C = map(int, input().split())
    if C > L:
        continue

    A -= 1
    B -= 1
    out_link[A].add(B)
    out_link[B].add(A)
    cost[(min(A, B), max(A, B))] = C


def should_supply(now_cost, next_cost):
    if now_cost % L == 0:
        return False

    return (now_cost - 1) // L != (next_cost - 1) // L


def search(S):
    already = set()
    H = [(0, S)]
    while H:
        c, p = hq.heappop(H)
        if p in already:
            continue

        already.add(p)
        min_length[(S, p)] = (c - 1) // L
        min_length[(p, S)] = (c - 1) // L

        for q in out_link[p]:
            if q in already:
                continue
            add_cost = cost[min(p, q), max(p, q)]
            next_cost = c + add_cost
            if should_supply(c, next_cost):
                next_cost = (c // L + 1) * L + add_cost

            hq.heappush(H, (next_cost, q))


calced_s = set()
Q = int(input())
ans = ""
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    if s not in calced_s:
        search(s)
        calced_s.add(s)
    res = min_length[(s, t)]
    ans += str(res) + "\n"

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
N,M,L = map(int,input().split())
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 =[[float('inf')]*N for i in range(N)]
for i in range(N):
    queue = deque([i])
    cost[i][i] = 0
    while(queue):
        q = queue.popleft()
        gas = cost[i][q]
        for t,c in load[q]:
            if gas//L < (gas+c-1)//L :
                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 == float('inf'):
        print(-1)
    else:
        print((ans-1)//L)

Submission status: Time Limit Exceeded

Solution code:
import heapq
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

N, M, L = map(int, input().split())
adj = [set() for _ in range(N)]
roads = [[-1]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    if c <= L:  # 移動出来ない経路は消す
        roads[a-1][b-1] = c
        roads[b-1][a-1] = c
        adj[a-1].add(b-1)
        adj[b-1].add(a-1)


def calc_ans(start, end):
    dist = [[-1]*(N+1) for _ in range(N)]  # dist[i][j] iまで給油j会で行った時の残りの最大値
    dist[start][0] = L
    Q = [[0, start]]  # (給油回数、current node)
    while Q:
        kyuyu, cur_node = heapq.heappop(Q)
        if cur_node == end:
            return kyuyu
        remain = dist[cur_node][kyuyu]
        assert remain != -1
        for next in adj[cur_node]:
            # 給油せずにいく
            to_next = roads[cur_node][next]
            if dist[next][kyuyu] == -1:
                if to_next <= remain:  # 給油なしでいける
                    dist[next][kyuyu] = remain-to_next
                    heapq.heappush(Q, [kyuyu, next])
            else:
                cur_cost = dist[next][kyuyu]
                if to_next-remain > cur_cost:
                    dist[next][kyuyu] = to_next-cur_cost
                    Q.append([kyuyu, next])
                    heapq.heappush(Q, [kyuyu, next])
            #　給油していく
            if kyuyu+1 <= N and dist[next][kyuyu+1] == -1:
                dist[next][kyuyu+1] = L-to_next
                heapq.heappush(Q, [kyuyu+1, next])
            elif kyuyu+1 <= N:
                cur_cost = dist[next][kyuyu+1]
                if L-to_next > cur_cost:
                    dist[next][kyuyu] = L-to_next
                    heapq.heappush(Q, [kyuyu+1, next])

    for i in range(N):
        if dist[end][i] >= 0:
            return i
    return -1


Q = int(input())
query = [list(map(lambda x:int(x)-1, input().split())) for _ in range(Q)]

for s, t in query:
    print(calc_ans(s, t))

Submission status: Time Limit Exceeded

Solution code:
import sys
fastinput = sys.stdin.readline
N,M,L = [int(i) for i in fastinput().split()]
togo = [[] for i in range(N)]
for i in range(M):
    A,B,C = [int(i) for i in fastinput().split()]
    togo[A-1].append((B-1,C))
    togo[B-1].append((A-1,C))
Q = int(fastinput())
for q in range(Q):
    s,t = [int(i)-1 for i in fastinput().split()]
    #Djikstra
    dist = [(-10000000000,0) for i in range(N)]#(－補給回数,残り燃料)(大きいほどえらい)
    kakutei = [False]*N
    dist[s] = (0,L)
    kakutei[s] = True
    curpos = s 
    for hoge in range(N):
        curkaisu,curfuel = dist[curpos]
        for p,d in togo[curpos]:
            if kakutei[p]:continue
            if curfuel < d:
                newkaisu = curkaisu - 1
                newfuel = L-d
            else:
                newkaisu = curkaisu
                newfuel = curfuel-d
            if (newkaisu,newfuel)>dist[p]:
                dist[p] = (newkaisu,newfuel)
        curmax = (-1,(-100000,0))
        for p,distance in enumerate(dist):
            if kakutei[p]:continue
            if curmax[1]<distance:
                curmax = (p,distance)
        kakutei[curmax[0]] = True
        curpos = curmax[0]
    ans = -dist[t][0]
    if ans ==10000000000:ans = -1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import *
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def main():
    n, m, l = map(int, input().split())
    to = defaultdict(list)
    for _ in range(m):
        a, b, c = map(int, input().split())
        a, b = a - 1, b - 1
        to[a].append((b, c))
        to[b].append((a, c))
    q = int(input())
    st = []
    idx = [[-1] * n for _ in range(n)]
    qc = [0] * n
    for i in range(q):
        s, t = map(int, input().split())
        s, t = s - 1, t - 1
        idx[s][t] = i
        qc[min(s, t)] += 1

    # for x in idx:
    # print(x)
    # print(qc)

    ans = [-1] * q
    for s in range(n):
        # print(ans)
        cnt = qc[s]
        if cnt == 0: continue
        hp = []
        heappush(hp, (0, -l, s))
        fin = [False] * n
        while cnt > 0 and hp:
            k, g, u = heappop(hp)
            if fin[u]: continue
            fin[u] = True
            g = -g
            i = idx[s][u]
            if i != -1:
                ans[i] = k
                idx[s][u] = -1
                cnt -= 1
            i = idx[u][s]
            if i != -1:
                ans[i] = k
                idx[u][s] = -1
                cnt -= 1
            for ku, c in to[u]:
                if fin[ku]: continue
                if g - c >= 0:
                    heappush(hp, (k, c - g, ku))
                elif l - c>=0:
                    heappush(hp, (k + 1, -l + c, ku))
    print(*ans,sep="\n")

main()

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq

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

out_link = {i: set() for i in range(N)}
cost = {}
min_length = {}


for _ in range(M):
    A, B, C = map(int, input().split())
    if C > L:
        continue

    A -= 1
    B -= 1
    out_link[A].add(B)
    out_link[B].add(A)
    cost[(min(A, B), max(A, B))] = C


def should_supply(now_cost, next_cost):
    if now_cost % L == 0:
        return False

    return (now_cost - 1) // L != (next_cost - 1) // L


def search(S, G):
    already = set()
    H = [(0, S)]
    while H:
        c, p = hq.heappop(H)
        if p in already:
            continue

        already.add(p)
        min_length[(S, p)] = (c - 1) // L
        min_length[(p, S)] = (c - 1) // L
        if p == G:
            return (c - 1) // L

        for q in out_link[p]:
            if q in already:
                continue
            add_cost = cost[min(p, q), max(p, q)]
            next_cost = c + add_cost
            if should_supply(c, next_cost):
                next_cost = (c // L + 1) * L + add_cost

            hq.heappush(H, (next_cost, q))

    return -1


Q = int(input())
ans = ""
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    if (s, t) in min_length:
        res = min_length[(s, t)]
    else:
        res = search(s, t)
    min_length[(t, s)] = res
    ans += str(res) + "\n"

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


class SolveE:

    def __init__(self, n, le):
        self.n = n
        self.le = le
        self.g1 = [[] for _ in range(n)]
        self.g2 = [[] for _ in range(n)]

    def add_edge(self, a, b, c):
        self.g1[a].append([b, c])

    def pre_compute(self):
        for i in range(self.n):
            d_list = [self.le + 1] * self.n
            d_list[i] = 0
            queue = deque([i])
            while len(queue) > 0:
                p = queue.popleft()
                for q, r in self.g1[p]:
                    if d_list[q] > d_list[p] + r and d_list[p] + r <= self.le:
                        d_list[q] = d_list[p] + r
                        queue.append(q)
            for j in range(self.n):
                if 0 < d_list[j] <= self.le:
                    self.g2[i].append(j)

    def query(self, s, t):
        d_list = [10000] * self.n
        d_list[s] = 0
        queue = deque([s])
        while len(queue) > 0:
            p = queue.popleft()
            for q in self.g2[p]:
                if q == t:
                    return d_list[p] + 1
                if d_list[q] > d_list[p] + 1:
                    d_list[q] = d_list[p] + 1
                    queue.append(q)
        return 0


def main():
    n, m, le = map(int, input().split())
    sol = SolveE(n, le)
    for _ in range(m):
        a, b, c = map(int, input().split())
        sol.add_edge(a - 1, b - 1, c)
        sol.add_edge(b - 1, a - 1, c)

    sol.pre_compute()

    q = int(input())
    res_list = [0] * q
    for i in range(q):
        s, t = map(int, input().split())
        res = sol.query(s - 1, t - 1)
        res_list[i] = res - 1

    for r in res_list:
        print(r)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import heapq as hq

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

out_link = {i: set() for i in range(N)}
cost = {}
min_length = {}


for _ in range(M):
    A, B, C = map(int, input().split())
    if C > L:
        continue

    A -= 1
    B -= 1
    out_link[A].add(B)
    out_link[B].add(A)
    cost[(min(A, B), max(A, B))] = C


def should_supply(now_cost, next_cost):
    if now_cost % L == 0:
        return False

    return (now_cost - 1) // L != (next_cost - 1) // L


def search(S, G):
    already = set()
    H = [(0, S)]
    while H:
        c, p = hq.heappop(H)
        if p in already:
            continue

        already.add(p)
        min_length[(S, p)] = (c - 1) // L
        min_length[(p, S)] = (c - 1) // L
        if p == G:
            return (c - 1) // L

        for q in out_link[p]:
            add_cost = cost[min(p, q), max(p, q)]
            next_cost = c + add_cost
            if should_supply(c, next_cost):
                next_cost = (c // L + 1) * L + add_cost

            hq.heappush(H, (next_cost, q))

    return -1


Q = int(input())
ans = ""
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    if (s, t) in min_length:
        res = min_length[(s, t)]
    else:
        res = search(s, t)
    min_length[(t, s)] = res
    ans += str(res) + "\n"

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,M,L = [int(i) for i in input().split()]
togo = [[] for i in range(N)]
for i in range(M):
    A,B,C = [int(i) for i in input().split()]
    togo[A-1].append((B-1,C))
    togo[B-1].append((A-1,C))
Q = int(input())
for q in range(Q):
    s,t = [int(i)-1 for i in input().split()]
    #Djikstra
    dist = [(-10000000000,0) for i in range(N)]#(－補給回数,残り燃料)(大きいほどえらい)
    kakutei = [False]*N
    dist[s] = (0,L)
    kakutei[s] = True
    curpos = s 
    for hoge in range(N):
        curkaisu,curfuel = dist[curpos]
        for p,d in togo[curpos]:
            if kakutei[p]:continue
            if curfuel < d:
                newkaisu = curkaisu - 1
                newfuel = L-d
            else:
                newkaisu = curkaisu
                newfuel = curfuel-d
            if (newkaisu,newfuel)>dist[p]:
                dist[p] = (newkaisu,newfuel)
        curmax = (-1,(-100000,0))
        for p,distance in enumerate(dist):
            if kakutei[p]:continue
            if curmax[1]<distance:
                curmax = (p,distance)
        kakutei[curmax[0]] = True
        curpos = curmax[0]
    ans = -dist[t][0]
    if ans ==10000000000:ans = -1
    print(ans)