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
N, M, L = map(int, input().split())
G = [[float('inf')] * N for i in range(N)]
for i in range(M):
    a, b, c = map(int, sys.stdin.readline().split())
    a, b = a - 1, b - 1
    G[a][b] = c
    G[b][a] = c


# 全点間最短距離を計算
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])


# コストL以下で移動可能な頂点間にコスト１の辺を張る
E = [[float('inf')] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if G[i][j] <= L:
            E[i][j] = 1


# そのグラフの全点間最短距離を求める
for k in range(N):
    for i in range(N):
        for j in range(N):
            E[i][j] = min(E[i][j], E[i][k] + E[k][j])


# クエリに答えていく
Q = int(input())
for i in range(Q):
    s, t = map(int, sys.stdin.readline().split())
    s, t = s - 1, t - 1
    print(E[s][t] - 1 if E[s][t] != float('inf') else - 1)

Submission status: Time Limit Exceeded

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


# 全点間最短距離を計算
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])


# コストL以下で移動可能な頂点間にコスト１の辺を張る
E = [[float('inf')] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if G[i][j] <= L:
            E[i][j] = 1


# そのグラフの全点間最短距離を求める
for k in range(N):
    for i in range(N):
        for j in range(N):
            E[i][j] = min(E[i][j], E[i][k] + E[k][j])


# クエリに答えていく
Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    s, t = s - 1, t - 1
    print(E[s][t] - 1 if E[s][t] != float('inf') else - 1)

Submission status: Time Limit Exceeded

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


# 全点間最短距離を計算
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 in range(N):
    G[i][i] = 0

# コストL以下で移動可能な頂点間にコスト１の辺を張る
E = [[float('inf')] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if G[i][j] <= L:
            E[i][j] = 1


# そのグラフの全点間最短距離を求める
for k in range(N):
    for i in range(N):
        for j in range(N):
            E[i][j] = min(E[i][j], E[i][k] + E[k][j])


# クエリに答えていく
Q = int(input())
for i in range(Q):
    s, t = map(int, input().split())
    s, t = s - 1, t - 1
    print(E[s][t] - 1 if E[s][t] != float('inf') else - 1)

Submission status: Time Limit Exceeded

Solution code:
def travel_by_car():
    INF = float('inf')
    
    def warshall_floyd(N, dist):
        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])
    
    N, M, L = map(int, input().split())
    dist = [[INF] * N for _ in range(N)]
    for _ in range(M):
        A, B, C = [int(i) for i in input().split()]
        A -= 1
        B -= 1
        dist[A][B] = dist[B][A] = C
    
    for i in range(N):
        dist[i][i] = 0
    
    warshall_floyd(N, dist)

    for i in range(N):
        for j in range(N):
            if dist[i][j] <= L:
                dist[i][j] = 1
            else:
                dist[i][j] = INF
    
    warshall_floyd(N, dist)
    
    Q = int(input())    
    for _ in range(Q):
        s, t = map(int, input().split())
        ans = dist[s-1][t-1]
        if ans == INF:
            print(-1)
        else:
            print(ans - 1)


def main():
  travel_by_car()


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
town_graph = {}
road_graph = {}

N,M,L = list(map(int, input().split()))
# N = num towns
# M = num roads
# L = fuel tank capacity

for _ in range(M):
    A,B,C = list(map(int, input().split()))
    if not A in town_graph:
        town_graph[A] = [B]
    else:
        town_graph[A].append(B)
    if not B in town_graph:
        town_graph[B] = [A]
    else:
        town_graph[B].append(B)

    road_graph[tuple(sorted([A,B]))] = C
    road_graph[tuple([A,A])] = 0
    road_graph[tuple([B,B])] = 0

Q = int(input())
queries = []
for _ in range(Q):
    queries.append(list(map(int,input().split())))

#print(town_graph)
#print(road_graph)

# initialize remaining road_graph distances:
for i in range(1, N+1):
    for j in range(1, N+1):
        key = tuple(sorted([i,j]))
        if not key in road_graph:
            road_graph[key] = float('inf')

# use flord warshall to find min path between all towns
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if road_graph[tuple(sorted([i,j]))] > road_graph[tuple(sorted([i,k]))] + road_graph[tuple(sorted([k,j]))]:
                road_graph[tuple(sorted([i,j]))] = road_graph[tuple(sorted([i,k]))] + road_graph[tuple(sorted([k,j]))]

#print(road_graph)

# if the two towns can be travelled to on one tank, add to our fuel graph with distance 1
fuel_graph = road_graph.copy()
for town_pair in road_graph:
    if road_graph[town_pair] <= L:
        fuel_graph[town_pair] = 1
    else:
        fuel_graph[town_pair] = float('inf')

#print(road_graph)
#print(fuel_graph)

# use flord warshall to find min number of fuel tanks to travel between two towns
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            if fuel_graph[tuple(sorted([i,j]))] > fuel_graph[tuple(sorted([i,k]))] + fuel_graph[tuple(sorted([k,j]))]:
                fuel_graph[tuple(sorted([i,j]))] = fuel_graph[tuple(sorted([i,k]))] + fuel_graph[tuple(sorted([k,j]))]
#print(fuel_graph)
for query in queries:
    num_tanks = fuel_graph[tuple(sorted(query))] - 1
    if num_tanks != float('inf'):
        print(num_tanks)
    else:
        print("-1")

Submission status: Time Limit Exceeded

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

def warshal_floyd(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())
d = [[float('inf') for i in range(n)] for j 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, b = a-1, b-1
  d[a][b] = c
  d[b][a] = c
  
d = warshal_floyd(d)

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

d2 = warshal_floyd(d2)

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

Submission status: Time Limit Exceeded

Solution code:
import sys,collections as cl,bisect as bs
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())

def wa(d):
    for k in range(len(d)):
        for i in range(len(d)):
            for j in range(len(d)):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d

def on():
    N,M,L = m()

    e = [[Max for i in range(N)]for j in range(N)]

    for i in range(M):
        a,b,c = m()
        e[a-1][b-1] = c
        e[b-1][a-1] = c

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

    d = wa(e)


    E = [[Max for i in range(N)]for j in range(N)]

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

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

    E = wa(E)
    q = onem()
    for i in range(q):
        s,t = m()
        if E[s-1][t-1] == Max:
            print(-1)
        else:
            print(E[s-1][t-1]-1)

if __name__ == "__main__":
    on()

Submission status: Time Limit Exceeded

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def wa(d):
    for k in range(len(d)):
        for i in range(len(d)):
            for j in range(len(d)):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d

def on():
    N,M,L = m()

    e = [[Max for i in range(N)]for j in range(N)]

    for i in range(M):
        a,b,c = m()
        e[a-1][b-1] = c
        e[b-1][a-1] = c

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

    d = wa(e)


    E = [[Max for i in range(N)]for j in range(N)]

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

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

    E = wa(E)
    q = onem()
    for i in range(q):
        s,t = m()
        if E[s-1][t-1] == Max:
            print(-1)
        else:
            print(E[s-1][t-1]-1)

if __name__ == "__main__":
    on()

Submission status: Time Limit Exceeded

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def wa(d):
    for k in range(len(d)):
        for i in range(len(d)):
            for j in range(len(d)):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d

N,M,L = m()

e = [[Max for i in range(N)]for j in range(N)]

for i in range(M):
    a,b,c = m()
    e[a-1][b-1] = c
    e[b-1][a-1] = c

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

d = wa(e)


E = [[Max for i in range(N)]for j in range(N)]

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

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

E = wa(E)
q = onem()
for i in range(q):
    s,t = m()
    if E[s-1][t-1] == Max:
        print(-1)
    else:
        print(E[s-1][t-1]-1)

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

class SegmentTree:
    def __init__(self, value=[], N=0, comp=lambda x,y: x<=y, reverse=False):
        M = max(len(value),N)
        N = 2**(len(bin(M))-3)
        if N < M: N *= 2
        self.N = N
        self.node = [0] * (2*N-1)
        for i in range(N):
            self.node[N-1+i] = i
        self.value = [None] * N
        for i, v in enumerate(value):
            self.value[i] = v
        self.comp = lambda x, y: True if y is None else False if x is None else comp(x,y)^reverse
        for i in range(N-2,-1,-1):
            left_i, right_i = self.node[2*i+1], self.node[2*i+2]
            left_v, right_v = self.value[left_i], self.value[right_i]
            self.node[i] = left_i if self.comp(left_v, right_v) else right_i

    def update(self, n, v):
        self.value[n] = v
        i = (self.N-1) + n
        while i > 0:
            i = (i-1)//2
            left_i, right_i = self.node[2*i+1], self.node[2*i+2]
            left_v, right_v = self.value[left_i], self.value[right_i]
            new_i = left_i if self.comp(left_v, right_v) else right_i
            if new_i == self.node[i] and new_i != n:
                break
            else:
                self.node[i] = new_i

    def at(self, n):
        if n is None:
            return None
        else:
            return self.value[n]

    def query(self, l=0, r=-1):
        return self.at(self.query_index(l,r))

    def query_index(self, l=0, r=-1):
        if r < 0: r = self.N
        L = l + self.N; R = r + self.N
        s = None
        while L < R:
            if R & 1:
                R -= 1
                if self.comp(self.at(self.node[R-1]), self.at(s)):
                    s = self.node[R-1]
            if L & 1:
                if self.comp(self.at(self.node[L-1]), self.at(s)):
                    s = self.node[L-1]
                L += 1
            L >>= 1; R >>= 1
        return s

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]*N for _ in range(N)]
for i in range(N):
    minimum[i][i] = 0

INF = 10**4
Q = int(input())
ST = [inpl() for _ in range(Q)]
starts = set([ s-1 for s,t in ST])
segtree = SegmentTree(N=N)
for start in starts:
    for i in range(N):
        segtree.update(i, (INF,0))
    segtree.update(start, (0,0))
    while True:
        p = segtree.query_index()
        pnred = segtree.at(p)
        if pnred is None:
            break
        else:
            pn, pred = pnred
            if pn >= INF:
                break
        minimum[start][p] = pn
        segtree.update(p, None)

        for q, c in road[p]:
            if segtree.at(q) is None:
                continue
            else:
                qn, qred = segtree.at(q)
            if pred + c > L:
                qn2, qred2 = pn + 1, c
            else:
                qn2, qred2 = pn, pred + c
            if qn < 0 or (qn2,qred2) < (qn,qred):
                segtree.update(q, (qn2, qred2))

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
from heapq import heappop, heappush
from collections import defaultdict

def dijkstra(start, goal, edges,
             start_distance=0,
             plus_func=lambda D,d: D+d):
    '''
    goal: int or list or set
    edges: list or dict
        edges[x] = (y, distance)
    '''
    q = [(start_distance, start)]
    done = set()
    if isinstance(goal, int):
        goal_set = {goal}
    else:
        goal_set = set(goal)
    ret = defaultdict(lambda: None)
    minimum = defaultdict(lambda: None)

    while q:
        D, x = heappop(q)
        if x in done:
            continue
        elif x in goal_set:
            ret[x] = D
            goal_set.remove(x)
            if len(goal_set) == 0:
                return ret
        done.add(x)
        for y, d in edges[x]:
            if not y in done:
                m = minimum[y]
                p = plus_func(D,d)
                if m is None or m > p:
                    heappush(q, (p, y))
                    minimum[y] = p
    return ret

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))
ans = [[None]*N for _ in range(N)]

Q = int(input())
ST = []
goals = [set() for _ in range(N)]
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))
    goals[s].add(t)

def plus(D, d):
    refuel, oil = D
    if oil + d > L:
        return (refuel+1, d)
    else:
        return (refuel, oil+d)

for s in range(N):
    if goals[s]:
        result = dijkstra(s, goals[s], road, (0,0), plus)
        for t in goals[s]:
            d = result[t]
            if d is None:
                ans[s][t] = -1
            else:
                ans[s][t] = result[t][0]

for s, t in ST:
    print(ans[s][t])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
import sys
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))
ans = [[-1]*N for _ in range(N)]

Q = int(input())
ST = []
goals = [set() for _ in range(N)]
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))
    goals[s].add(t)

for s in range(N):
    if not goals[s]:
        continue
    q = [((0,0), s)]
    done = [False]*N
    goal_n = len(goals[s])
    goal_flag = [False]*N
    for g in goals[s]:
        goal_flag[g] = True
    while q:
        D, x = heappop(q)
        refuel, oil = D
        if done[x]:
            continue
        elif goal_flag[x]:
            ans[s][x] = refuel
            goal_n -= 1
            if goal_n == 0:
                break
        done[x] = True
        for y, d in road[x]:
            if done[y]:
                continue
            if oil + d > L:
                heappush(q, ((refuel+1, d), y))
            else:
                heappush(q, ((refuel, oil+d), y))

for s, t in ST:
    print(ans[s][t])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
import sys
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))
ans = [[-1]*N for _ in range(N)]

Q = int(input())
ST = []
goals = [set() for _ in range(N)]
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))
    goals[s].add(t)

for s in range(N):
    if not goals[s]:
        continue
    q = [((0,0), s)]
    done = set()
    goal_set = set(goals[s])
    while q:
        D, x = heappop(q)
        refuel, oil = D
        if x in done:
            continue
        elif x in goal_set:
            ans[s][x] = refuel
            goal_set.remove(x)
            if len(goal_set) == 0:
                break
        done.add(x)
        for y, d in road[x]:
            if y in done:
                continue
            if oil + d > L:
                heappush(q, ((refuel+1, d), y))
            else:
                heappush(q, ((refuel, oil+d), y))

for s, t in ST:
    print(ans[s][t])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
from heapq import heappop, heappush
from collections import defaultdict

def dijkstra(start, goal, edges,
             start_distance=0,
             plus_func=lambda D,d: D+d):
    '''
    goal: int or list or set
    edges: list or dict
        edges[x] = (y, distance)
    '''
    q = [(start_distance, start)]
    done = set()
    if isinstance(goal, int):
        goal_set = {goal}
    else:
        goal_set = set(goal)
    ret = defaultdict(lambda: None)

    while q:
        D, x = heappop(q)
        if x in done:
            continue
        elif x in goal_set:
            ret[x] = D
            goal_set.remove(x)
            if len(goal_set) == 0:
                return ret
        done.add(x)
        for y, d in edges[x]:
            if not y in done:
                heappush(q, (plus_func(D,d), y))
    return ret

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))
ans = [[None]*N for _ in range(N)]

Q = int(input())
ST = []
goals = [set() for _ in range(N)]
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))
    goals[s].add(t)

def plus(D, d):
    refuel, oil = D
    if oil + d > L:
        return (refuel+1, d)
    else:
        return (refuel, oil+d)

for s in range(N):
    if goals[s]:
        result = dijkstra(s, goals[s], road, (0,0), plus)
        for t in goals[s]:
            d = result[t]
            if d is None:
                ans[s][t] = -1
            else:
                ans[s][t] = result[t][0]

for s, t in ST:
    print(ans[s][t])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def warshall_floyd(V, d):

    return d

INF = 10 ** 9
n, m, l = map(int, input().split())
d = [[INF for j in range(n + 1)] for i in range(n + 1)]
d2 = [[INF for j in range(n + 1)] for i in range(n + 1)]
for _ in range(m):
    i, j, c = map(int, input().split())
    d[i][j] = c
    d[j][i] = c
    if c <= l:
        d2[i][j] = 1
        d2[j][i] = 1

q = int(input())
Q = [list(map(int, input().split())) for _ in range(q)]

for k in range(1, n + 1):
    for i in range(1, n):
        for j in range(i, n + 1):
            dk = d[i][k] + d[k][j]
            if d[i][j] > dk:
                d[i][j] = dk
                d[j][i] = dk
                if dk <= l:
                    d2[i][j] = 1
                    d2[j][i] = 1

for k in range(1, n + 1):
    for i in range(1, n):
        for j in range(i, n + 1):
            dk = d2[i][k] + d2[k][j]
            if d2[i][j] > dk:
                d2[i][j] = dk
                d2[j][i] = dk

for i in range(q):
    s, t = Q[i]
    di = d2[s][t]
    if di >= INF:
        print(-1)
    else:
        print(di - 1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def warshall_floyd(V, d):
    for k in range(1, V + 1):
        for i in range(1, V):
            for j in range(i, V + 1):
                dk = d[i, k] + d[k, j]
                if d[i, j] > dk:
                    d[i, j] = dk
                    d[j, i] = dk
    return d

INF = 10 ** 9
n, m, l = map(int, input().split())
E = INF * np.ones([n + 1, n + 1], np.int)
for _ in range(m):
    i, j, c = map(int, input().split())
    E[i, j] = c
    E[j, i] = c

q = int(input())
Q = [list(map(int, input().split())) for _ in range(q)]

d = warshall_floyd(n, E)
E2 = (d <= l).astype(np.int)
E2[E2 == 0] = INF
d2 = warshall_floyd(n, E2)

for i in range(q):
    s, t = Q[i]
    di = d2[s, t]
    if di >= INF:
        print(-1)
    else:
        print(di - 1)

Submission status: Time Limit Exceeded

Solution code:
from math import *
def warshall_floyd(n, ad_table):
    """
    ワーシャルフロイド法
    :param n: 頂点の数
    :param ad_table: 隣接行列
    """
    for k in range(n):     # 経由する頂点
      for i in range(n):   # 始点
        for j in range(n): # 終点
          # i->jへの経路コストについて
          # i->jとi->k->jのうち          # コストの小さい方を採用
            ad_table[i][j] = min(ad_table[i][j],ad_table[i][k]+ad_table[k][j])
    return ad_table




n,m,l = map(int, input().split())
c = [[int(i) for i in input().split()] for i in range(m)]
q = int(input())
p = [[int(i) for i in input().split()] for i in range(q)]

# 経路コストの表を作成
table = [[1000000001 for _ in range(n)] for _ in range(n)]
for i in range(n):
    table[i][i] = 0


for i in range(len(c)):
    if c[i][2] <= l:
        table[c[i][0]-1][c[i][1]-1] = c[i][2]
        table[c[i][1]-1][c[i][0]-1] = c[i][2]





warshall_floyd(n, table)



table2 = [[1000000001 for _ in range(n)] for _ in range(n)]
for i in range(n):
    for j in range(n):
        if table[i][j] <= l:
            table2[i][j] = 1
            table2[i][j] = 1


warshall_floyd(n, table2)




for i in range(q):
    out = table2[p[i][0]-1][p[i][1]-1]
    if out == 1000000001:
        print(-1)
    else:
        print(out-1)

Submission status: Time Limit Exceeded

Solution code:
# 2019-11-19 10:28:31(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import array
# from scipy.misc import comb # (default: exact=False)
# import numpy as np 



INF = 10 ** 12

# V: number of vertices, cost: graph(dist[u][v] / time[u][v] / ...)
def warshall_floyd(V, cost):
    min_cost = cost
    for w in range(1, V+1): # way-point
        for s in range(1, V+1): # start
            for t in range(1, V+1): # goal
                min_cost[s][t] = min(min_cost[s][t], min_cost[s][w] + min_cost[w][t])
    return min_cost


def main():
    # stdin
    n, m, l = map(int, sys.stdin.readline().split())
    dist = [[None for _ in range(n+1)]] + [[None] + [INF for _ in range(n)] for _ in range(n)]
    for s in range(1,n+1):
        dist[s][s] = 0
    for _ in range(m):
        u, v, d = map(int, sys.stdin.readline().split())
        dist[u][v], dist[v][u] = min(dist[u][v], d), min(dist[v][u], d)
        # 問題の条件より、２点間の直経路が一つだけとは限らないので複数あった場合に最短を選択する処理
    
    q = int(sys.stdin.readline().rstrip())
    st = map(int, sys.stdin.read().split())
    st = zip(st, st)



    shortest_dist = warshall_floyd(n, dist)


    filling_times = [[None for _ in range(n+1)]] + [[None] + [INF for _ in range(n)] for _ in range(n)]
    for s in range(1, n+1):
        for t in range(1, n+1):
            if s == t:
                filling_times[s][t] = 0
            elif shortest_dist[s][t] <= l:
                filling_times[s][t] = 1
    
    min_filling_times = warshall_floyd(n, filling_times)
    for s, t in st:
        # 最初は満タンのため-1
        print(min_filling_times[s][t] - 1 if not min_filling_times[s][t] == INF else -1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict



def dijkstra(s,t,route,n,w,l):
    d = [float("inf")] * n
    d[s] = 0

    unusedlist = list(range(n))
      
    while True:
        max = float("inf")
        max_i = -1
        for i,item in enumerate(unusedlist):
            if d[item] < max:
                max = d[item]
                max_i = i
            
        if max_i == -1:
               break
           
        v = unusedlist[max_i]
        del unusedlist[max_i]

        e_l = d[v]
        subcost = route[v]
        if subcost == 0: continue
        for j in unusedlist: #range(n):
            try:
                cost = subcost[j]
            except:
                continue
            if cost == 0: continue

            if l-e_l%l >= cost:
                next_d = e_l + cost
            else:
                next_d = (1 + e_l//l)*l + cost
            d[j] = min(d[j],next_d)

    if not t in unusedlist:
        return (d[t]-1)//l
    else:
        return -1



if __name__ == '__main__':
    route = defaultdict(defaultdict)

    n,m,l = list(map(lambda x: int(x), input().split()))

    for i_num in range(m):
        a,b,c = list(map(lambda x: int(x), input().split()))

        if c > l:
            m -= 1
            continue
        else:
            route[a-1][b-1] = c
            route[b-1][a-1] = c
 
    q = int(input())

    for i_num in range(q):
        s,t = list(map(lambda x: int(x), input().split()))    
        print(dijkstra(s-1,t-1,route,n,m,l))

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
singular = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N): singular[i][i] = 0
for i in range(M):
    A, B, C = map(int, input().split())
    A, B = A-1, B-1
    singular[A][B] = C
    singular[B][A] = C

for k in range(N):
    for i in range(N):
        for j in range(N):
            singular[i][j] = min(singular[i][j], singular[i][k] + singular[k][j])
for i in range(N):
    for j in range(N):
        if singular[i][j] <= L:
            singular[i][j] = 0
        else:
            singular[i][j] = float('inf')

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

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

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
edges = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N): edges[i][i] = 0
for i in range(M):
    A, B, C = map(int, input().split())
    A, B = A-1, B-1
    edges[A][B] = C
    edges[B][A] = C

singular = [list(edges[j]) for j in range(N)]
for k in range(N):
    for i in range(N):
        for j in range(N):
            singular[i][j] = min(singular[i][j], singular[i][k] + singular[k][j])
for i in range(N):
    for j in range(N):
        if singular[i][j] <= L:
            singular[i][j] = 0
        else:
            singular[i][j] = float('inf')

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

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