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())
#基本的にワーシャルフロイドの場合、行列式のリストで距離を保管する
d = [[10**20 for i in range(n+1)] for i in range(n+1)]
for i in range(m):
    x,y,z = map(int,input().split())
    #有向グラフか無向グラフかによってここで場合わけが生じる
    d[x][y] = z
    d[y][x] = z    
for i in range(n+1):
    d[i][i] = 0 #自身のところに行くコストは０
q=int(input())
que=[]
for _ in range(q):
    s,t=map(int,input().split())
    que.append((s,t))
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(n+1)] for i in range(n+1)]

for i in range(1,n+1):
    for j in range(1,n+1):
        if d[i][j]<=l:
            e[i][j]=1
            
for i in range(n+1):
    e[i][i]=0  
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][j],e[i][k] + e[k][j])
for some in que:
    s,t=some[0],some[1]
    if e[s][t]<10**20:
        print(e[s][t]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

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

#基本的にワーシャルフロイドの場合、行列式のリストで距離を保管する

d = [[10**20 for i in range(n+1)] for i in range(n+1)]

for i in range(m):
    x,y,z = map(int,input().split())
    #有向グラフか無向グラフかによってここで場合わけが生じる
    d[x][y] = z
    d[y][x] = z
    
for i in range(n+1):
    d[i][i] = 0 #自身のところに行くコストは０

def warshall_floyd(d):
    #d[i][j]=i番目の頂点からj番目の頂点までの最短距離
    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])
    return d

d=warshall_floyd(d)

e = [[10**20 for i in range(n+1)] for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        if d[i][j]<=l:
            e[i][j]=1
for i in range(n+1):
    e[i][i]=0
    
f=warshall_floyd(e)

q=int(input())

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

Submission status: Time Limit Exceeded

Solution code:
import sys

def wf(d):
  for i in range(n):
    for j in range(n):#start
      for k in range(n):#end
        d[j][k]=min(d[j][k], d[j][i] + d[i][k])
  return d

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

d=[[sys.maxsize]*(n) for _ in range(n)]
e=[[sys.maxsize]*(n) for _ in range(n)]
for i in range(n):
  d[i][i] = 0
  e[i][i] = 0

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

d=wf(d)
for i in range(n):
  for j in range(n):
    if d[i][j] <= l:
      e[i][j] = 1

e=wf(e)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

def wf(d):
  for i in range(n):
    for j in range(n):#start
      for k in range(n):#end
        d[j][k]=min(d[j][k], d[j][i] + d[i][k])
  return d

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

d=[[sys.maxsize]*(n) for _ in range(n)]
e=[[sys.maxsize]*(n) for _ in range(n)]
for i in range(n):
  d[i][i] = 0
  e[i][i] = 0

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

d=wf(d)
for i in range(n):
  for j in range(n):
    if d[i][j] <= l:
      e[i][j] = 1

e=wf(e)

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

Submission status: Time Limit Exceeded

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

d=[[sys.maxsize]*(n+1) for _ in range(n+1)]
e=[[sys.maxsize]*(n+1) for _ in range(n+1)]
for i in range(n+1):
  d[0][i] = 0
  d[i][0] = 0
  d[i][i] = 0
  e[0][i] = 0
  e[i][0] = 0
  e[i][i] = 0

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

for i in range(1,n+1):
  for j in range(1,n+1):#start
    for k in range(1,n+1):#end
      d[j][k]=min(d[j][k], d[j][i] + d[i][k])

for i in range(1,n+1):
  for j in range(1,n+1):
    if d[i][j] <= l:
      e[i][j] = 1

for i in range(1,n+1):
  for j in range(1,n+1):#start
    for k in range(1,n+1):#end
      e[j][k]=min(e[j][k], e[j][i] + e[i][k])

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

Submission status: Time Limit Exceeded

Solution code:
MOD = 10 **9 + 7
INF = 10 ** 10

def main():
    n,m,l = map(int,input().split())
    dist = [[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])

    cnt = [[INF] * n for _ in range(n)]   
    for i in range(n):
        for j in range(n):
            if dist[i][j] <= l:
                cnt[i][j] = 1

    for k in range(n):
        for i in range(n):
            for j in range(n):
                cnt[i][j] = min(cnt[i][j],cnt[i][k] + cnt[k][j])
    
    q = int(input())
    for _ in range(q):
        s,t = map(int,input().split())
        s -= 1
        t -= 1
        print(cnt[s][t] - 1 if cnt[s][t] != INF  else -1)       
if __name__ == '__main__':
    main()

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

import sys

input=sys.stdin.readline

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

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

Submission status: Time Limit Exceeded

Solution code:
import queue


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

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

d = []

for s in range(n):
    tank = [[1000,0] for i in range(n)]
    tank[s]=[0,l]
    q = queue.Queue()
    q.put(s)
    while not q.empty():
        p = q.get()
        for b,c in road[p]:
            if tank[p][1]>=c:
                t = [tank[p][0],tank[p][1]-c]
            elif l>=c:
                t = [tank[p][0]+1,l-c]
            else:
                continue

            if tank[b][0] > t[0]:
                tank[b] = t
                q.put(b)
            elif tank[b][0] == t[0]:
                if tank[b][1] < t[1]:
                    tank[b] = t
                    q.put(b)
    d.append([tank[i][0] for i in range(n)])

q = int(input())
for i in range(q):
    s,t = map(int, input().split())
    s-=1
    t-=1
    print([d[s][t],-1][d[s][t]==1000])

Submission status: Time Limit Exceeded

Solution code:
class WarshallFloyd:
    def __init__(self,n):
        self.v = n
        self.d = []
        for i in range(n):
            self.d.append([1e100]*n)
            self.d[i][i] = 0

    def path(self,x,y,c):
        if x == y:
            return False
        self.d[x][y] = c
        self.d[y][x] = c
        return True

    def build(self):
        for k in range(self.v):
            for i in range(self.v):
                for j in range(self.v):
                    self.d[i][j] = min(self.d[i][j], self.d[i][k] + self.d[k][j])
        return self.d

n,m,l = map(int,input().split())
wf = WarshallFloyd(n)
for i in range(m):
    a,b,c = map(int,input().split())
    wf.path(a-1,b-1,c)
d = wf.build()
wf = WarshallFloyd(n)

for i in range(1,n):
    for j in range(i):
        if d[i][j] <= l:
            wf.path(i,j,1)

ans = wf.build()

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

Submission status: Time Limit Exceeded

Solution code:
class WarshallFloyd:
    def __init__(self,n):
        self.v = n
        self.d = []
        for i in range(n):
            self.d.append([1e100]*n)
            self.d[i][i] = 0

    def path(self,x,y,c):
        if x == y:
            return False
        self.d[x][y] = c
        self.d[y][x] = c
        return True

    def build(self):
        for k in range(self.v):
            for i in range(self.v):
                for j in range(self.v):
                    self.d[i][j] = min(self.d[i][j], self.d[i][k] + self.d[k][j])

n,m,l = map(int,input().split())
wf = WarshallFloyd(n)
for i in range(m):
    a,b,c = map(int,input().split())
    wf.path(a-1,b-1,c)
wf.build()
d = []
for i in range(n):
    d.append([1e100]*n)
    for j in range(n):
        if i == j:
            d[i][j] = 0
        elif wf.d[i][j] <= l:
            d[i][j] = 1

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

q = int(input())
for i in range(q):
    s,t = map(int,input().split())
    ans = d[s-1][t-1]
    if ans == 1e100:
        print(-1)
    else:
        print(ans - 1)

Submission status: Time Limit Exceeded

Solution code:
class WarshallFloyd:
    def __init__(self,n):
        self.v = n
        self.d = [[1e100]*n for _ in range(n)]
        for i in range(n):
            self.d[i][i] = 0

    def path(self,x,y,c):
        if x == y:
            return False
        self.d[x][y] = c
        self.d[y][x] = c
        return True

    def build(self):
        for k in range(self.v):
            for i in range(self.v):
                for j in range(self.v):
                    self.d[i][j] = min(self.d[i][j], self.d[i][k] + self.d[k][j])

n,m,l = map(int,input().split())
wf = WarshallFloyd(n)
for i in range(m):
    a,b,c = map(int,input().split())
    wf.path(a-1,b-1,c)
wf.build()
d = [[1e100]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if i == j:
            d[i][j] = 0
        elif wf.d[i][j] <= l:
            d[i][j] = 1

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

q = int(input())
for i in range(q):
    s,t = map(int,input().split())
    ans = d[s-1][t-1]
    if ans == 1e100:
        print(-1)
    else:
        print(ans - 1)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(G):
    inf = 10**18
    # 重みつきグラフGに対してすべての頂点対の距離を求める
    n = len(G)
    d = [[inf for i in range(n)] for j in range(n)]
    for i in range(n):
        d[i][i] = 0
        for j in G[i].keys():
            d[i][j] = G[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())
G = [{} for i in range(n)]
for j in range(m):
    a, b, c = map(int, input().split())
    G[a-1][b-1] = c
    G[b-1][a-1] = c
D = warshall_floyd(G)
G = [{} for i in range(n)]
for i in range(n):
    for j in range(n):
        if D[i][j] <= l:
            G[i][j] = 1
D = warshall_floyd(G)
for k in range(int(input())):
    s, t = map(int, input().split())
    if D[s-1][t-1] > 10**10:
        print(-1)
    else:
        print(D[s-1][t-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
"""def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
sys.setrecursionlimit(10**7)"""
input=lambda :sys.stdin.readline().rstrip()



N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    if C<=L:
        data[A].append([B,C])
        data[B].append([A,C])



d=[[[301,0]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if l+c>L:
                        if d[i][p]>[m+1,c]:
                            d[i][p]=[m+1,c]
                            if p>i:
                                d[p][i]=[m+1,L]
                            heappush(stack,[m+1,c,p])
                    else:
                        if d[i][p]>[m,l+c]:
                            d[i][p]=[m,l+c]
                            if p>i:
                                d[p][i]=[m,L]
                            heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
"""def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
sys.setrecursionlimit(10**7)"""
input=lambda :sys.stdin.readline().rstrip()



N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    data[A].append([B,C])
    data[B].append([A,C])



d=[[[301,0]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                if p>i:
                                    d[p][i]=[m+1,L]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                if p>i:
                                    d[p][i]=[m,L]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
"""def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
sys.setrecursionlimit(10**7)"""
input=lambda :sys.stdin.readline().rstrip()



N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[{} for i in range(N+1)]
se=[set() for i in range(N+1)]
for A,B,C in ABC:
    data[A][B]=C
    data[B][A]=C
    se[A].add(B)
    se[B].add(A)

d=[[[301,0]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            if len(visited)==N:
                break
            for p in se[a]-visited:
                    c=data[a][p]
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                if p>i:
                                    d[p][i]=[m+1,L]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                if p>i:
                                    d[p][i]=[m,L]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
"""def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
sys.setrecursionlimit(10**7)"""
input=lambda :sys.stdin.readline().rstrip()



N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[{} for i in range(N+1)]
se=[set() for i in range(N+1)]
for A,B,C in ABC:
    data[A][B]=C
    data[B][A]=C
    se[A].add(B)
    se[B].add(A)

d=[[[301,0]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            if len(visited)==N:
                break
            for p in se[a]-visited:
                    c=data[a][p]
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                if p>i:
                                    d[p][i]=[m+1,L]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                if p>i:
                                    d[p][i]=[m+1,L]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:

from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
"""def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
sys.setrecursionlimit(10**7)"""
input=lambda :sys.stdin.readline().rstrip()



N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[{} for i in range(N+1)]
se=[set() for i in range(N+1)]
for A,B,C in ABC:
    data[A][B]=C
    data[B][A]=C
    se[A].add(B)
    se[B].add(A)

d=[[[301,0]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            #d[i][a]=[m,l]
            if len(visited)==N:
                break
            for p in se[a]-visited:
                    c=data[a][p]
                #if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:

from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""

input=lambda :sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))

N,M,L=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
ST=[list(map(int,input().split())) for i in range(int(input()))]

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    data[A].append([B,C])
    data[B].append([A,C])

d=[[[301,L]]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            #d[i][a]=[m,l]
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:

from heapq import *
import sys
"""
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import time

import math
"""
input=lambda :sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))

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

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    data[A].append([B,C])
    data[B].append([A,C])

d=[[[301,L+1] for n in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            #d[i][a]=[m,l]
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from heapq import *
from itertools import *
#from fractions import gcd

from decimal import *
import copy
from bisect import *
import time
import sys
import math

input=lambda :sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))

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

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    data[A].append([B,C])
    data[B].append([A,C])

d=[[[301,L+1] for n in range(N+1)] for i in range(N+1)]
for i in [s for s,t in ST]:
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            d[i][a]=[m,l]
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from heapq import *
from itertools import *
#from fractions import gcd

from decimal import *
import copy
from bisect import *
import time
import sys
import math

input=lambda :sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))

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

data=[[] for i in range(N+1)]
for A,B,C in ABC:
    data[A].append([B,C])
    data[B].append([A,C])

d=[[[301,L+1] for n in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
    visited=set()
    stack=[[0,0,i]]
    while stack:
        m,l,a=heappop(stack)
        if not a in visited:
            visited.add(a)
            d[i][a]=[m,l]
            if len(visited)==N:
                break
            for p,c in data[a]:
                if not p in visited:
                    if c<=L:
                        if l+c>L:
                            if d[i][p]>[m+1,c]:
                                d[i][p]=[m+1,c]
                                heappush(stack,[m+1,c,p])
                        else:
                            if d[i][p]>[m,l+c]:
                                d[i][p]=[m,l+c]
                                heappush(stack,[m,l+c,p])
for s,t in ST:
    if d[s][t][0]!=301:
        print(d[s][t][0])
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
def W(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,w,l= map(int,input().split()) #n:頂点数　w:辺の数

d = [[10**14]*n for i in range(n)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(w):
    x,y,z = map(int,input().split())
    if z>l:
      continue
    x=x-1
    y=y-1
    d[x][y] = z
    d[y][x] = z
for i in range(n):
    d[i][i] = 0 #自身のところに行くコストは０
D=W(d)
G=[[10**4]*n for i in range(n)]
for i in range(n):
  for j in range(n):
    if D[i][j]>l:
      continue
    G[i][j]=1
WW=W(G)
for i in range(int(input())):
  a,b=map(int,input().split())
  a=a-1
  b=b-1
  if WW[a][b]>=10**4:
    print(-1)
  else:
    print(WW[a][b]-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

class WarshallFloyd():
    def __init__(self, N):
        self.N = N
        self.d = [[float("inf") for i in range(N)]
                  for i in range(N)]  # d[u][v] : 辺uvのコスト(存在しないときは'inf')

    def add(self, u, v, c, directed=False):
        """
        0-indexedであることに注意
        u = from, v = to, c = cost
        directed = Trueなら、有向グラフである
        """
        if directed is False:
            self.d[u][v] = c
            self.d[v][u] = c
        else:
            self.d[u][v] = c

    def WarshallFloyd_search(self):
        # これを d[i][j]: iからjへの最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行ける
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    self.d[i][j] = min(
                        self.d[i][j], self.d[i][k] + self.d[k][j])
        for i in range(self.N):
            self.d[i][i] = 0
        return self.d

n,m,l = na()
g = WarshallFloyd(n)

for i in range(m):
    a,b,c = na()
    g.add(a-1,b-1,c)

gg = WarshallFloyd(n)
d = g.WarshallFloyd_search()

for i in range(n):
    for j in range(n):
        if d[i][j] <= l:
            gg.add(i,j,1)

q = ni()
dd = gg.WarshallFloyd_search()

for i in range(q):
    s,t = na()
    print(-1 if dd[s-1][t-1] == float('inf') else dd[s-1][t-1]-1)