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: Accepted

Solution code:
N, M, L = map(int, input().split())
dist = [[10**12] * N for _ in range(N)]
for i in range(N):
    dist[i][i] = 0
    
for _ in range(M):
    a, b, c = map(int, input().split())
    if c <= L:
    	dist[a-1][b-1] = dist[b-1][a-1] = 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])

old_dist = [row[:] for row in dist]
for i in range(N):
    for j in range(N):
        if old_dist[i][j] <= L:
            dist[i][j] = 1
            
for k in range(N):
    for i in range(N):
        for j in range(N):
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

Q = int(input())
for _ in range(Q):
    start, end= map(int, input().split())
    if dist[start-1][end-1] < 10**12:
    	print(dist[start-1][end-1] - 1)
    else:
        print(-1)

Submission status: Accepted

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall


def solve():
    N, M, L = map(int, input().split())
    dist = [[0 for _ in range(N)] for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        dist[a-1][b-1] = c
        dist[b-1][a-1] = c
    fw = floyd_warshall(csr_matrix(dist))

    ok = [[0 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if fw[i][j] <= L:
                ok[i][j] = 1
    ans = floyd_warshall(csr_matrix(ok))

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


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n,m,l=map(int,input().split())
    E=[[] for _ in range(n)]
    for _ in range(m):
        a,b,c=map(int,input().split())
        if(c>l): continue
        a-=1; b-=1
        E[a].append((b,c))
        E[b].append((a,c))

    # 各頂点を始点としたDijkstra
    A=[None]*n
    for s in range(n):
        dist=[(INF,INF)]*n
        dist[s]=(0,0)
        visited=[0]*n
        for _ in range(n-1):
            v=min((dist[v],v) for v in range(n) if(not visited[v]))[1]
            visited[v]=1
            for nv,w in E[v]:
                a,b=dist[v]
                if(b+w<=l): na,nb=a,b+w
                else: na,nb=a+1,w
                if(dist[nv]>(na,nb)):
                    dist[nv]=(na,nb)
        A[s]=dist

    for _ in range(int(input())):
        s,t=map(int,input().split())
        s-=1; t-=1
        print(A[s][t][0] if(A[s][t][0]!=INF) else -1)
resolve()

Submission status: Accepted

Solution code:
N, M, L= map(int,input().split())
cost = [[float('inf')]*N for i in range(N)]

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

for _ in range(M):
    a,b,c = map(int,input().split())
    cost[a-1][b-1] = c
    cost[b-1][a-1] = c
def func(f):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                f[i][j] = min(f[i][k] + f[k][j], f[i][j])
    return f
cost = func(cost)
for i in range(N):
    for j in range(N):
        if cost[i][j] > L:
            cost[i][j] = float('inf')
        else:
            cost[i][j] = 1
cost = func(cost)

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

Submission status: Accepted

Solution code:
import sys
from copy import deepcopy

def main():
    INF = 10**18
    input = sys.stdin.readline
    N, M, L = [int(x) for x in input().split()]
    d = [set() for _ in range(N+1)]
    ds = [[INF] * (N+1) for _ in range(N+1)]
    bs = [[INF] * (N+1) for _ in range(N+1)]
    for _ in range(M):
        A, B, C = [int(x) for x in input().split()]
        A, B = sorted([A, B])
        d[A].add(B)
        if L >= C:
            ds[A][B] = C

    nes = set()
    for k in range(1, N+1):
        for i in range(1, N+1):
            for j in range(i+1, N+1):
                ds[i][j] = min(ds[i][j], ds[min(i, k)][max(i, k)] + ds[min(k, j)][max(k, j)])
                if ds[i][j] <= L:
                    bs[i][j] = 1

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

    Q, = [int(x) for x in input().split()]
    for _ in range(Q):
        s, t = sorted(int(x) for x in input().split())
        print(bs[s][t]-1 if bs[s][t] < INF else -1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
import sys
def input():
	return sys.stdin.readline()[:-1]

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

fw = floyd_warshall(csr_matrix(dist))

num = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if fw[i][j] <= l:
			num[i][j] = 1

ans = floyd_warshall(csr_matrix(num))

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

Submission status: Accepted

Solution code:
import sys
from scipy.sparse.csgraph import floyd_warshall
N, M, L = map(int, input().split())
INF = 10 ** 9 + 1
G = [[float('inf')] * N for i in range(N)]
for i in range(M):
    a, b, c = map(int, sys.stdin.readline().split())
    a, b = a - 1, b - 1
    G[a][b] = c
    G[b][a] = c


# 全点間最短距離を計算
G = floyd_warshall(G)


# コストL以下で移動可能な頂点間にコスト１の辺を張る
E = [[float('inf')] * N for i in range(N)]
for i in range(N):
    for j in range(N):
        if G[i][j] <= L:
            E[i][j] = 1


# そのグラフの全点間最短距離を求める
E = floyd_warshall(E)


# クエリに答えていく
Q = int(input())
for i in range(Q):
    s, t = map(int, sys.stdin.readline().split())
    s, t = s - 1, t - 1
    print(int(E[s][t] - 1) if E[s][t] != float('inf') else - 1)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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

edges = [[0] * N for _ in range(N)]

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

Q = int(input())
queries = []

for _ in range(Q):
    queries.append(list(map(int,input().split())))

# use flord warshall to find min path between all towns
edges = floyd_warshall(edges)

# if the two towns can be travelled to on one tank, add to our fuel graph with distance 1
for i in range(N):
    for j in range(N):
        if edges[i][j] <= L:
            edges[i][j] = 1
        else:
            edges[i][j] = 0

# use flord warshall to find min number of fuel tanks to travel between two towns
edges = floyd_warshall(edges)

for query in queries:
    s = query[0] - 1
    t = query[1] - 1
    num_tanks = edges[s][t] - 1
    if num_tanks != float('inf'):
        print(int(num_tanks))
    else:
        print("-1")

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse.csgraph import floyd_warshall

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

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

gurahu = floyd_warshall(gurahu, directed=False)
gurahu = np.where((gurahu <= L) & (gurahu > 0), 1, 0)
gurahu = floyd_warshall(gurahu) - np.ones((N, N))

Q = int(input())

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

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

N, M, L = inpl()
graph = [[0]*N for _ in range(N)]
for i in range(M):
    A, B, C = inpl()
    if C <= L:
        graph[A-1][B-1] = C

Q = int(input())
ST = []
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))

distance = floyd_warshall(csr_matrix(graph), directed=False)
path = [[0]*N for _ in range(N)]
for i in range(N-1):
    for j in range(i+1,N):
        d = distance[i][j]
        if d <= L:
            path[i][j] = 1
ans = floyd_warshall(csr_matrix(path), directed=False)
for s, t in ST:
    if ans[s][t] == np.float('inf'):
        print(-1)
    else:
        print(int(ans[s][t]-1))

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
def warshall_floyd(N, edges,
                   nopath=None,
                   start_distance=0,
                   plus_func=lambda D,d: D+d):
    '''
    edges: list of set
        edges = [{(y0, distance0), (y1, distance1), ...}, ...]
    '''
    ret = [[nopath]*N for _ in range(N)]
    for i in range(N):
        ret[i][i] = start_distance
    for i in range(N):
        for j, d in edges[i]:
            if 0 <= j < N:
                ret[i][j] = plus_func(start_distance, d)
    for k in range(N):
        for i in range(N):
            if i == k: continue
            for j in range(N):
                if j == k or ret[i][k] == nopath or ret[k][j] == nopath:
                    continue
                d = plus_func(ret[i][k], ret[k][j])
                if ret[i][j] == nopath or d < ret[i][j]:
                    ret[i][j] = d
    return ret

N, M, L = inpl()
road = [[] for _ in range(N)]
for i in range(M):
    A, B, C = inpl()
    if C <= L:
        road[A-1].append((B-1,C))
        road[B-1].append((A-1,C))

Q = int(input())
ST = []
goals = [set() for _ in range(N)]
for _ in range(Q):
    s, t = inpl()
    s -= 1
    t -= 1
    ST.append((s, t))

distance = warshall_floyd(N, road)
path = [set() for _ in range(N)]
for i in range(N):
    for j in range(N):
        d = distance[i][j]
        if d is not None and d <= L:
            path[i].add((j,1))
ans = warshall_floyd(N, path)
for s, t in ST:
    if ans[s][t] is None:
        print(-1)
    else:
        print(ans[s][t]-1)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
 
# 下準備
N, M, L = map(int,input().split())
d = [[float("inf") for i in range(N)] for j in range(N)]
answer_d = [[float("inf") for i in range(N)] for j in range(N)]
for i in range(M):
    A, B, C = map(int,input().split())
    d[A-1][B-1] = d[B-1][A-1] = C
for i in range(N):
    d[i][i] = 0
 
# 燃料補給回数の最小値を求める
d = floyd_warshall(d)
for i in range(N):
    for j in range(N):
        if d[i][j] <= L:
            answer_d[i][j] = answer_d[j][i] = 1
d = floyd_warshall(answer_d)
 
# クエリを答える
Q = int(input())
answer = [-1]*Q
for i in range(Q):
    s, t = map(int,input().split())
    if d[s-1][t-1] != float("inf"):
        answer[i] = d[s-1][t-1]-1
 
for i in answer:
    print(i)

Submission status: Accepted

Solution code:
INF = 10 ** 9
n, m, l = map(int, input().split())
d = [[INF for j in range(n + 1)] for i in range(n + 1)]
d2 = [[INF for j in range(n + 1)] for i in range(n + 1)]
for _ in range(m):
    i, j, c = map(int, input().split())
    d[i][j] = c
    d[j][i] = c
    if c <= l:
        d2[i][j] = 1
        d2[j][i] = 1

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

for k in range(1, n + 1):
    for i in range(1, n):
        for j in range(i, n + 1):
            dk = d[i][k] + d[k][j]
            if d[i][j] > dk:
                d[i][j] = dk
                d[j][i] = dk
                if dk <= l:
                    d2[i][j] = 1
                    d2[j][i] = 1

for k in range(1, n + 1):
    for i in range(1, n):
        for j in range(i, n + 1):
            dk = d2[i][k] + d2[k][j]
            if d2[i][j] > dk:
                d2[i][j] = dk
                d2[j][i] = dk

for i in range(q):
    s, t = Q[i]
    di = d2[s][t]
    if di >= INF:
        print(-1)
    else:
        print(di - 1)

Submission status: Accepted

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

    def Dijkstra(adjList, vSt):
        numV = len(adjList)
        useds = [False] * numV
        fuels = [-1] * numV
        fuels[vSt] = L
        nums = [INF] * numV
        num = 0
        vs = set([vSt])
        while vs:
            vNexts = set()
            fuelNexts = [-1] * numV
            while vs:
                fNow, vNow = -1, -1
                for v in vs:
                    if fuels[v] > fNow:
                        fNow, vNow = fuels[v], v
                nums[vNow] = num
                useds[vNow] = True
                vs.remove(vNow)

                fuel = fuels[vNow]
                for v2, wt in adjList[vNow]:
                    if useds[v2]: continue
                    if fuel >= wt:
                        if fuel-wt > fuels[v2]:
                            fuels[v2] = fuel-wt
                        vs.add(v2)
                    elif L >= wt:
                        if L-wt > fuelNexts[v2]:
                            fuelNexts[v2] = L-wt
                        vNexts.add(v2)

            vs = set([v for v in vNexts if not useds[v]])
            fuels = fuelNexts
            num += 1
        return nums


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

    numss = []
    for v in range(N):
        nums = Dijkstra(adjL, v)
        numss.append(nums)

    Q = int(input())
    anss = []
    for _ in range(Q):
        s, t = map(int, input().split())
        s, t = s-1, t-1
        if numss[s][t] == INF:
            anss.append(-1)
        else:
            anss.append(numss[s][t])

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


solve()

Submission status: Accepted

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

    def Dijkstra(adjList, vSt):
        numV = len(adjList)
        useds = [False] * numV
        numUsed = 0
        costs = [INF] * numV
        costs[vSt] = 0
        while True:
            cNow, vNow = INF, -1
            for v in range(numV):
                if useds[v]: continue
                if costs[v] < cNow:
                    cNow, vNow = costs[v], v
            useds[vNow] = True
            numUsed += 1
            if numUsed == numV: break
            for v2, wt in adjList[vNow]:
                c2 = cNow + wt
                if c2 < costs[v2]:
                    costs[v2] = c2
        return costs

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

    costss = [Dijkstra(adjL, vSt) for vSt in range(N)]

    adjL2 = [[] for _ in range(N)]
    for i, costs in enumerate(costss):
        for j, cost in enumerate(costs[i+1:], i+1):
            if cost <= L:
                adjL2[i].append((j, 1))
                adjL2[j].append((i, 1))

    costss = [Dijkstra(adjL2, vSt) for vSt in range(N)]

    Q = int(input())
    anss = []
    for _ in range(Q):
        s, t = map(int, input().split())
        s, t = s-1, t-1
        if costss[s][t] == INF:
            anss.append(-1)
        else:
            anss.append(costss[s][t]-1)

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


solve()

Submission status: Accepted

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

    def WarshallFloyd(adjList):
        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))

    D = WarshallFloyd(adjL)

    adjL2 = [[] for _ in range(N)]
    for i in range(N):
        for j in range(i+1, N):
            if D[i][j] <= L:
                adjL2[i].append((j, 1))
                adjL2[j].append((i, 1))

    D = WarshallFloyd(adjL2)

    Q = int(input())
    anss = []
    for _ in range(Q):
        s, t = map(int, input().split())
        s, t = s-1, t-1
        if D[s][t] == INF:
            anss.append(-1)
        else:
            anss.append(D[s][t]-1)

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


solve()

Submission status: Accepted

Solution code:
# 2019-11-19 10:28:31(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# import re
# import heapq
# import array
# from scipy.misc import comb # (default: exact=False)
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
import numpy as np 


def main():
    n, m, l = map(int, sys.stdin.readline().split())
    ABCQST = np.array(sys.stdin.read().split(), np.int64)
    ABC = ABCQST[:m * 3]
    A, B, C = ABC[::3], ABC[1::3], ABC[2::3]
    ST = ABCQST[m * 3 + 1:]
    S, T = ST[::2], ST[1::2]

    dist = csr_matrix((C, (A, B)), (n+1, n+1))
    min_dist = floyd_warshall(dist, directed=False)

    filling_times = np.full((n+1, n+1), np.inf)
    np.diagonal(filling_times, 0)
    filling_times[min_dist <= l] = 1

    min_filling_times = floyd_warshall(filling_times, directed=False)

    min_filling_times[min_filling_times == np.inf] = 0
    # 最後に-1する
    min_filling_times = min_filling_times.astype(int)

    res = min_filling_times[S, T] - 1
    print('\n'.join(res.astype(str)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,m,l=map(int,input().split())
d=[[10**18]*n for i in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split())
    if c<=l:
        d[a-1][b-1]=c
        d[b-1][a-1]=c
for i in range(n):
    d[i][i]=0
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])

for i in range(n):
    for j in range(n):
        if 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())
    s-=1
    t-=1
    print(d[s][t]-1 if d[s][t]-1<999999999999999999 else -1)

Submission status: Accepted

Solution code:
# import numpy as np
from scipy.sparse.csgraph import floyd_warshall
N, M, L = map(int, input().split())

INF = 10 ** 18
dist1 = [[INF] * N for _ in range(N)]
for i in range(N):
    dist1[i][i] = 0

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

dist1 = floyd_warshall(dist1)

dist2 = [[INF] * N for _ in range(N)]
for i in range(N):
    for j in range(N):
        if dist1[i][j] <= L:
            dist2[i][j] = 1

dist2 = floyd_warshall(dist2)

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

Submission status: Accepted

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

INF = 10 ** 18
dist1 = [[INF] * N for _ in range(N)]
for i in range(N):
    dist1[i][i] = 0

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

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

dist2 = [[INF] * N for _ in range(N)]
for i in range(N):
    for j in range(N):
        if dist1[i][j] <= L:
            dist2[i][j] = 1

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

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
 
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)]
 
graph = [[float('inf') for _ in range(n)] for _ in range(n)]
 
 
for a, b, c in abc:
    graph[a-1][b-1] = c 
    graph[b-1][a-1] = c
for i in range(n):
    graph[i][i] = 0
 
# print(graph)
 
def warshall_floyd(d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    return d
 
graph = warshall_floyd(graph)
 
for i in range(n):
    for j in range(n):
        if 0 < graph[i][j] <= l:
            graph[i][j] = 1
        if graph[i][j] > l:
            graph[i][j] = float('inf')
 
graph = warshall_floyd(graph)
 
for s, t in st:
    print(graph[s-1][t-1]-1 if graph[s-1][t-1] != float('inf') else -1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
input = sys.stdin.readline
from bisect import *
from collections import *
from heapq import *
import functools
import itertools
import math
INF = float('inf')
MOD = 10**9+7

def dijkstra(s, edges):
    dist = [INF] * len(edges)
    dist[s], h = 0, []
    heappush(h, (0, s))
    while (len(h)):
        dv, v = heappop(h)
        if dv > dist[v]:
            continue
        for u, cost in edges[v]:
            if dv + cost < dist[u]:
                dist[u] = dv + cost
                heappush(h, (dist[u], u))
    return dist

N, M, L = map(int, input().split())
es = [[INF] * N for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    es[a][b] = es[b][a] = c
for i in range(N):
    es[i][i] = 0
for k in range(N):
    for i in range(N):
        for j in range(N):
            tmp = es[i][k] + es[k][j]
            if tmp < es[i][j]:
                es[i][j] = tmp
es2 = [[] for i in range(N)]
for i in range(N-1):
    for j in range(i+1, N):
        if es[i][j] <= L:
            es2[i].append((j, 1))
            es2[j].append((i, 1))
dist = [dijkstra(i, es2) for i in range(N)]
Q = int(input())
for i in range(Q):
    s, t = map(lambda x: int(x)-1, input().split())
    ans = dist[s][t]
    if ans == INF:
        ans = 0
    print(ans-1)

Submission status: Accepted

Solution code:
import sys
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
readlines=sys.stdin.buffer.readlines

N,M,L=map(int,readline().split())
#print("N M L:",N,M,L)

root=[[10**10 for i in range(N+1)] for j in range(N+1)]
for i in range(M):
  A,B,C=map(int,readline().split())
  root[A][B],root[B][A]=C,C
  
Q=int(readline())
S,T=[0]*Q,[0]*Q
for i in range(Q):
  S[i],T[i]=map(int,readline().split())
#print("root:",root)
#print("S:",S)
#print("T:",T)

for k in range(1,N+1):
  for i in range(1,N+1):
    for j in range(1,N+1):
      root[i][j]=min(root[i][j],root[i][k]+root[k][j])
#print("root:",root)
for i in range(1,N+1):
  for j in range(1,N+1):
    if root[i][j]<=L:
      root[i][j]=1
    else:
      root[i][j]=10**10
#print("root(1):",root)

for k in range(1,N+1):
  for i in range(1,N+1):
    for j in range(1,N+1):
      if root[i][k]!=-1 and root[k][j]!=-1:
        root[i][j]=min(root[i][j],root[i][k]+root[k][j])
#print("root(2):",root)

for i in range(Q):
  print(root[S[i]][T[i]]-1 if root[S[i]][T[i]]<10**10 else -1)

Submission status: Accepted

Solution code:
import sys


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    wn, wm, wwl = list(map(int, input().rstrip('\n').split()))
    inf = 10 ** 13
    wl = [[inf] * wn for _ in range(wn)]
    for i in range(wn):
        wl[i][i] = 0

    for i in range(wm):
        wa, wb, wc = list(map(int, input().rstrip('\n').split()))
        wl[wa - 1][wb - 1] = wc
        wl[wb - 1][wa - 1] = wc

    for i in range(wn):
        for j in range(wn):
            for k in range(wn):
                wl[j][k] = min(wl[j][k], wl[j][i] + wl[i][k])

    nwl = [[inf] * wn for _ in range(wn)]
    for i in range(wn):
        for j in range(wn):
            if wl[i][j] <= wwl:
                nwl[i][j] = 1

    for i in range(wn):
        for j in range(wn):
            for k in range(wn):
                nwl[j][k] = min(nwl[j][k], nwl[j][i] + nwl[i][k])

    q = int(input().rstrip('\n'))
    for i in range(q):
        s, t = list(map(int, input().rstrip('\n').split()))
        print(nwl[s-1][t-1] - 1 if nwl[s-1][t-1] != inf else -1)


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

"""
def warshall_floyd(d):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] =min(d[i][j],d[i][k] + d[k][j])            
    return d
"""
N, M, L = map(int, input().split())

d = [[0 for i in range(N)] for i in range(N)]

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

d = floyd_warshall(d, directed = False)
S = [[0 for i in range(N)] for i in range(N)]


for i in range(N):
    for j in range(N):
        if d[i][j] <= L:
            S[i][j] = 1
            S[j][i] = 1
            
S = floyd_warshall(S, directed = False)

Q = int(input())

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

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import numpy as np

N, M, L = map(int, input().split())
inf = 10**9 + 1
dist = [[inf] * N for i in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    dist[A-1][B-1] = dist[B-1][A-1] = C

dist = floyd_warshall(dist, directed=False)
dist = np.where(dist <= L, 1, inf)
dist = floyd_warshall(dist, directed=False)
dist = np.where(dist < inf, dist-1, -1)

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

Submission status: Accepted

Solution code:
# ワ―シャルフロイドで解くよ
def main():
    import sys
    input = sys.stdin.readline  # 1行ごとの入力を繰り返し扱う場合の高速化
    N, M, L = map(int, input().split())
    # distanceを格納(未到達は無限遠として初期化)
    d = [[10 ** 12] * N for _ in range(N)]  
    # input-edges
    for i in range(M):
        a, b, c = map(int, input().split())
        if L >= c: # 距離がLより大きいのは無視
            d[a - 1][b - 1] = d[b - 1][a - 1] = c
    for i in range(N):
        d[i][i] = 0  # 自己ループ無
    
    # ワ―シャルフロイド法適用
    # 町間の最短距離を一度求める。
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] = min(d[i][k] + d[k][j], d[i][j])
    
    # 先ほど求めた町間の内、最短距離がL以下のものを距離1で結ぶ。
    edge = [[10 ** 12] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            if d[i][j] <= L:
                edge[i][j] = 1
    
    # もう一度ワ―シャルフロイド法適用
    for k in range(N):
        for i in range(N):
            for j in range(N):
                edge[i][j] = min(edge[i][k] + edge[k][j], edge[i][j])
    
    # input-query
    Q = int(input())
    for _ in range(Q):
        s, t = map(int, input().split())
        if edge[s - 1][t - 1] >= 10 ** 12:
            print(-1)
        else:
            print(edge[s - 1][t - 1] - 1)  # 最初に燃料Lがある分、マイナス1をする。
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, M, L = map(int, input().split())
INF = 10**12
dp = [[INF]*N for i in range(N)]
fp = [[INF]*N for i in range(N)]
for i in range(N):
  dp[i][i]=0
  fp[i][i]=0
k = [[0]*N for i in range(N)]
for i in range(M):
  a, b, c = map(int, input().split())
  dp[a-1][b-1] = c
  dp[b-1][a-1] = c

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

for j in range(N):
  for h in range(N):
    if dp[j][h]<=L:
      fp[j][h] = 1
for i in range(N):
  for j in range(N):
    for h in range(N):
      fp[j][h] = min(fp[j][h], fp[j][i]+fp[i][h])
Q = int(input())
for i in range(Q):
  s, t = map(int, input().split())
  s = s-1
  t = t-1
  if fp[s][t]==INF:
    print(-1)
  else:
    print(fp[s][t]-1)