Problem:


Score : 500 points

Problem Statement

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

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

Process the following Q queries:

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

Constraints

All values in input are integers.

2 \leq N \leq 300

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

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

1 \leq C_i \leq 10^9

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

1 \leq s_i, t_i \leq N

s_i \neq t_i

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

Input

Input is given from Standard Input in the following format:

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

Output

Print Q lines.

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

Sample Input 1

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

Sample Output 1

0
1

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

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

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

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



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


Sample output:
0
1

Submission status: Time Limit Exceeded

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

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への最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行けそう
        # d[i][i] < 0 なら、グラフは負のサイクルを持つ
        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])
        hasNegativeCycle = False
        for i in range(self.N):
            if self.d[i][i] < 0:
                hasNegativeCycle = True
                break
        for i in range(self.N):
            self.d[i][i] = 0
        return hasNegativeCycle, self.d


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

graph=WarshallFloyd(n)
graph2=WarshallFloyd(n)
for a,b,c in ABC:
    graph.add(a-1,b-1,c)
hasNegativeCycle, d = graph.WarshallFloyd_search()
#ans = sorted([[i, max(d[i])] for i in range(n)], key=lambda x: x[0])
ans=graph.WarshallFloyd_search()
#print(ans)
L=[[0,0,0] for _ in range(n**2)]
for i in range(n):
    for j in range(n):
        L[i*n+j][0],L[i*n+j][1],L[i*n+j][2]=i+1,j+1,ans[1][i][j]
#print(L)
for a,b,c in L:
    if 0<c<=l:
        graph2.add(a-1,b-1,1)
ans1=graph2.WarshallFloyd_search()
#print(ans1)
for i,j in st:
    if ans1[1][i-1][j-1]-1!=float('inf'):
        print(ans1[1][i-1][j-1]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
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への最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行けそう
        # d[i][i] < 0 なら、グラフは負のサイクルを持つ
        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])
        hasNegativeCycle = False
        for i in range(self.N):
            if self.d[i][i] < 0:
                hasNegativeCycle = True
                break
        for i in range(self.N):
            self.d[i][i] = 0
        return hasNegativeCycle, self.d

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

graph=WarshallFloyd(n)
graph2=WarshallFloyd(n)
for a,b,c in ABC:
    graph.add(a-1,b-1,c)
hasNegativeCycle, d = graph.WarshallFloyd_search()
#ans = sorted([[i, max(d[i])] for i in range(n)], key=lambda x: x[0])
ans=graph.WarshallFloyd_search()
#print(ans)
L=[[0,0,0] for _ in range(n**2)]
for i in range(n):
    for j in range(n):
        L[i*n+j][0],L[i*n+j][1],L[i*n+j][2]=i+1,j+1,ans[1][i][j]
#print(L)
#print(L)
for a,b,c in L:
    if 0<c<=l:
        graph2.add(a-1,b-1,1)
ans1=graph2.WarshallFloyd_search()
#print(ans1)
for i,j in st:
    if ans1[1][i-1][j-1]-1!=float('inf'):
        print(ans1[1][i-1][j-1]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
#WarshallFloyd法(全点対最短路)　計算量O(|V|**3)
#V:頂点の集合 E:辺の集合

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への最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行けそう
        # d[i][i] < 0 なら、グラフは負のサイクルを持つ
        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])
        hasNegativeCycle = False
        for i in range(self.N):
            if self.d[i][i] < 0:
                hasNegativeCycle = True
                break
        for i in range(self.N):
            self.d[i][i] = 0
        return hasNegativeCycle, self.d

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

graph=WarshallFloyd(n)
graph2=WarshallFloyd(n)
for a,b,c in ABC:
    graph.add(a-1,b-1,c)
hasNegativeCycle, d = graph.WarshallFloyd_search()
#ans = sorted([[i, max(d[i])] for i in range(n)], key=lambda x: x[0])
ans=graph.WarshallFloyd_search()
#print(ans)
L=[[0,0,0] for _ in range(n**2)]
for i in range(n):
    for j in range(n):
        L[i*n+j][0],L[i*n+j][1],L[i*n+j][2]=i+1,j+1,ans[1][i][j]
#print(L)
#print(L)
for a,b,c in L:
    if 0<c<=l:
        graph2.add(a-1,b-1,1)
ans1=graph2.WarshallFloyd_search()
#print(ans1)
for i,j in st:
    if ans1[1][i-1][j-1]-1!=float('inf'):
        print(ans1[1][i-1][j-1]-1)
    else:
        print(-1)

Submission status: Time Limit Exceeded

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

V = list(range(N))  # vertices
E = [[0 if v == u else float('inf') for u in V] for v in V]

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

def allpairs_shortest_paths(D):
    """Floyd-Warshall algorithm"""
    for v in V:
        for a in V:
            for b in V:
                D[a][b] = min(D[a][b], D[a][v] + D[v][b])

allpairs_shortest_paths(E)

for row in E:
    for u in range(len(row)):
        row[u] = 1 if row[u] <= L else float('inf')

allpairs_shortest_paths(E)

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

Submission status: Time Limit Exceeded

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

V = list(range(N))  # vertices
E = [[0 if v == u else float('inf') for u in V] for v in V]

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

def allpairs_shortest_paths(D):
    """Floyd-Warshall algorithm"""
    for v in V:
        for a in V:
            for b in V:
                D[a][b] = min(D[a][b], D[a][v] + D[v][b])
    return D

D = [[E[v][u] for u in V] for v in V]
D = allpairs_shortest_paths(D)

D = [[1 if D[v][u] <= L else float('inf') for u in V] for v in V]
D = allpairs_shortest_paths(D)

Q = int(input())
for i 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:
N, M, L = map(int, input().split())

V = list(range(1, N + 1))  # vertices
E = {v: {v: 0} for v in V}

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

def allpairs_shortest_paths(D):
    """Floyd-Warshall algorithm"""
    for v in V:
        D2 = {}
        for a in V:
            D2[a] = {}
            for b in V:
                D2[a][b] = min(D[a][b], D[a][v] + D[v][b])
        D = D2
    return D

D = {v: {u: E[v][u] if u in E[v] else float('inf') for u in V} for v in V}
D = allpairs_shortest_paths(D)

D = {v: {u: 1 if D[v][u] <= L else float('inf') for u in V} for v in V}
D = allpairs_shortest_paths(D)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools

input = sys.stdin.readline

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

dis = [[float("inf") for _ in range(N)] for _ in range(N)]

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

for k, i, j in itertools.product(range(N), repeat=3):
    dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])

for i, j in itertools.product(range(N), repeat=2):
    dis[i][j] = 1 if dis[i][j] <= L else float("inf")

for k, i, j in itertools.product(range(N), repeat=3):
    dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])

Q = int(input())

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

Submission status: Time Limit Exceeded

Solution code:
n, m, L = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]
q = int(input())
st = [list(map(int, input().split())) for _ in range(q)]

d = [[float('inf') for _ in range(n)] for _ in range(n)]
for a, b, c in abc:
    if c > L:
        continue
    d[a-1][b-1] = c
    d[b-1][a-1] = c

def warshall_floyd(d):
    for k in range(n):
        for i in range(n):
            if i == k:
                continue
            for j in range(n):
                if i == j:
                    continue
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

warshall_floyd(d)

for i in range(n):
    for j in range(n):
        if i == j:
            continue
        elif d[i][j] <= L:
            d[i][j] = 1
        else:
            d[i][j] = float('inf')

warshall_floyd(d)

for s, t in st:
    if d[s-1][t-1] == float('inf'):
        print(-1)
    else:
        print(d[s-1][t-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys

inp = sys.stdin
# inp = open("testdata.txt", "r")
def input():
	return inp.readline().strip()

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

adjl = [[0 if i==j else float('inf') for j in range(n)] for i in range(n)]

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

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

old_adjl = [[ele for ele in row] for row in adjl]

for i in range(n):
	for j in range(n):
		if i==j: adjl[i][j] = 0
		else: adjl[i][j] = 1 if old_adjl[i][j] <= l else float("inf")

for k in range(n):
	for i in range(n):
		for j in range(n):
			if i==k or k==j:
				continue
			adjl[i][j] = min(adjl[i][j], adjl[i][k]+adjl[k][j])

q = int(input())

for _ in range(q):
	a, b = map(int, input().split())
	ans = adjl[a-1][b-1]
	print(-1 if ans==float("inf") else ans-1)

Submission status: Time Limit Exceeded

Solution code:
#import sys
import heapq
#from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 1234567890

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  if c>l:
    continue
  a -= 1
  b -= 1
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  #for j in range(n):
  #  if j==i:
  #    continue
  #  if hops[i][j] > hops[j][i]:
  #    hops[i][j] = hops[j][i]

  #q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  q = [ ((0,distance[i][x]), x) for x in dst[i] ]
  heapq.heapify(q)
  while len(q)>0:
    #y,e = q.popleft()
    e,y = heapq.heappop(q)
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      if newd < hops[i][f]:
        heapq.heappush(q,(newd,f))
        #q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

B2 = BIG//2
#for i in range(n):
#  for j in range(n):
#    if hops[i][j][0] > B2:
#      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  x = hops[s-1][t-1][0]
  print(x if x<B2 else -1)

Submission status: Time Limit Exceeded

Solution code:
#import sys
from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 1234567890

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  if c>l:
    continue
  a -= 1
  b -= 1
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  while len(q)>0:
    y,e = q.popleft()
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      if newd < hops[i][f]:
        q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

B2 = BIG//2
#for i in range(n):
#  for j in range(n):
#    if hops[i][j][0] > B2:
#      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  x = hops[s-1][t-1][0]
  print(x if x<B2 else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 1234567890

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  if c>l:
    continue
  a -= 1
  b -= 1
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  while len(q)>0:
    y,e = q.popleft()
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      if newd < hops[i][f]:
        q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

B2 = BIG//2
#for i in range(n):
#  for j in range(n):
#    if hops[i][j][0] > B2:
#      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  x = hops[s-1][t-1][0]
  print(x if x<B2 else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 1234567890

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  a -= 1
  b -= 1
  if c>l:
    continue
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  d = (0,0)
  q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  while len(q)>0:
    y,e = q.popleft()
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      if newd < hops[i][f]:
        q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

for i in range(n):
  for j in range(n):
    if hops[i][j][0] > BIG/2:
      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  print(hops[s-1][t-1][0])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 9876598765

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  a -= 1
  b -= 1
  if c>l:
    continue
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  d = (0,0)
  q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  while len(q)>0:
    y,e = q.popleft()
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      if newd < hops[i][f]:
        q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

for i in range(n):
  for j in range(n):
    if hops[i][j][0] > BIG/2:
      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  print(hops[s-1][t-1][0])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split()) 
DBG = True  and False
BIG = 9876598765

def ddprint(x):
  if DBG:
    print(x)

n,m,l = inm()

distance = [ [BIG] * n for i in range(n) ]
hops = [ [(BIG,0)] * n for i in range(n) ]
for i in range(n):
  distance[i][i] = 0
  hops[i][i] = (0,0)

dst = [ [] for i in range(n) ]
for i in range(m):
  a,b,c = inm()
  a -= 1
  b -= 1
  if c>l:
    continue
  distance[a][b] = distance[b][a] = c
  dst[a].append(b)
  dst[b].append(a)

for i in range(n):
  d = (0,0)
  q = deque([ (x,(0,distance[i][x])) for x in dst[i] ])
  while len(q)>0:
    y,e = q.popleft()
    #ddprint("y {} e {} {}".format(y,e[0],e[1]))
    if e>=hops[i][y]:
      continue
    #ddprint("upd i {} y {}".format(i,y))
    hops[i][y] = e
    for f in dst[y]:
      ds = distance[y][f]
      #ddprint("y {} f {} ds {}".format(y,f,ds))
      if e[1]+ds > l:
        newd = (e[0]+1, ds)
      else:
        newd = (e[0], e[1]+ds)
      q.append((f,newd))

if DBG:
  for i in range(n):
    print(hops[i])

for i in range(n):
  for j in range(n):
    if hops[i][j][0] > BIG/2:
      hops[i][j] = (-1,0)

p = inn()
for i in range(p):
  s,t = inm()
  #ddprint("q {} s {} t {}".format(i,s,t))
  print(hops[s-1][t-1][0])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from scipy.sparse.csgraph import floyd_warshall
    
def solve(s,t,edge):
    edge = floyd_warshall(edge)
 
    for i in range(n):
        for j in range(n):
            if edge[i][j]<=l:
                edge[i][j] = 1
            else:
                edge[i][j] = 0
 
    edge = floyd_warshall(edge)
 
    if edge[s-1][t-1] == float("inf"):
        return -1
    else:
        return int(edge[s-1][t-1] - 1)
      
n,m,l = map(int,input().split())
edge = [[0]*n for _ in range(n)]
for i in range(m):
    a,b,c = map(int,input().split())
    edge[a-1][b-1] = c
    edge[b-1][a-1] = c
    
q = int(input())
for i in range(q):
  s,t = map(int,input().split())
  print(solve(s,t,edge))

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import floyd_warshall
    
def solve(s,t,edge):
    edge = floyd_warshall(edge)

    for i in range(n):
        for j in range(n):
            if edge[i][j]<=l:
                edge[i][j] = 1
            else:
                edge[i][j] = 0

    edge = floyd_warshall(edge)

    if edge[s-1][t-1] == float("inf"):
        return -1
    else:
        return int(edge[s-1][t-1] - 1)
      
n,m,l = map(int,input().split())
edge = [[0]*n for _ in range(n)]
for i in range(m):
    a,b,c = map(int,input().split())
    edge[a-1][b-1] = c
    edge[b-1][a-1] = c
    
q = int(input())
for i in range(q):
  s,t = map(int,input().split())
  print(solve(s,t,edge))

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

d = [[float("inf") for i in range(n)] for _ in range(n)]
# d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(w):
    x, y, z = map(int, input().split())
    x -= 1
    y -= 1
    d[x][y] = z
    d[y][x] = z
for i in range(n):
    d[i][i] = 0  # 自身のところに行くコストは０
d = warshall_floyd(d)

D = [[float("inf") for i in range(n)] for i in range(n)]

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

D = warshall_floyd(D)

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

Submission status: Time Limit Exceeded

Solution code:
N,M,L = map(int,input().split())
abc = [[int(i) for i in input().split()] for j in range(M)]
Q = int(input())
INF = 1<<30
Path = [[INF for i in range(N)] for j in range(N)]
AnsPath = [[INF for i in range(N)] for j in range(N)]

def PathInit():
    for i in range(N):
        Path[i][i] = 0

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

PathInit()
for i,j,k in abc:
    Path[i-1][j-1] = k
    #双方向

    Path[j-1][i-1] = k
wasialFloid(Path)
for i in range(N):
    for j in range(N):
        if Path[i][j] <= L:
            AnsPath[i][j] = 1
wasialFloid(AnsPath)
for i in range(Q):
    s,t = map(int,input().split())
    if AnsPath[s-1][t-1] == INF:
        print(-1)
    else:
        print(AnsPath[s-1][t-1]-1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M,L = map(int,input().split( ))
R = [[] for x in range(N+1)]
ST = []
def depth_search(start,end,gas,gasup):
    stack.append(start)
    global mingas
    global gasreco
    for i in range(len(R[start])):
        if R[start][i][0] not in stack:
            now = R[start][i][0]
            gas = gasreco[-1][0]
            gasup = gasreco[-1][1]
            if gas >= R[start][i][1]:
                gas = gas - R[start][i][1]
            else:
                gas = L - R[start][i][1]
                gasup+=1
            gasreco.append([gas,gasup])
            if now == end :
                if mingas == -1 or gasup < mingas:
                    mingas = gasup
                gasreco.pop()
                continue
            depth_search(now,end,gasreco[-1][0],gasreco[-1][1])
    stack.pop()
    if stack == []:
        return mingas
    else:
        gasreco.pop()



for i in range(M):
    A, B, C = map(int,input().split( ))
    if C <= L:
        R[A].append([B,C])
        R[B].append([A,C])
Q = int(input())
for i in range(Q):
    ST.append(list(map(int,input().split( ))))
result = [-1 for _ in range(Q)]
for i in range(Q):
    gasreco = [[L,0]]
    stack = []
    mingas = -1
    mingasoline = depth_search(ST[i][0],ST[i][1],L,0)
    result[i] = mingasoline
for i in result:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(d):
  n = len(d)
  for i in range(n):
    for j in range(n):
      for k in range(n):
        d[j][k] = min(d[j][k], d[j][i]+d[k][i])
  
  return d


N, M, L = map(int, input().split())
d = [[float('inf') for _ in range(N)] for _ in range(N)]

for _ 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)
d2 = [[1 if d[i][j]<=L else float('inf') for j in range(N)] for i in range(N)]
for i in range(N):
  d2[i][i] = 0

d2 = warshall_floyd(d2)

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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


N, M, L = map(int, input().split())
d = np.ones([N, N]) * np.inf

for _ 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)
d2 = (d <= L)*1.0
d2[d2 == 0] = np.inf
d2 = warshall_floyd(d2)

Q = int(input())
for _ in range(Q):
  s, t = map(int, input().split())
  out = d2[s-1, t-1]
  print(-1 if out == np.inf else int(out-1))

Submission status: Time Limit Exceeded

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

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

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

Rd = floyd_warshall(RG, directed=False)

FG=lil_matrix((N,N))
FG[Rd <= L] = 1

Fd = floyd_warshall(FG, directed=False)

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

Submission status: Time Limit Exceeded

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

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

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

Rd = floyd_warshall(RG, directed=False)

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

Fd = floyd_warshall(FG, directed=False)

Q=int(input())
for i in range(Q):
    s, t = map(int, input().split())
    v = Fd[s-1][t-1]
    if s == t:
        print (str(0))
    if v == float('inf'):
        print (str(-1))
    else:
        print (str(int(v-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 xrange(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, directed=False)

FG=lil_matrix((N,N))
for i in xrange(N):
    for j in xrange(i+1, N):
        if Rd[i][j] <= L:
            FG[(i,j)] = 1
            FG[(j,i)] = 1

Fd = floyd_warshall(FG, directed=False)

Q=int(raw_input())
for i in xrange(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:
# 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())

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

Fd = floyd_warshall(FG.tocsr())

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