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:



from scipy.sparse.csgraph import floyd_warshall as fw

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

S = [[float("inf") for i in range(N)] for i in range(N)]

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

Sdist = fw(S)

for i in range(N):
    for j in range(N):
        if Sdist[i][j]>L:
            Sdist[i][j] = float("inf")
        else:
            Sdist[i][j] = 1

Ssup = fw(Sdist)

Q = int(input())

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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import lil_matrix
import numpy

N,M,L=map(int, raw_input().split())
RG=lil_matrix((N,N))

for i in range(M):
    f,t,c = map(int, raw_input().split())
    RG[(f-1,t-1)] = c
    RG[(t-1,f-1)] = c

Rd = floyd_warshall(RG.tocsr())

vf = numpy.vectorize(lambda x: 1.0 if x <= L else float('inf'))

Fd = floyd_warshall(vf(Rd), directed=False)

Q=int(raw_input())
for i in range(Q):
    s, t = map(int, raw_input().split())
    v = Fd[s-1][t-1]
    if s == t:
        print (str(0))
    elif v == float('inf'):
        print (str(-1))
    else:
        print (str(int(v-1)))

Submission status: Time Limit Exceeded

Solution code:
n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]
q=int(input())
st=[list(map(int,input().split())) for i in range(q)]
inf=float("inf")
dp=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    dp[i][i]=0
for u in abc:
    a,b,c=u
    dp[a][b]=c
    dp[b][a]=c
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])
data=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        if 0<dp[i][j]<=l:
            data[i][j]=1
        elif dp[i][j]==0:
            data[i][j]=0
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            data[i][j]=min(data[i][j],data[i][k]+data[k][j])
for u in st:
    s,t=u
    if data[s][t]!=inf:
        print(data[s][t]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
n,m,l=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]
q=int(input())
st=[list(map(int,input().split())) for i in range(q)]
inf=float("inf")
dp=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    dp[i][i]=0
for u in abc:
    a,b,c=u
    dp[a][b]=c
    dp[b][a]=c
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])
data=[[inf]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        if dp[i][j]<=l:
            data[i][j]=1
for k in range(n+1):
    for i in range(n+1):
        for j in range(n+1):
            data[i][j]=min(data[i][j],data[i][k]+data[k][j])
for u in st:
    s,t=u
    if data[s][t]!=inf:
        print(data[s][t]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

N, M, L = map(int, input().split())
INF = 10**9 + 1
dist = [[0 if i == j else INF for i in range(N+1)] for j in range(N+1)]
for i in range(M):
  a, b, c = map(int, input().split())
  dist[a][b] = c
  dist[b][a] = c

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

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

dist_2 = [[INF for i in range(N+1)] for j in range(N+1)]
for i in range(1, N+1):
  for j in range(i+1, N+1):
    if dist[i][j] <= L:
      dist_2[i][j] = 1
      dist_2[j][i] = 1

for k in range(1, N+1):
  for i in range(1, N+1):
    if dist_2[i][k] == INF:
      continue
    for j in range(1, N+1):
      if dist_2[j][k] == INF:
        continue
      dist_2[i][j] = min(dist_2[i][j], dist_2[i][k] + dist_2[k][j])

for i in range(Q):
  s, t = queries[i]
  print(-1 if dist_2[s][t] == INF else dist_2[s][t]-1)

Submission status: Time Limit Exceeded

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

for i in range(N):
    for j in range(N):
        if 0 < d[i][j] <= L:
            D[i][j] = 1
        elif d[i][j] == 0:
            D[i][j] = 0
D = warshall_floyd(D)

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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix,lil_matrix

N,M,L=map(int, raw_input().split())
RG=lil_matrix((N,N))

for i in range(M):
    f,t,c = map(int, raw_input().split())
    RG[(f-1,t-1)] = c
    RG[(t-1,f-1)] = c

Rd = floyd_warshall(RG.tocsr())

FG=lil_matrix((N,N))
d = csr_matrix(Rd).todok()
for k,v in d.items():
    if v <= L:
        FG[k] = 1

Fd = floyd_warshall(FG.tocsr(), directed=False)

Q=int(raw_input())
Queries = []
for i in range(Q):
    s, t = map(int, raw_input().split())
    v = Fd[s-1][t-1]
    if s == t:
        print (str(0))
    elif v == float('inf'):
        print (str(-1))
    else:
        print (str(int(v-1)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,M,L = map(int, input().split())
INF = float("inf")
dist1 = [[INF]*N for i in range(N)]
dist2 = [[INF]*N for i in range(N)]

for i in range(M):
  A,B,C = map(int, input().split())
  A -= 1
  B -= 1
  dist1[A][B] = C
  dist1[B][A] = C

for i in range(N):
  dist1[i][i] = 0
  dist2[i][i] = 0
  
for k in range(N):
  for i in range(N):
    for j in range(N):
      dist1[i][j] = min(dist1[i][j], dist1[i][k]+dist1[k][j])
for i in range(N):
  for j in range(N):
    if dist1[i][j] > L:
      continue
    if i==j:
      dist2[i][j] = 0
    else:
      dist2[i][j] = 1
for k in range(N):
  for i in range(N):
    for j in range(N):
      dist2[i][j] = min(dist2[i][j], dist2[i][k]+dist2[k][j])
Q = int(input())
for i in range(Q):
  s,t = map(int, input().split())
  print(dist2[s-1][t-1]-1 if dist2[s-1][t-1]<=L else -1)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
from scipy.sparse.csgraph import floyd_warshall
from scipy.sparse import csr_matrix

N,M,L=map(int, raw_input().split())
RG=csr_matrix((N,N))

for i in range(M):
    f,t,c = map(int, raw_input().split())
    RG[(f-1,t-1)] = c
    RG[(t-1,f-1)] = c

Rd = floyd_warshall(RG)

FG=csr_matrix((N,N))
for i in range(N):
    for j in range(N):
        if Rd[i][j] <= L:
            FG[(i,j)] = 1

Fd = floyd_warshall(FG, directed=False)

Q=int(raw_input())
Queries = []
for i in range(Q):
    s, t = map(int, raw_input().split())
    v = Fd[s-1][t-1]
    if s == t:
        print (str(0))
    elif v == float('inf'):
        print (str(-1))
    else:
        print (str(int(v-1)))

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
def floyd_warshall(n, edge):
 
    rn = range(n)
    dist = [ [float('inf')] * n for i in rn]
    
    for i in rn:
        dist[i][i] = 0
            
    for src, dest, distance in edge:
        dist[src-1][dest-1] = distance
    
    for k, i, j in product(rn, repeat=3):
        new_dist = dist[i][k] + dist[k][j]
        if new_dist < dist[i][j]:
            dist[i][j] = new_dist
            
    return dist
 
grafo = []
n,m,l = [int(i) for i in input().split()]
 
for i in range(m):
    a,b,c = [int(i) for i in input().split()]
    if c <= l:
        grafo.append([a,b,c])
        grafo.append([b,a,c])
        
dist = floyd_warshall(n, grafo)

grafo = []

for i in range(n):
    for j in range(n):
        if i != j and dist[i][j] <= l:
            grafo.append([i+1,j+1,1])
            grafo.append([j+1,i+1,1])

dist = floyd_warshall(n, grafo)

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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import bisect

N,M,L=map(int, raw_input().split())
Roads = [] # from, to, cost
for i in range(M):
    Roads.append(map(int, raw_input().split()))
Q=int(raw_input())
Queries = [] # from, to
for i in range(Q):
    Queries.append(map(int, raw_input().split()))

def dijkstra(s, t):

    candidates = [[s,0,0]] # node, charge, used
    candidates_val = [0]

    while candidates:
        cn, cc, cu = candidates.pop(0)
        candidates_val.pop(0)
        if cn == t:
            return cc
        for fi, ti, ci in Roads:
            if fi == cn:
                node = ti
            elif ti == cn:
                node = fi
            else:
                continue

            if ci > L:
                continue
            elif cu + ci > L:
                charge = cc + 1
                used = ci
            else:
                charge = cc
                used = ci + cu

            cost = charge * L + used
            idx = bisect.bisect_left(candidates_val, cost)
            candidates_val.insert(idx, cost)
            candidates.insert(idx, [node, charge, used])
    return -1

for s,t in Queries:
    print dijkstra(s,t)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

N,M,L=map(int, raw_input().split())
Roads = [] # from, to, cost
for i in range(M):
    Roads.append(map(int, raw_input().split()))
Q=int(raw_input())
Queries = [] # from, to
for i in range(Q):
    Queries.append(map(int, raw_input().split()))

def dijkstra(s, t):

    candidates = [[s,0,0]] # node, charge, used
    confirmed = []

    while candidates:
        c = candidates.pop(0)
        confirmed.append(c)
        if c[0] == t:
            return c
        for i in Roads:
            if i[0] == c[0]:
                node = i[1]
            elif i[1] == c[0]:
                node = i[0]
            else:
                continue

            if i[2] > L:
                continue
            elif i[2] + c[2] > L:
                charge = c[1] + 1
                used = i[2]
            else:
                charge = c[1]
                used = c[2] + i[2]

            candidates.append([node, charge, used])
        candidates.sort(key=lambda x: x[1]*L+x[2])
    return None

for s,t in Queries:
    ret = dijkstra(s,t)
    if ret:
        print str(ret[1])
    else:
        print str(-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:
n,m,l = map(int,input().split())
g = [[1<<30]*n for _ in range(n)]
for _ in range(m):
  a,b,c = map(int,input().split())
  g[a-1][b-1] = c
  g[b-1][a-1] = c
for i in range(n):
  g[i][i] = 0

def bell(g,n):
  for k in range(n):
    for i in range(n-1):
      for j in range(i+1,n):
        if g[i][j] > g[i][k] + g[k][j]:
          g[i][j] = g[i][k] + g[k][j]
          g[j][i] = g[i][j]
  return g

g = bell(g,n)
for i in range(n):
  for j in range(n):
    if i == j:
      g[i][j] = 0
    elif g[i][j] <= l:
      g[i][j] = 1
    else:
      g[i][j] = 1<<30
g = bell(g,n)

q = int(input())
for _ in range(q):
  s,t = map(int,input().split())
  if g[s-1][t-1]>>30:
    print(-1)
  else:
    print(g[s-1][t-1]-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)


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 sti in s_t_index:
    if sti[0] != s_0:
        s_0 = sti[0]
        d = Dijkstra(g2, s_0-1)
        ans.append([sti[2], d.dist[sti[1]-1]])
    else:
        ans.append([sti[2], d.dist[sti[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)


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, sti in enumerate(s_t_index):
    if sti[0] != s_0:
        s_0 = sti[0]
        d = Dijkstra(g2, s_0-1)
        ans.append([sti[2], d.dist[sti[1]-1]])
    else:
        ans.append([sti[2], d.dist[sti[1]-1]])

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def dijkstra(links, n, l):
    dists = []

    F9 = (1 << 9) - 1
    F30 = (1 << 30) - 1
    INF = 10 ** 18

    for s in range(n):

        q = [s]
        fixed = [-1] * n
        upper = [INF] * n

        while q:
            item = heappop(q)

            v = item & F9
            if fixed[v] != -1:
                continue

            count = item >> 39
            used = (item >> 9) & F30
            fixed[v] = count

            for u, c in links[v]:
                if l - used < c:
                    new_item = ((count + 1) << 39) | (c << 9) | u
                else:
                    new_item = (count << 39) | ((used + c) << 9) | u
                if new_item >= upper[u]:
                    continue
                upper[u] = new_item
                heappush(q, new_item)

        dists.append(fixed)

    return dists


n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()

links = [set() for _ in range(n)]

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if l < c:
        continue
    links[a].add((b, c))
    links[b].add((a, c))

dists = dijkstra(links, n, l)
buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(dists[s - 1][t - 1])

print('\n'.join(map(str, buf)))

Submission status: Time Limit Exceeded

Solution code:
import sys

import numpy as np

input = sys.stdin.readline


def solve():
    infinity = 10 ** 10
    n, m, le = map(int, input().split())
    paths = np.full((n, n), infinity)
    for i in range(n):
        paths[i,i] = 0

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

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

    refuels = np.array(paths, copy=True)
    for i in range(n):
        for j in range(n):
            refuels[i, j] = 1 if refuels[i, j] <= le else infinity
            if i == j:
                refuels[i, j] = 0

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

    q = int(input())
    answer = []
    for _ in range(q):
        s, t = map(int, input().split())
        answer.append(refuels[s-1, t-1] - 1 if refuels[s-1, t-1] < infinity else -1)

    print("\n".join(map(str, answer)))


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
import math

input = sys.stdin.readline


def solve():
    infinity = 10 ** 10
    n, m, le = map(int, input().split())
    paths = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            if i != j:
                paths[i, j] = infinity

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

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

    refuels = np.array(paths, copy=True)
    for i in range(n):
        for j in range(n):
            refuels[i, j] = 1 if refuels[i, j] <= le else infinity
            if i == j:
                refuels[i, j] = 0

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

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


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int, input().split())
RL=[list(map(int, input().split())) for _ in range(M)]
Q=int(input())
QL=[list(map(int, input().split())) for _ in range(Q)]
inf=float('inf')
fuel=[[inf]*N for _ in range(N)]
dist=[[inf]*N for _ in range(N)]
for i in range(N):
    fuel[i][i]=0
for I in RL:
    fuel[I[0]-1][I[1]-1]=fuel[I[1]-1][I[0]-1]=I[2]
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 i in range(N):
    for j in range(N):
        if fuel[i][j] <= L:
            dist[i][j]=1
for i in range(N):
    dist[i][i]=0
for k in range(N):
    for i in range(N):
        for j in range(N):
            dist[i][j]=min(dist[i][j], dist[i][k]+dist[k][j])
for i in range(Q):
    print(dist[QL[i][0]-1][QL[i][1]-1]-1 if dist[QL[i][0]-1][QL[i][1]-1] != inf else -1)

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int, input().split())
RL=[list(map(int, input().split())) for _ in range(M)]
Q=int(input())
QL=[list(map(int, input().split())) for _ in range(Q)]
inf=float('inf')
fuel=[[inf]*N for _ in range(N)]
dist=[[inf]*N for _ in range(N)]
for i in range(N):
    fuel[i][i]=dist[i][i]=0
for I in RL:
    fuel[I[0]-1][I[1]-1]=fuel[I[1]-1][I[0]-1]=I[2]
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 i in range(N):
    for j in range(N):
        if fuel[i][j] <= L:
            dist[i][j]=min(dist[i][j],1)
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])
for i in range(Q):
    print(dist[QL[i][0]-1][QL[i][1]-1]-1 if dist[QL[i][0]-1][QL[i][1]-1] != inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


class UnionFind:
    def __init__(self, n):
        self.table = [-1] * n

    def _root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self._root(self.table[x])
            return self.table[x]

    def find(self, x, y):
        return self._root(x) == self._root(y)

    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.table[r1] += d2
        else:
            self.table[r1] = r2
            self.table[r2] += d1

    def united_count(self, x):
        return -self.table[self._root(x)]


def dijkstra(links, l, uft):
    dists = []

    F9 = (1 << 9) - 1
    F30 = (1 << 30) - 1
    INF = 10 ** 18

    for s in range(n):

        q = [s]
        fixed = [-1] * n
        upper = [INF] * n
        fixed_count = 0
        limit = uft.united_count(s)

        while q:
            item = heappop(q)

            v = item & F9
            if fixed[v] != -1:
                continue

            count = item >> 39
            used = (item >> 9) & F30
            fixed[v] = count

            fixed_count += 1
            if fixed_count >= limit:
                break

            for u, c in links[v]:
                if l - used < c:
                    new_item = ((count + 1) << 39) | (c << 9) | u
                else:
                    new_item = (count << 39) | ((used + c) << 9) | u
                if new_item >= upper[u]:
                    continue
                upper[u] = new_item
                heappush(q, new_item)

        dists.append(fixed)

    return dists


n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()

links = [set() for _ in range(n)]
uft = UnionFind(n)

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if l < c:
        continue
    links[a].add((b, c))
    links[b].add((a, c))
    uft.union(a, b)

dists = dijkstra(links, l, uft)
buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(dists[s - 1][t - 1])

print('\n'.join(map(str, buf)))

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush


def dijkstra(links, l):
    dists = []

    F9 = (1 << 9) - 1
    F30 = (1 << 30) - 1
    INF = 10 ** 18

    for s in range(n):

        q = [s]
        fixed = [-1] * n
        upper = [INF] * n
        while q:
            item = heappop(q)

            v = item & F9
            if fixed[v] != -1:
                continue

            count = item >> 39
            used = (item >> 9) & F30
            fixed[v] = count

            for u, c in links[v]:
                if l - used < c:
                    new_item = ((count + 1) << 39) | (c << 9) | u
                else:
                    new_item = (count << 39) | ((used + c) << 9) | u
                if new_item >= upper[u]:
                    continue
                heappush(q, new_item)

        dists.append(fixed)

    return dists


n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()

links = [set() for _ in range(n)]

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if l < c:
        continue
    links[a].add((b, c))
    links[b].add((a, c))

dists = dijkstra(links, l)
buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    buf.append(dists[s - 1][t - 1])

print('\n'.join(map(str, buf)))

Submission status: Time Limit Exceeded

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

edges = [tuple(map(int, input().split(" "))) for i in range (M)]
edges = [(x-1, y-1, w) for (x, y, w) in edges if w <= L]

def wf(V, E):
    dist = [[int(1e25)] * len(V) for i in range(len(V))]
    for x, y, w in E:
        dist[x][y] = w
        dist[y][x] = w

    for v in V:
        dist[v][v] = 0

    for k in range(0, len(V)):
        for i in range(0, len(V)):
            for j in range(0, len(V)):
                if dist[i][j] > dist[i][k] + dist[k][j]:
                    dist[i][j] = dist[i][k]+ dist[k][j]

    return dist

dist = wf(range(N), edges)

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

dist1 = wf(range(N), dist_E)

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

    if dist1[s][t] > 1000:
        print(-1)
    else:
        print(dist1[s][t] - 1)

Submission status: Time Limit Exceeded

Solution code:
import copy
def warshall_floyd(dist):
    #d[i][j]: iからjへの最短距離
    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])
    return dist
 
n, m, l = map(int, input().split()) #N:頂点数　M:辺の数 L:容量
dist = [[float("inf") for i in range(n)] for j in range(n)]
dist2 = copy.deepcopy(dist) 
for i in range(n):
    dist[i][i] = 0
 
for i in range(m):
    a, b, c = map(int, input().split())
    dist[a-1][b-1] = c
    dist[b-1][a-1] = c
 
warshall_floyd(dist)
 
 
for i in range(n):
    for j in range(n):
        if dist[i][j] <= l:
            dist2[i][j] = 1
 
warshall_floyd(dist2)
q = int(input())
for i in range(q):
    s, t = map(int, input().split())
    ans = dist2[s-1][t-1]-1
    if dist2[s-1][t-1] == float("inf"):
        ans = -1
    print(ans)