Problem:


Score : 500 points

Problem Statement

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

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

Process the following Q queries:

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

Constraints

All values in input are integers.

2 \leq N \leq 300

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

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

1 \leq C_i \leq 10^9

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

1 \leq s_i, t_i \leq N

s_i \neq t_i

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

Input

Input is given from Standard Input in the following format:

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

Output

Print Q lines.

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

Sample Input 1

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

Sample Output 1

0
1

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

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

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

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



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


Sample output:
0
1

Submission status: Time Limit Exceeded

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

inf = float('INF')
road = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
    road[i][i] = 0
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    road[a][b] = road[b][a] = c

def warshall(d, n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]:
                    d[i][j] = d[i][k] + d[k][j]

warshall(road, n)
# [print(cost) for cost in road]
# print()
costs = [[1 if road[i][j] <= l and i != j else inf for j in range(n)] for i in range(n)]
for i in range(n):
    costs[i][i] = 0
warshall(costs, n)

# [print(cost) for cost in costs]
q = int(input())
for i in range(q):
    s,t = map(int, input().split())
    
    print(costs[s-1][t-1]-1 if costs[s-1][t-1] < inf else -1)

Submission status: Time Limit Exceeded

Solution code:
N,M,L=map(int,input().split())
d=[[10**20 for i in range(0,N+1)] for i in range(0,N+1)]
for i in range(0,M):
    a,b,c=map(int,input().split())
    d[a][b]=c
    d[b][a]=c

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

e=[[10**20 for i in range(0,N+1)] for i in range(0,N+1)]
for i in range(1,N+1):
    for j in range(1,N+1):
        if L>=d[i][j]:
            e[i][j]=1

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

Q=int(input())
ans=[]
for i in range(Q):
    s,t=map(int,input().split())
    if e[s][t]!=10**20:
        ans.append(e[s][t]-1)
    else:
        ans.append(-1)

for i in range(0,Q):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
N,M,L=map(int,input().split())
d=[[10**20 for i in range(0,N+1)] for i in range(0,N+1)]
for i in range(0,M):
    a,b,c=map(int,input().split())
    d[a][b]=c
    d[b][a]=c

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

e=[[10**20 for i in range(0,N+1)] for i in range(0,N+1)]
for i in range(1,N+1):
    for j in range(1,N+1):
        if L>=d[i][j]:
            e[i][j]=1

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

Q=int(input())
ans=[]
for i in range(Q):
    s,t=map(int,input().split())
    if e[s][t]!=10**20:
        ans.append(e[s][t]-1)
    else:
        ans.append(-1)

for i in range(0,Q):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self,s):

        import heapq
        que=[]
        D=[(10**15,L)] * self.V
        D[s]=(0,0)
        heapq.heappush(que,((0,0),s))

        while len(que)!=0:
            cost,v=heapq.heappop(que)
            a,b=cost
            c,d=D[v]

            if a>c:
                continue
            elif a==c and b>d:
                continue

            for i in range(len(self.G[v])):
                e=self.G[v][i]
                a,b=D[e.to]
                nokori=L-cost[1]
                if nokori>=e.cost:
                    c,d=cost[0],cost[1]+e.cost
                else:
                    c,d=cost[0]+1,e.cost
                if a>c or (a==c and b>d):
                    D[e.to]=(c,d)
                    heapq.heappush(que,(D[e.to],e.to))

        return D

N,M,L=map(int,input().split())
city=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    if L>=c:
        city.add(a-1,b-1,c)
        city.add(b-1,a-1,c)

ans=[city.shortest_path(i) for i in range(0,N)]

p=[]

Q=int(input())
for i in range(0,Q):
    s,t=map(int,input().split())
    if ans[s-1][t-1]!=(10**15,L):
        p.append(ans[s-1][t-1][0])
    else:
        p.append(-1)

for i in range(0,Q):
    print(p[i])

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    n,m,l = map(int,input().split())
    E = [[] for i in range(n)]
    for i in range(m):
        a,b,c = map(int,input().split())
        E[a-1].append((b-1,c))
        E[b-1].append((a-1,c))

    from collections import deque

    def bfs(s):
        dist = [[float("INF")]*2 for _ in range(n)]
        
        dist[s] = [0,l]
        q = deque([])
        q.append((0,s,l))
        
        while q:
            count,cur,fuel = q.popleft()
            for nex, nex_len in E[cur]:
                if fuel >= nex_len:
                    nex_fuel = fuel - nex_len
                    if dist[nex][0] > count or (dist[nex][0]==count and nex_fuel > dist[nex][1]):
                        q.append((count,nex,nex_fuel))
                        dist[nex] = [count,nex_fuel]
                else:
                    if l >= nex_len:
                        nex_fuel = l-nex_len
                        nex_count = count+1
                        if dist[nex][0] > nex_count or (dist[nex][0]==nex_count and nex_fuel > dist[nex][1]):
                            q.append((nex_count,nex,nex_fuel))
                            dist[nex] = [nex_count,nex_fuel]

        return dist


    ans = []
    for i in range(n):
        ans.append(bfs(i))
    
    x = int(input())
    for i in range(x):
        s,g = map(int,input().split())
        if ans[s-1][g-1][0] == float("INF"):
            print(-1)
        else:
            print(ans[s-1][g-1][0]) 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    n,m,l = map(int,input().split())
    E = [[] for i in range(n)]
    for i in range(m):
        a,b,c = map(int,input().split())
        E[a-1].append((b-1,c))
        E[b-1].append((a-1,c))

    import heapq

    def dijkstra(s):
        dist = [[float("INF")]*2 for _ in range(n)]
        
        dist[s] = [0,l]
        q = []
        heapq.heappush(q, (0,s,l))
        
        while q:
            count,cur,fuel = heapq.heappop(q)
            for nex, nex_len in E[cur]:
                if fuel >= nex_len:
                    nex_fuel = fuel - nex_len
                    if dist[nex][0] > count or (dist[nex][0]==count and nex_fuel > dist[nex][1]):
                        heapq.heappush(q, (count,nex,nex_fuel))
                        dist[nex] = [count,nex_fuel]
                else:
                    if l >= nex_len:
                        nex_fuel = l-nex_len
                        nex_count = count+1
                        if dist[nex][0] > nex_count or (dist[nex][0]==nex_count and nex_fuel > dist[nex][1]):
                            heapq.heappush(q, (nex_count,nex,nex_fuel))
                            dist[nex] = [nex_count,nex_fuel]

        return dist


    ans = []
    for i in range(n):
        ans.append(dijkstra(i))
    
    x = int(input())
    for i in range(x):
        s,g = map(int,input().split())
        if ans[s-1][g-1][0] == float("INF"):
            print(-1)
        else:
            print(ans[s-1][g-1][0]) 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    
    n,m,l = map(int,input().split())
    E = [[] for i in range(n)]
    for i in range(m):
        a,b,c = map(int,input().split())
        E[a-1].append((b-1,c))
        E[b-1].append((a-1,c))

    import heapq

    def dijkstra(graph, node, start):
        dist = [[float("INF")]*2 for _ in range(node)]
        
        dist[start] = [0,l]
        q = []
        heapq.heappush(q, (0,start,l))
        
        while q:
            count,cur,fuel = heapq.heappop(q)
            for nex, nex_len in graph[cur]:
                if fuel >= nex_len:
                    nex_fuel = fuel - nex_len
                    if dist[nex][0] > count or (dist[nex][0]==count and nex_fuel > dist[nex][1]):
                        heapq.heappush(q, (count,nex,nex_fuel))
                        dist[nex] = [count,nex_fuel]
                else:
                    if l >= nex_len:
                        nex_fuel = l-nex_len
                        nex_count = count+1
                        if dist[nex][0] > nex_count or (dist[nex][0]==nex_count and nex_fuel > dist[nex][1]):
                            heapq.heappush(q, (nex_count,nex,nex_fuel))
                            dist[nex] = [nex_count,nex_fuel]

        return dist


    ans = []
    for i in range(n):
        ans.append(dijkstra(E, n, i))
    
    x = int(input())
    for i in range(x):
        s,g = map(int,input().split())
        if ans[s-1][g-1][0] == float("INF"):
            print(-1)
        else:
            print(ans[s-1][g-1][0]) 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n,m,l=map(int,input().split())
edge=[[]for _ in range(n)]
for _ in range(m):
  a,b,c=map(int,input().split())
  if c>l:continue
  a-=1;b-=1
  edge[a].append([b,c])
  edge[b].append([a,c])
from heapq import heappop,heappush
inf=10**10
cost=[[[inf,inf]for _ in range(n)]for _ in range(n)]
for i in range(n):
  cost[i][i]=[0,0]
  h=[[0,i]]
  while h:
    c,v=heappop(h)
    c,co=c//(10**9+7),c%(10**9+7)
    if cost[i][v][0]<c or (cost[i][v][0]==c and cost[i][v][1]<co):continue
    for u,t in edge[v]:
      if co+t>l:
        c2=c+1
        co2=t
      else:
        c2=c
        co2=co+t
      if cost[i][u][0]>c2 or (cost[i][u][0]==c2 and cost[i][u][1]>co2):
        cost[i][u]=[c2,co2]
        heappush(h,[c2*(10**9+7)+co2,u])
ans=[[j[0]for j in i]for i in cost]
q=int(input())
ab=[list(map(int,input().split()))for _ in range(q)]
for a,b in ab:
  if ans[a-1][b-1]==10**10:print(-1)
  else:print(ans[a-1][b-1])

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(edge):
  e=edge
  for k in range(len(e)):
    for i in range(len(e)):
      for j in range(len(e)):e[i][j]=min(e[i][j],e[i][k]+e[k][j])
  return e
n,m,l=map(int,input().split())
edge=[n*[10**10]for _ in range(n)]
for i in range(n):edge[i][i]=0
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1;b-=1
  edge[a][b]=edge[b][a]=c
edge=warshall_floyd(edge)
edgee=[n*[10**10]for _ in range(n)]
for i in range(n):
  edgee[i][i]=0
  for j in range(n):
    if edge[i][j]<=l:edgee[i][j]=1
edgee=warshall_floyd(edgee)
q=int(input())
for _ in range(q):
  s,t=map(int,input().split())
  s-=1;t-=1
  ans=edgee[s][t]
  if ans==10**10:print(-1)
  else:print(ans-1)

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
Map = [[int(1e18) for _ in range(N)] for __ in range(N)]
Graph = [[int(1e18) for _ in range(N)] for _ in range(N)]

for i in range(M):
  A, B, C = map(int, input().split())
  if C <= L:
    Map[A-1][B-1] = C
    Map[B-1][A-1] = C
  
for k in range(N):
  for i in range(N):
    for j in range(N):
      if Map[i][j] > Map[i][k] + Map[k][j]:
        Map[i][j] = Map[i][k] + Map[k][j]

for i in range(N):
  for j in range(N):
    if i == j:
      Map[i][i] = 0
      Graph[i][i] = 0
    elif Map[i][j] <= L:
      Graph[i][j] = 1
for k in range(N):
  for i in range(N):
    for j in range(N):
      if Graph[i][j] > Graph[i][k] + Graph[k][j]:
        Graph[i][j] = Graph[i][k] + Graph[k][j]

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

Submission status: Time Limit Exceeded

Solution code:
import heapq
n,m,l = map(int,input().split())
road = [[] for i in range(n+1)]
for i in range(m):
    a,b,c = list(map(int,input().split()))
    road[a].append([b,c])
    road[b].append([a,c])
q = int(input())
al = []
for i in range(q):
    s,t = map(int,input().split())
    rl = [[1000,-1] for x in range(n+1)]
    al0 = []
    d = [[0,s,l]]
    heapq.heapify(d)
    rl[s] = [0,l]
    key = 1000
    while len(d):
        h,now,g = heapq.heappop(d)
        #print(h,now,g,key)
        if h >= key:
            break
        if g >= 0:
            for j in road[now]:
                if j[0] == t:
                    if j[1] <= g:
                        al0.append(h)
                        key = h
                    else:
                        if j[1] <= l:
                            al0.append(h+1)
                            key = h+1
                else:
                    h0 = h
                    g0 = g
                    if j[1] <= g0:
                        g0 -= j[1]
                    else:
                        if j[1] <= l:
                            h0 += 1
                            g0 = l-j[1]
                        else:
                            h0 += 10000
                            g0 = -1
                    if rl[j[0]][0] > h0:
                        rl[j[0]][0] = h0
                        rl[j[0]][1] = g0
                        heapq.heappush(d,[h0,j[0],g0])
                    elif rl[j[0]][0] == h0:
                        if rl[j[0]][1] < g0:
                            rl[j[0]][1] = g0
                            heapq.heappush(d,[h0,j[0],g0])
    if len(al0) == 0:
        al.append(-1)
    else:
        al.append(min(al0))
for i in al:
    print(i)

Submission status: Time Limit Exceeded

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

def main():
    n, m, l = map(int, input().split())
    dist = [[float('inf')]*n for _ in range(n)]
    
    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
      
    for _ in range(m):
        a, b, c = map(int, input().split())
        if c > l:
            continue
        a -= 1
        b -= 1
        dist[a][b] = c
        dist[b][a] = c

    Warshall_Floyd(dist)

    dist2 = [[float('inf')]*n for _ in range(n)]
    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 _ in range(q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if dist2[s][t] == float('inf'):
            print(-1)
            continue
        ans = dist2[s][t]
        print(ans-1)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    n, m, l = map(int, input().split())
    dist = [[float('inf')]*n for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        dist[a][b] = c
        dist[b][a] = c

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

    dist2 = [[float('inf')]*n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if dist[i][j] <= l:
                dist2[i][j] = 1
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist2[i][j] = min(dist2[i][j], dist2[i][k] + dist2[k][j])


    q = int(input())
    for _ in range(q):
        s, t = map(int, input().split())
        s -= 1
        t -= 1
        if dist2[s][t] == float('inf'):
            print(-1)
            continue
        ans = dist2[s][t]
        print(ans-1)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    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()) #n:頂点数　w:辺の数

d = [[float("inf")]*n for i in range(n)]
dd = [[float("inf")]*n for i in range(n)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
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 #自身のところに行くコストは０
for i in range(n):
     for j in range(n):
          if warshall_floyd(d)[i][j] <= l:
               dd[i][j] = 1
q = int(input())
for i in range(q):
     s,t = map(int,input().split())
     if warshall_floyd(dd)[s-1][t-1] >400:
          print(-1)
     else:
          print(warshall_floyd(dd)[s-1][t-1]-1)

Submission status: Time Limit Exceeded

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

import sys
from collections import deque
from array import array

def input():
    return sys.stdin.readline().rstrip('\n')

# diagonal square matrix for pypy

class DiagonalMatrix:
    def __init__(self, size):
        self._size = size
        array_size = (size+1)*size//2
        # 三角行列の要素を1次元配列に並べる
        self._storage = array('l', [0]*array_size)

    def _index(self, i, j):
        _n = self._size
        _i = i+1
        _j = j+1
        return (_n+1)*_n//2 - (_n-_i+2)*(_n-_i+1)//2 + (_j-_i+1) - 1
    
    def get(self,i,j):
        if i <= j:
            return self._storage[self._index(i,j)]
        else:
            return self._storage[self._index(j,i)]

    def set(self, i, j, value):
        if i <= j:
            self._storage[self._index(i,j)] = value
        else:
            self._storage[self._index(j,i)] = value
        
'''
N = 5
matrix = DiagonalMatrix(N)
for i in range(N):
    for j in range(i,N):
        matrix.set(i,j,matrix._index(i,j))
        print(i,j,matrix._index(i,j),matrix._storage)

for i in range(N):
    print([matrix.get(i,j) for j in range(N)])
'''
    
##### main

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

C = DiagonalMatrix(N)

for i in range(M):
    a,b,c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if c>L:
        continue
    C.set(a,b,c)

Q = int(input())

#S = array('q', [0]*Q)
#T = array('q', [0]*Q)
#S = [0]*Q
#T = [0]*Q
#ST = {}
ST = [None]*Q

for i in range(Q):
    s, t = list(map(int, input().split()))
    ST[i] = (s-1,t-1)

# ワーシャルフロイド法

# distance from i to j
#D = [array('q', [0]*N) for i in range(N)]
D = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(i+1,N):
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(i+1,N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))

'''
fo i in range(N):
    print([D.get(i,j) for j in range(N)])
'''


#sys.exit()

# D[i][j] <= L となる i,j に辺を張る
for i in range(N):
    for j in range(i+1,N):
        if D.get(i,j) <= L:
            C.set(i,j,1)

# ワーシャルフロイド法 again

# distance from i to j
D = DiagonalMatrix(N)
STEP = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(i+1,N):
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
            STEP.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)
            STEP.set(i,j,1)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(i+1,N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))
                STEP.set(i,j, STEP.get(i,k) + STEP.get(k,j))

# answer
for q in range(Q):
    i,j = ST[q]
    step = STEP.get(i,j)
    if step == sys.maxsize:
        print(-1)
    else:
        print(step-1)

Submission status: Time Limit Exceeded

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

import sys
from collections import deque
from array import array

def input():
    return sys.stdin.readline().rstrip('\n')

# diagonal square matrix for pypy

class DiagonalMatrix:
    def __init__(self, size):
        self._size = size
        array_size = (size+1)*size//2
        # 三角行列の要素を1次元配列に並べる
        self._storage = array('l', [0]*array_size)

    def _index(self, i, j):
        _n = self._size
        _i = i+1
        _j = j+1
        return (_n+1)*_n//2 - (_n-_i+2)*(_n-_i+1)//2 + (_j-_i+1) - 1
    
    def get(self,i,j):
        if i <= j:
            return self._storage[self._index(i,j)]
        else:
            return self._storage[self._index(j,i)]

    def set(self, i, j, value):
        if i <= j:
            self._storage[self._index(i,j)] = value
        else:
            self._storage[self._index(j,i)] = value
        
'''
N = 5
matrix = DiagonalMatrix(N)
for i in range(N):
    for j in range(i,N):
        matrix.set(i,j,matrix._index(i,j))
        print(i,j,matrix._index(i,j),matrix._storage)

for i in range(N):
    print([matrix.get(i,j) for j in range(N)])
'''
    
##### main

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

C = DiagonalMatrix(N)

for i in range(M):
    a,b,c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if c>L:
        continue
    C.set(a,b,c)

Q = int(input())

#S = array('q', [0]*Q)
#T = array('q', [0]*Q)
#S = [0]*Q
#T = [0]*Q
#ST = {}
ST = [None]*Q

for i in range(Q):
    s, t = list(map(int, input().split()))
    ST[i] = (s-1,t-1)

# ワーシャルフロイド法

# distance from i to j
#D = [array('q', [0]*N) for i in range(N)]
D = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(i,N):
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(i,N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))

'''
fo i in range(N):
    print([D.get(i,j) for j in range(N)])
'''
    
# D[i][j] <= L となる i,j に辺を張る
for i in range(N):
    for j in range(i,N):
        if D.get(i,j) <= L:
            C.set(i,j,1)

# ワーシャルフロイド法 again

# distance from i to j
D = DiagonalMatrix(N)
STEP = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(i,N):
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
            STEP.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)
            STEP.set(i,j,1)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(i,N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))
                STEP.set(i,j, STEP.get(i,k) + STEP.get(k,j))

# answer
for q in range(Q):
    i,j = ST[q]
    step = STEP.get(i,j)
    if step == sys.maxsize:
        print(-1)
    else:
        print(step-1)

Submission status: Time Limit Exceeded

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

import sys
from collections import deque
from array import array

def input():
    return sys.stdin.readline().rstrip('\n')

# diagonal square matrix for pypy
class DiagonalMatrix:
    def __init__(self, size):
        self._size = size
        array_size = (size+1)*size//2
        self._storage = array('l', [0]*array_size)

    def _index(self, i, j):
        _n = self._size
        _i = i+1
        _j = j+1
        return (_n+1)*_n//2 - (_n-_i+2)*(_n-_i+1)//2 + (_j-_i+1) - 1
    
    def get(self,i,j):
        if i <= j:
            return self._storage[self._index(i,j)]
        else:
            return self._storage[self._index(j,i)]

    def set(self, i, j, value):
        if i <= j:
            self._storage[self._index(i,j)] = value
        else:
            self._storage[self._index(j,i)] = value
        
'''
N = 5
matrix = DiagonalMatrix(N)
for i in range(N):
    for j in range(i,N):
        matrix.set(i,j,matrix._index(i,j))
        print(i,j,matrix._index(i,j),matrix._storage)

for i in range(N):
    print([matrix.get(i,j) for j in range(N)])
'''
    
##### main

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

C = DiagonalMatrix(N)

for i in range(M):
    a,b,c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if c>L:
        continue
    C.set(a,b,c)

Q = int(input())

#S = array('q', [0]*Q)
#T = array('q', [0]*Q)
#S = [0]*Q
#T = [0]*Q
#ST = {}
ST = [None]*Q

for i in range(Q):
    s, t = list(map(int, input().split()))
    ST[i] = (s-1,t-1)

# ワーシャルフロイド法

# distance from i to j
#D = [array('q', [0]*N) for i in range(N)]
D = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(N):
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))

'''
fo i in range(N):
    print([D.get(i,j) for j in range(N)])
'''
    
# D[i][j] <= L となる i,j に辺を張る
for i in range(N):
    for j in range(N):
        if D.get(i,j) <= L:
            C.set(i,j,1)

# ワーシャルフロイド法 again

# distance from i to j
D = DiagonalMatrix(N)
STEP = DiagonalMatrix(N)

# initialization
for i in range(N):
    for j in range(i,N):
        c = C.get(i,j)
        c = C.get(i,j)
        if c == 0:
            D.set(i,j,sys.maxsize)
            STEP.set(i,j,sys.maxsize)
        else:
            D.set(i,j,c)
            STEP.set(i,j,1)

# 本計算
for k in range(N):
    for i in range(N):
        for j in range(N):
            if D.get(i,j) > D.get(i,k) + D.get(k,j):
                D.set(i,j, D.get(i,k) + D.get(k,j))
                STEP.set(i,j, STEP.get(i,k) + STEP.get(k,j))

# answer
for q in range(Q):
    i,j = ST[q]
    step = STEP.get(i,j)
    if step == sys.maxsize:
        print(-1)
    else:
        print(step-1)

Submission status: Time Limit Exceeded

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

import sys
from collections import deque
from array import array

def input():
    return sys.stdin.readline().rstrip('\n')

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

_C = {}

for i in range(M):
    a,b,c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if c>L:
        continue
    _C[a*300+b] = c
    _C[b*300+a] = c

def C_(i,j):
    return _C.get(i*300+j, sys.maxsize)

Q = int(input())

#S = array('q', [0]*Q)
#T = array('q', [0]*Q)
#S = [0]*Q
#T = [0]*Q
ST = {}

for i in range(Q):
    s, t = list(map(int, input().split()))
    ST[i] = (s-1,t-1)

# ワーシャルフロイド法

# distance from i to j
#D = [array('q', [0]*N) for i in range(N)]
D = [[0]*N for i in range(N)]

# initialization
for i in range(N):
    for j in range(N):
        D[i][j] = C_(i,j)
        #print(i,j,D[i][j])

# 本計算
for k in range(N):
    Dk = D[k]
    for i in range(N):
        Di = D[i]
        for j in range(N):
            #if D[i][j] > D[i][k] + D[k][j]:
                #D[i][j] = D[i][k] + D[k][j]
            if Di[j] > Di[k] + Dk[j]:
                Di[j] = Di[k] + Dk[j]


# D[i][j] <= L となる i,j に辺を張る
for i in range(N):
    for j in range(N):
        if D[i][j] <= L:
            _C[i*300+j] = 1
            _C[j*300+i] = 1

# ワーシャルフロイド法 again

# distance from i to j
#D = [array('q', [0]*N) for i in range(N)]
D = [[0]*N for i in range(N)]
#STEP = [array('q', [0]*N) for i in range(N)]
STEP = [[0]*N for i in range(N)]

# initialization
for i in range(N):
    for j in range(N):
        c = C_(i,j)
        D[i][j] = c
        if c == sys.maxsize:
            STEP[i][j] = sys.maxsize
        else:
            STEP[i][j] = 1
        #print(i,j,D[i][j],STEP[i][j])

# 本計算
for k in range(N):
    Dk = D[k]
    STEPk = STEP[k]
    for i in range(N):
        Di = D[i]
        STEPi = STEP[i]
        for j in range(N):
            if Di[j] > Di[k] + Dk[j]:
                Di[j] = Di[k] + Dk[j]
                STEPi[j] = STEPi[k] + STEPk[j]


# answer
for q in range(Q):
    i,j = ST[q]
    step = STEP[i][j]
    if step == sys.maxsize:
        #print(i,j,-1)
        print(-1)
    else:
        print(step-1)