Problem:


Score : 500 points

Problem Statement

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

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

Process the following Q queries:

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

Constraints

All values in input are integers.

2 \leq N \leq 300

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

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

1 \leq C_i \leq 10^9

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

1 \leq s_i, t_i \leq N

s_i \neq t_i

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

Input

Input is given from Standard Input in the following format:

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

Output

Print Q lines.

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

Sample Input 1

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

Sample Output 1

0
1

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

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

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

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



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


Sample output:
0
1

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

if __name__ == '__main__':
    n, m, l = map(int, stdin.readline().rstrip().split())
    abc = [list(map(int, stdin.readline().rstrip().split())) for _ in range(m)]
    q = int(stdin.readline().rstrip())
    st = [list(map(int, stdin.readline().rstrip().split())) for _ in range(q)]

    from collections import defaultdict
    import heapq
    g = defaultdict(list)
    for a, b, c in abc:
        if c <= l:
            g[a-1].append((b-1, c))
            g[b-1].append((a-1, c))

    starts = [s - 1 for (s, t) in st]

    ans = dict()
    for start in starts:
        mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
        mins[start] = [0, l]

        q = [(0, l, start)] # added, left_gas, pos
        heapq.heapify(q)

        while q:
            a, b, u = heapq.heappop(q)

            if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
                continue

            for v, weight in g[u]:
                if weight > b:
                    a_new = a + 1
                    b_new = l - weight
                else:
                    a_new = a
                    b_new = b - weight

                if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                    mins[v][0], mins[v][1] = a_new, b_new
                    heapq.heappush(q, (a_new, b_new, v))

        ans[start] = [_mins[0] for _mins in mins]

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

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

from collections import defaultdict
import heapq
g = defaultdict(list)
for a, b, c in abc:
    g[a-1].append((b-1, c))
    g[b-1].append((a-1, c))

ans = []
for start in range(n):
    mins = [[float('inf'), 0] for _ in range(n)] # (a, b)
    mins[start] = [0, l]

    q = [(0, l, start)] # added, left_gas, pos
    heapq.heapify(q)

    while q:
        a, b, u = heapq.heappop(q)

        if (a > mins[u][0]) or (a == mins[u][0] and b < mins[u][1]):
            continue

        for v, weight in g[u]:
            if weight > l:
                continue

            if weight > b:
                a_new = a + 1
                b_new = l - weight
            else:
                a_new = a
                b_new = b - weight

            if a_new < mins[v][0] or (a_new == mins[v][0] and b_new > mins[v][1]):
                mins[v][0], mins[v][1] = a_new, b_new
                heapq.heappush(q, (a_new, b_new, v))

    ans.append([_mins[0] for _mins in mins])

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

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def wff(n,l,abc,st):
    nl = list(range(n))
    d = [[inf] * n for _ in nl]
    for i in nl:
        d[i][i] = 0
    for a,b,c in abc:
        a -= 1
        b -= 1
        d[a][b] = c
        d[b][a] = c

    for i in nl:
        di = d[i]
        for j in nl:
            if i == j:
                continue
            dj = d[j]
            for k in nl:
                if i != k and j != k and dj[k] > dj[i] + di[k]:
                    dj[k] = dj[i] + di[k]

    dd = [[inf] * n for _ in nl]
    for i in nl:
        dd[i][i] = 0
    for i in nl:
        for j in nl:
            if j != i and d[i][j] <= l:
                dd[i][j] = 1

    for i in nl:
        di = dd[i]
        for j in nl:
            if i == j:
                continue
            dj = dd[j]
            for k in nl:
                if i != k and j != k and dj[k] > dj[i] + di[k]:
                    dj[k] = dj[i] + di[k]

    rr = []
    for s,t in st:
        if dd[s][t] == inf:
            rr.append(-1)
        else:
            rr.append(dd[s][t] - 1)

    return JA(rr, "\n")


def main():
    n,m,l = LI()
    abc = [LI() for _ in range(m)]
    q = I()
    st = [LI_() for _ in range(q)]

    if m > 300 * 100:
        return wff(n,l,abc,st)

    e = collections.defaultdict(list)
    for a,b,c in abc:
        a -= 1
        b -= 1
        e[a].append((b, c))
        e[b].append((a, c))

    def search(s):
        d = collections.defaultdict(lambda: inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv, ud in e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] > vd and vd <= l:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return set([k for k,v in d.items() if v <= l])

    d = {}
    for i in range(n):
        d[i] = search(i)

    dd = [[inf] * n for _ in range(n)]
    for i in range(n):
        q = [(0, i)]
        qi = 0
        v = set([i])
        while len(q) > qi:
            k, t = q[qi]
            qi += 1
            u = d[t] - v
            v |= u
            dd[i][t] = k
            for w in u:
                q.append((k+1, w))

    rr = []
    for s,t in st:
        if dd[s][t] == inf:
            rr.append(-1)
        else:
            rr.append(dd[s][t] - 1)


    return JA(rr, "\n")

print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,m,l = LI()
    abc = [LI() for _ in range(m)]
    q = I()
    st = [LI_() for _ in range(q)]

    e = collections.defaultdict(list)
    for a,b,c in abc:
        a -= 1
        b -= 1
        e[a].append((b, c))
        e[b].append((a, c))

    def search(s):
        d = collections.defaultdict(lambda: inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv, ud in e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] > vd and vd <= l:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return set([k for k,v in d.items() if v <= l])

    d = {}
    for i in range(n):
        d[i] = search(i)

    dd = [[inf] * n for _ in range(n)]
    for i in range(n):
        q = [(0, i)]
        qi = 0
        v = set([i])
        while len(q) > qi:
            k, t = q[qi]
            qi += 1
            u = d[t] - v
            v |= u
            dd[i][t] = k
            for w in u:
                q.append((k+1, w))

    rr = []
    for s,t in st:
        if dd[s][t] == inf:
            rr.append(-1)
        else:
            rr.append(dd[s][t] - 1)


    return JA(rr, "\n")

print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,m,l = LI()
    abc = [LI() for _ in range(m)]
    q = I()
    st = [LI_() for _ in range(q)]

    nl = list(range(n))
    d = [[inf] * n for _ in nl]
    for i in nl:
        d[i][i] = 0
    for a,b,c in abc:
        a -= 1
        b -= 1
        d[a][b] = c
        d[b][a] = c

    for i in nl:
        di = d[i]
        for j in nl:
            if i == j:
                continue
            dj = d[j]
            for k in nl:
                if i != k and j != k and dj[k] > dj[i] + di[k]:
                    dj[k] = dj[i] + di[k]

    dd = [[inf] * n for _ in nl]
    for i in nl:
        dd[i][i] = 0
    for i in nl:
        for j in nl:
            if j != i and d[i][j] <= l:
                dd[i][j] = 1

    for i in nl:
        di = dd[i]
        for j in nl:
            if i == j:
                continue
            dj = dd[j]
            for k in nl:
                if i != k and j != k and dj[k] > dj[i] + di[k]:
                    dj[k] = dj[i] + di[k]

    rr = []
    for s,t in st:
        if dd[s][t] == inf:
            rr.append(-1)
        else:
            rr.append(dd[s][t] - 1)


    return JA(rr, "\n")

print(main())

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

import sys
input = sys.stdin.readline

INF = float("INF")

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

cost = [[INF] * N for _ in range(N)]
for i in range(N):
    cost[i][i] = 0

for _ in range(M):
    v1, v2, w = map(int, input().split())
    v1, v2 = v1-1, v2-1
    cost[v1][v2] = w
    cost[v2][v1] = w

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

for i in range(N):
    for j in range(N):
        if cost[i][j] == 0:
            continue
        elif cost[i][j] <= L:
            cost[i][j] = 1
        else:
            cost[i][j] = INF

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

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

Submission status: Time Limit Exceeded

Solution code:

INF = float("INF")


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

cost = [[INF] * N for _ in range(N)]
for i in range(N):
    cost[i][i] = 0

for _ in range(M):
    v1, v2, w = map(int, input().split())
    v1, v2 = v1-1, v2-1
    cost[v1][v2] = w
    cost[v2][v1] = w

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

for i in range(N):
    for j in range(N):
        if cost[i][j] == 0:
            pass
        elif cost[i][j] <= L:
            cost[i][j] = 1
        else:
            cost[i][j] = INF

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

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

INF = float("INF")


def run(cost, N):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                cost[i][j] = min(
                    cost[i][j],
                    cost[i][k] + cost[k][j])
    return cost


if __name__ == '__main__':
    N, M, L = map(int, input().split())

    cost = [[INF] * N for _ in range(N)]
    for i in range(N):
        cost[i][i] = 0

    for _ in range(M):
        v1, v2, w = map(int, input().split())
        v1, v2 = v1-1, v2-1
        cost[v1][v2] = w
        cost[v2][v1] = w
    cost = run(cost, N)

    for i in range(N):
        for j in range(N):
            if cost[i][j] == 0:
                pass
            elif cost[i][j] <= L:
                cost[i][j] = 1
            else:
                cost[i][j] = INF
    cost = run(cost, N)

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)


def run(cost, N):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                cost[i][j] = min(
                    cost[i][j],
                    cost[i][k] + cost[k][j])
    return cost


if __name__ == '__main__':
    N, M, L = map(int, input().split())

    cost = [[float('inf')] * N for _ in range(N)]
    for i in range(N):
        cost[i][i] = 0

    for _ in range(M):
        v1, v2, w = map(int, input().split())
        v1, v2 = v1-1, v2-1
        if w <= L:
            cost[v1][v2] = w
            cost[v2][v1] = w
    cost = run(cost, N)

    for i in range(N):
        for j in range(N):
            if cost[i][j] == 0:
                pass
            elif cost[i][j] <= L:
                cost[i][j] = 1
            else:
                cost[i][j] = float('inf')
    cost = run(cost, N)

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)


class Warshall(object):
    def __init__(self, n:int):
        self.cost = [[float('inf')] * n for _ in range(n)]

        self.n = n
        for i in range(n):
            self.cost[i][i] = 0

    def add_edge(self, v1: int, v2: int, w: float, undirected=False):
        self.cost[v1][v2] = w
        if undirected:
            self.cost[v2][v1] = w

    def run(self):
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    self.cost[i][j] = min(
                        self.cost[i][j],
                        self.cost[i][k] + self.cost[k][j]
                    )


if __name__ == '__main__':
    N, M, L = map(int, input().split())

    g = Warshall(N)
    g2 = Warshall(N)
    for _ in range(M):
        v1, v2, w = map(int, input().split())
        if w <= L:
            g.add_edge(v1 - 1, v2 - 1, w, undirected=True)
    g.run()

    for i in range(N):
        for j in range(N):
            if g.cost[i][j] <= L:
                g2.cost[i][j] = 1
    g2.run()

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

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
N,M,L=map(int,input().split())
costable=[[float("inf") for _ in range(N)] for _ in range(N)]
needoil=[[float("inf") for _ in range(N)] for _ in range(N)]
needing=0
tree=[[] for _ in range(N)]
for i in range(M):
    a,b,c=map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    costable[a-1][b-1]=c
    costable[b-1][a-1]=c
Q=int(input())
query=[list(map(int,input().split())) for _ in range(Q)]
for i in range(N):
    q=[]
    q.append((0,i,L))
    needoil[i][i]=0
    heapify(q)
    #print(q)
    while len(q)>0:
        needingnum,u,nowoil=heappop(q)
        #print(needingnum,u,nowoil)
        if needoil[i][u]<needingnum:continue
        #if nowoil!=L:
        #    q.heappush([needingnum+1,i,L])
        for j in tree[u]:
            nextoil=nowoil-costable[u][j]
            nextoilwithcharge=L-costable[u][j]
            if (nextoil>=0)and(needingnum<=needoil[i][j]):
                needoil[i][j]=needingnum
                heappush(q,(needingnum,j,nextoil))
                #heappush(q, [needingnum+1, j, nextoilwithcharge])
            elif (nextoilwithcharge>=0)and(needingnum+1<=needoil[i][j]):
                needoil[i][j] = needingnum+1
                heappush(q,(needingnum+1,j,nextoilwithcharge))
        #print(needoil,q)
        #input()
for l in query:
    u,v=l
    num=needoil[u-1][v-1]
    if num==float("inf"):
        print(-1)
    else:
        print(num)

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
N,M,L=map(int,input().split())
costable=[[float("inf") for _ in range(N)] for _ in range(N)]
needoil=[[float("inf") for _ in range(N)] for _ in range(N)]
needing=0
tree=[[] for _ in range(N)]
for i in range(M):
    a,b,c=map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    costable[a-1][b-1]=c
    costable[b-1][a-1]=c
Q=int(input())
query=[list(map(int,input().split())) for _ in range(Q)]
for i in range(N):
    q=[]
    q.append([0,i,L])
    needoil[i][i]=0
    heapify(q)
    #print(q)
    while len(q)>0:
        needingnum,u,nowoil=heappop(q)
        #print(needingnum,u,nowoil)
        if needoil[i][u]<needingnum:continue
        #if nowoil!=L:
        #    q.heappush([needingnum+1,i,L])
        for j in tree[u]:
            nextoil=nowoil-costable[u][j]
            nextoilwithcharge=L-costable[u][j]
            if (nextoil>=0)and(needingnum<=needoil[i][j]):
                needoil[i][j]=needingnum
                heappush(q,[needingnum,j,nextoil])
                #heappush(q, [needingnum+1, j, nextoilwithcharge])
            elif (nextoilwithcharge>=0)and(needingnum+1<=needoil[i][j]):
                needoil[i][j] = needingnum+1
                heappush(q,[needingnum+1,j,nextoilwithcharge])
        #print(needoil,q)
        #input()
for l in query:
    u,v=l
    num=needoil[u-1][v-1]
    if num==float("inf"):
        print(-1)
    else:
        print(num)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)


class Warshall(object):
    """ 全てのノード間の最短路を計算する """
    def __init__(self, n:int):
        self.adjacency_dict = {}
        self.n = n
        for i in range(n):
            self.add_vertex(i)

            for j in range(n):
                if i == j:
                    self.adjacency_dict[i][j] = 0
                else:
                    self.adjacency_dict[i][j] = float('inf')

    def add_vertex(self, v: int):
        """ ノードを追加する """
        self.adjacency_dict[v] = {}

    def add_edge(self, v1: int, v2: int, w: float, undirected=False):
        self.adjacency_dict[v1][v2] = w
        if undirected:
            self.adjacency_dict[v2][v1] = w

    def run(self):
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    self.adjacency_dict[i][j] = min(
                        self.adjacency_dict[i][j],
                        self.adjacency_dict[i][k] + self.adjacency_dict[k][j]
                    )


if __name__ == '__main__':
    N, M, L = map(int, input().split())

    g = Warshall(N)
    g2 = Warshall(N)
    for _ in range(M):
        v1, v2, w = map(int, input().split())
        if w <= L:
            g.add_edge(v1 - 1, v2 - 1, w, undirected=True)
            # g2.add_edge(v1 - 1, v2 - 1, 1, undirected=True)
    g.run()

    for i in range(N):
        for j in range(N):
            if g.adjacency_dict[i][j] <= L:
                g2.adjacency_dict[i][j] = 1
    g2.run()

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# E

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect

# 再起回数上限変更
# sys.setrecursionlimit(1000000)


class Warshall(object):
    """ 全てのノード間の最短路を計算する """
    def __init__(self, n:int):
        self.adjacency_dict = {}
        self.n = n
        for i in range(n):
            self.add_vertex(i)

            for j in range(n):
                if i == j:
                    self.adjacency_dict[i][j] = 0
                else:
                    self.adjacency_dict[i][j] = float('inf')

    def add_vertex(self, v: int):
        """ ノードを追加する """
        self.adjacency_dict[v] = {}

    def add_edge(self, v1: int, v2: int, w: float, undirected=False):
        self.adjacency_dict[v1][v2] = w
        if undirected:
            self.adjacency_dict[v2][v1] = w

    def run(self):
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    self.adjacency_dict[i][j] = min(
                        self.adjacency_dict[i][j],
                        self.adjacency_dict[i][k] + self.adjacency_dict[k][j]
                    )


if __name__ == '__main__':
    N, M, L = map(int, input().split())

    g = Warshall(N)
    g2 = Warshall(N)
    for _ in range(M):
        v1, v2, w = map(int, input().split())
        if w <= L:
            g.add_edge(v1 - 1, v2 - 1, w, undirected=True)
            g2.add_edge(v1 - 1, v2 - 1, 1, undirected=True)

    g.run()

    g2.adjacency_dict = g.adjacency_dict
    for i in range(N):
        for j in range(N):
            if g.adjacency_dict[i][j] <= L:
                g2.adjacency_dict[i][j] = 1
    g2.run()

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

Submission status: Time Limit Exceeded

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

def solve():
    INF = float('inf')

    def WarshallFloyd(adjList, INF):
        numV = len(adjList)
        D = [[INF]*numV for _ in range(numV)]
        for u, adj in enumerate(adjList):
            for v, wt in adj:
                D[u][v] = wt
            D[u][u] = 0

        for k in range(numV):
            Dk = D[k]
            for i in range(numV):
                Di = D[i]
                Dik = Di[k]
                for j in range(numV):
                    D2 = Dik + Dk[j]
                    if D2 < Di[j]:
                        D[i][j] = D2

        return D

    N, M, L = map(int, input().split())
    adjL = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a, b = a-1, b-1
        adjL[a].append((b, c))
        adjL[b].append((a, c))
    Q = int(input())
    querys = [tuple(map(int, input().split())) for _ in range(Q)]

    cost1ss = WarshallFloyd(adjL, INF)

    adjL2 = [[] for _ in range(N)]
    for a in range(N):
        for b in range(a+1, N):
            if cost1ss[a][b] <= L:
                adjL2[a].append((b, 1))
                adjL2[b].append((a, 1))

    cost2ss = WarshallFloyd(adjL2, INF)

    anss = []
    for s, t in querys:
        s, t = s-1, t-1
        cost = cost2ss[s][t]
        if cost == INF:
            anss.append(-1)
        else:
            anss.append(cost-1)

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


solve()

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = 10 ** 30
dp = [[INF] * N for _ in range(N)]

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

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

dp2 = [[INF] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if dp[i][j] <= L:
            dp2[i][j] = 1
            dp2[j][i] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k]+dp2[k][j])
    
Q = int(input())
for i in range(Q):
    s, t = map(lambda x:int(x)-1, input().split())
    d = dp2[s][t]
    if d == INF:
        print(-1)
    else:
        print(d-1)

Submission status: Time Limit Exceeded

Solution code:
N, M, L = map(int, input().split())
INF = 10 ** 30
dp = [[INF] * N for _ in range(N)]

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

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

dp2 = [[INF] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if dp[i][j] <= L:
            dp2[i][j] = 1
for k in range(N):
    for i in range(N):
        for j in range(N):
            dp2[i][j] = min(dp2[i][j], dp2[i][k]+dp2[k][j])
    

Q = int(input())
for i in range(Q):
    s, t = map(lambda x:int(x)-1, input().split())
    d = dp2[s][t]
    if d == INF:
        print(-1)
    else:
        print(d-1)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from scipy.sparse.csgraph import shortest_path
    import numpy as np
    inf = 10 ** 20
    n, m, l = map(int, input().split())
    if m == 0:
        q = int(input())
        for _ in range(q):
            print(-1)
        return
    ar = np.zeros((n, n))
    for _ in range(m):
        a, b, c = map(int, input().split())
        ar[a - 1, b - 1] = c
        ar[b - 1, a - 1] = c
    x = shortest_path(ar)
    br = np.zeros((n, n))
    for i in range(n):
        for j in range(i + 1, n):
            if x[i, j] <= l:
                br[i, j] = 1
                br[j, i] = 1
    y = shortest_path(br)
    q = int(input())
    for _ in range(q):
        s, t = map(int, input().split())
        p = y[s - 1, t - 1]
        print(int(p) - 1 if p < inf else -1)


if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
INF = 1e10

def floyd(n):
    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])

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

d = [[INF]*N for i in range(N)]

for x in range(M):
    a,b,w = map(int,input().split())
    d[a-1][b-1] = w
    d[b-1][a-1] = w
    d[a-1][a-1] = 0
    d[b-1][b-1] = 0

floyd(N)
grafo2 = [[INF] * N for i in range(N)]

for x in range(len(d)):
    for y in range(len(d[x])) :
        if d[x][y] <= L:
            grafo2[x][y] = 1
            grafo2[y][x] = 1

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

query = int(input())

for x in range(query):
    s,t = map(int,input().split())
    if grafo2[s-1][t-1] == INF:
        print(-1)
    else:
        print(grafo2[s-1][t-1] - 1)