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: Wrong Answer

Solution code:
import heapq

inf = float('INF')

def dijkstra(ad_lst, n, s, l):
    costs = [inf for i in range(n)]
    costs[s], Q = 0, []
    heapq.heappush(Q, [0, s])

    while(Q != []):
        acc, u = heapq.heappop(Q)
        for v, c in ad_lst[u].items():
            if c > l:
                continue
            to_cost = 0
            if acc + c > l:
                to_cost = 1
                c -= acc
            if costs[u] + to_cost < costs[v] and costs:
                heapq.heappush(Q, [acc + c, v])
                costs[v] = costs[u] + to_cost
    return costs

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

route = {i:{} for i in range(n)}
for _ in range(m):
    a,b,c = map(int, input().split())
    route[a-1][b-1] = route[b-1][a-1] = c

p_route = []
for i in range(n):
    p_route.append(dijkstra(route, n, i, l))

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

Submission status: Wrong Answer

Solution code:
from collections import Counter,defaultdict,deque
import sys,bisect,math,itertools,string,queue
from heapq import heappop, heappush
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]

n,m,l = inpl()
a = [0] * m
b = [0] * m
c = [0] * m
for i in range(m):
    a[i],b[i],c[i] = inpl()
q = inp()
s = [0] * q
t = [0] * q
for i in range(q):
    s[i],t[i] = inpl()
g = Graph()
for i in range(m):
    g.add_edge(a[i],b[i], c[i])
    g.add_edge(a[i],b[i], c[i])
for i in range(q):
    d = Dijkstra(g, s[i])
    xxx = d.shortest_path(t[i])
    ans = 0
    tmp = l
    for j in xxx:
        if tmp == l and tmp < j:
            print(-1)
            break
        if tmp - j >= 0:
            tmp -= j
        else:
            ans += 1
            tmp = l
    print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from itertools import accumulate
INF = float("inf")

# 無向グラフを仮定する。


class Graph(object):
    def __init__(self, N):
        self.N = N
        self.E = [[] for _ in range(N)]

    def add_edge(self, s, t, w=1):
        self.E[s].append([t, w])
        self.E[t].append([s, w])


def shortestPath(g: Graph, s: int, L: int):

    charge = [INF]*g.N
    charge[s] = 0

    rest = [INF]*g.N            # 現在の走行距離
    rest[s] = 0

    Q = []
    heapq.heappush(Q, s)

    while len(Q) > 0:
        u = heapq.heappop(Q)
        for v, w in g.E[u]:
            if rest[u]+w > L:
                c, r = (charge[u]+1, w)
            else:
                c, r = (charge[u], rest[u]+w)
            if charge[v] > c or (charge[v] == c and rest[v] > r):
                rest[v] = r
                charge[v] = c
                heapq.heappush(Q, v)

    return charge, rest


def solve(N: int,
          M: int,
          L: int,
          A: "List[int]",
          B: "List[int]",
          C: "List[int]",
          Q: int,
          s: "List[int]",
          t: "List[int]"):
    g = Graph(N)
    for i in range(M):
        if C[i] < L:
            g.add_edge(A[i]-1, B[i]-1, C[i])
    # dist = Warshall_Floyd(g)
    # print(*dist, sep="\n")

    charges = []
    rests = []
    for i in range(N):
        charge, rest = shortestPath(g, i, L)
        charges.append(charge)
        rests.append(rest)
    # for c, r in zip(charges[0], rests[0]):
    #     print(c, r)
    # return

    for i in range(Q):
        charge, rest = charges[s[i]-1], rests[s[i]-1]
        if charge[t[i]-1] == INF:
            print(-1)
        else:
            print(charge[t[i]-1])

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    L = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    Q = int(next(tokens))  # type: int
    s = [int()] * (Q)  # type: "List[int]"
    t = [int()] * (Q)  # type: "List[int]"
    for i in range(Q):
        s[i] = int(next(tokens))
        t[i] = int(next(tokens))
    solve(N, M, L, A, B, C, Q, s, t)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

n,m,l = map(int,input().split())
dp = [[[-1,-1]] * n for _ in range(n)]
for i in range(n):
    dp[i][i] = [0,[l]]

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


for k in range(n):
    for i in range(n):
        for j in range(n):
            if dp[i][k] != [-1,-1] and dp[k][j] != [-1,-1]:
                if dp[i][j] == [-1,-1]:
                    if dp[i][k][1][-1] + dp[k][j][1][0] > l:
                        dp[i][j] = (dp[i][k][0]+dp[k][j][0]+1,dp[i][k][1] + dp[k][j][1])
                    else:
                        dp[i][j] = (dp[i][k][0]+dp[k][j][0],dp[i][k][1] + dp[k][j][1])
                else:
                    if dp[i][k][1][-1] + dp[k][j][1][0] > l:
                        if dp[i][k][0]+dp[k][j][0]+1 < dp[i][j][0] or (dp[i][k][0]+dp[k][j][0]+1 == dp[i][j][0] and dp[k][j][1][-1] < dp[i][j][1][-1]):
                            dp[i][j] = (dp[i][k][0]+dp[k][j][0]+1,dp[i][k][1] + dp[k][j][1])
                    else:
                        if dp[i][k][0]+dp[k][j][0] < dp[i][j][0] or (dp[i][k][0]+dp[k][j][0] == dp[i][j][0] and dp[i][k][1][-1] + dp[k][j][1][-1] < dp[i][j][1][-1]):
                            dp[i][j] = (dp[i][k][0]+dp[k][j][0],dp[i][k][1] + dp[k][j][1])


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

Submission status: Wrong Answer

Solution code:
def dijkstra(s,n,w,cost):
    #始点sから各頂点への最短距離
    #n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0
    
    while True:
        v = -1
        #まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
               v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
               break
        used[v] = True
               
        for j in range(n):
               d[j] = min(d[j],d[v]+cost[v][j])
    return d


n,w,l = map(int,input().split()) #n:頂点数　w:辺の数
cost = [[float("inf") for i in range(n)] for i in range(n)] 
for i in range(w):
    x,y,z = map(int,input().split())
    cost[x-1][y-1] = z
    cost[y-1][x-1] = z

Q = int(input())
for j in range(Q):
    p,q = map(int,input().split())
    tmp = dijkstra(p-1,n,w,cost)[q-1]
    print(-1 if str(tmp)=="inf" else (tmp // l))

Submission status: Wrong Answer

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


class Node(object):

  def __init__(self, idx):
    self.idx = idx
    self.fixed = False
    self.supply = 300
    self.remain = 0
    self.edges = []

  def __gt__(self, obj):
    return self.supply > obj.supply or self.remain < obj.supply

  def __lt__(self, obj):
    return self.supply < obj.supply or self.remain > obj.supply

  def __hash__(self):
    return self.idx

  # def __str__(self):
  #  return (f'{self.idx}: {self.supply}/{self.remain} - ' +
  #          ','.join(f'{e.idx}({d})' for e, d in self.edges))


def main():
  n, m, tank = map(int, input().split())
  nodes = [Node(i) for i in range(n + 1)]

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

  queries = [list(map(int, input().split())) for _ in range(int(input()))]
  results = [[None] * len(nodes) for _ in range(len(nodes) - 1)]

  for start in range(len(nodes) - 1):
    for n in nodes:
      n.fixed = False
      n.supply = 300
      n.remain = 0

    nodes[start].supply = 0
    nodes[start].remain = tank

    while True:
      node = min([n for n in nodes if not n.fixed], key=lambda n: (n.supply, -n.remain))
      node.fixed = True

      if node.idx == len(nodes) - 1:
        break

      for e, d in node.edges:
        if e.fixed or d > tank:
          continue

        if d > node.remain:
          remain = tank - d
          supply = node.supply + 1
        else:
          remain = node.remain - d
          supply = node.supply

        if e.supply > supply or e.remain < remain:
          e.supply = supply
          e.remain = remain

    for end in range(len(nodes)):
      results[start][end] = nodes[end].supply

  for start, end in queries:
    print(results[start - 1][end - 1])


if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
import sys

n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()
INF = 10 ** 18

dists = [[(INF, INF)] * n for _ in range(n)]

for i in range(n):
    dists[i][i] = (0, 0)

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if c > l:
        continue
    dists[a][b] = (0, c)
    dists[b][a] = (0, c)

for k in range(n):
    dk = dists[k]
    for i in range(n):
        di = dists[i]
        for j in range(n):
            cik, uik = di[k]
            ckj, ukj = dk[j]
            if ckj == 0 and uik + ukj <= l:
                new_dist = (cik, uik + ukj)
            else:
                new_dist = (cik + ckj + 1, ukj)
            if di[j] > new_dist:
                di[j] = new_dist
# print(*dists, sep='\n')

buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    dist, _ = dists[s - 1][t - 1]
    buf.append(-1 if dist == INF else dist)

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

Submission status: Wrong Answer

Solution code:
import sys

n, m, l = list(map(int, input().split()))
lines = sys.stdin.readlines()
INF = 10 ** 18

dists = [[(INF, INF)] * n for _ in range(n)]

for i in range(n):
    dists[i][i] = (0, 0)

for line in lines[:m]:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    if c > l:
        continue
    dists[a][b] = (0, c)
    dists[b][a] = (0, c)

for k in range(n):
    dk = dists[k]
    for i in range(n):
        di = dists[i]
        for j in range(n):
            cik, uik = di[k]
            ckj, ukj = dk[j]
            if ckj == 0 and uik + ukj <= l:
                new_dist = (cik, uik + ukj)
            else:
                new_dist = (cik + ckj + 1, ukj)
            if di[j] > new_dist:
                di[j] = new_dist
print(*dists, sep='\n')

buf = []

for line in lines[m + 1:]:
    s, t = map(int, line.split())
    dist, _ = dists[s - 1][t - 1]
    buf.append(-1 if dist == INF else dist)

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

Submission status: Wrong Answer

Solution code:
n,m,l=map(int,input().split())
f=[[2*[float("inf")]for _ in range(n)]for _ in range(n)]
for i in range(n):f[i][i][1]=0

for i in range(m):
  a,b,c=map(int,input().split())
  if c>l:continue
  f[a-1][b-1][1]=f[b-1][a-1][1]=1
  f[a-1][b-1][0]=f[b-1][a-1][0]=c

for i in range(n):
  for j in range(n):
    for k in range(n):
      a=f[i][j][1]
      b=f[i][k][1]+f[k][j][1]
      if f[i][k][0]+f[j][k][0]<=l:b-=1
      if a>b:
        f[i][j][1]=b
        f[i][j][0]=f[k][j][0]
      elif a==b:
        if f[k][j][0]<f[i][j][0]:f[i][j][0]=f[k][j][0]

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

Submission status: Wrong Answer

Solution code:
from collections import deque,defaultdict

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

li=[[inf]*n for _ in range(n)]
ll=defaultdict(list)

for i in range(n):
  li[i][i]=0

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

q=int(input())

for i in range(q):
  s,t=map(int,input().split())
  ans=0
  gas=l
  qu=deque()
  vi=set()
  qu.append([s-1,l,0])
  while qu:
    now=qu.popleft()
    if now[0]==t-1:
      print(now[2])
      break
    else:
      vi.add(now[0])
      kouho=ll[now[0]]
      for i in kouho:
        if i in vi:
          continue
        elif l-li[now[0]][i]<0:
          continue
        elif now[1]-li[now[0]][i]>=0:
          qu.append([i,now[1]-li[now[0]][i],now[2]])
        else:
          qu.append([i,l-li[now[0]][i],now[2]+1])
  else:
    print(-1)

Submission status: Wrong Answer

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


def main():
    mod = 10**10
    N, M, L = map(int, input().split())
    dist = [[float('inf') for _ in range(N+1)] for _ in range(N+1)]
    ans = [[float('inf') for _ in range(N+1)] for _ in range(N+1)]
    for i in range(1, N+1):
        dist[i][i] = 0
        ans[i][i] = 1
    for _ in range(M):
        a, b, c = map(int, input().split())
        if c <= L:
            dist[a][b] = c
            dist[b][a] = c

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

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, M, L, ABC, Q, ST):

    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = c
        g[b][a] = c
    
    dd = defaultdict(lambda: -1)
    def f(s, t):
        if s > t:
            t, s = s, t
        if (s, t) in dd:
            return dd[(s, t)]
        q = [(0, s)]
        done = set([s])
        d = 0
        while q:
            d, u = heapq.heappop(q)
            qq = [(-L, u)]
            cand = set()
            while qq:
                rem, uu = heapq.heappop(qq)
                rem = -rem
                for vv in g[uu]:
                    if rem-g[uu][vv] < 0:
                        continue
                    if vv in done:
                        continue
                    qq.append((-(rem-g[uu][vv]), vv))
                    cand.add(vv)
            
            done |= cand
            for v in cand:
                dd[(s, v)] = d
                heapq.heappush(q, (d+1, v))

        for i in range(1, N+1):
            if i not in done:
                dd[(s, i)] = -1

        return dd[(s, t)]

    for s, t in ST:
        print(f(s, t))



def main():
    N, M, L = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    Q = read_int()
    ST = [read_int_n() for _ in range(Q)]
    (slv(N, M, L, ABC, Q, ST))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
input=open(0).readline
n,m,l=map(int,input().split())
d=[[[10**18]*2for _ in range(n)]for _ in range(n)]
for _ in range(m):
    a,b,c=map(int,input().split())
    d[a-1][b-1]=[0,c]
    d[b-1][a-1]=[0,c]
for k in range(n):
    for i in range(n):
        for j in range(n):
            t,u=d[i][k][:],d[k][j]
            t[0]+=u[0]
            t[1]+=u[1]
            if t[1]>l:
                t[0]+=1
                t[1]-=u[1]
            d[i][j]=min(d[i][j],t)
for _ in range(int(input())):
    s,t=map(int,input().split())
    print(d[s-1][t-1][0])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
from collections import deque
def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math

n, m, l = getList()

INF = 10 ** 10
vers = [[INF for j in range(n)] for i in range(n)]
ver_dis = [[INF for j in range(n)] for i in range(n)]
ver_res = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
    vers[i][i] = 0
    ver_dis[i][i] = 0
    ver_res[i][i] = l

for _ in range(m):
    a, b, c = getList()
    if c <= l:
        vers[a-1][b-1] = c
        vers[b - 1][a - 1] = c
        ver_dis[a - 1][b - 1] = 0
        ver_dis[b - 1][a - 1] = 0
        ver_res[a - 1][b - 1] = l-c
        ver_res[b - 1][a - 1] = l-c

# print(vers)
def warshall_floyd(d, d2, d3, mxfuel):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                # 更新1: 少ない階数
                # 更新2: 残る燃料
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
                if d[i][j] <= mxfuel:
                    d2[i][j] = 0
                    d3[i][j] = mxfuel - d[i][j]
                elif d2[i][k] != INF:
                    if d2[i][j] > d2[i][k] + d2[k][j] + 1:
                        # ノンストップ
                        if d3[i][k] - d[k][j] >= 0:
                            # print("NONSTOP, ", i, j, k, d3)
                            # print(d2)
                            d3[i][j] = d3[i][k] - d[k][j]
                            d2[i][j] = d2[i][k]


                        else:
                            # 1回使う
                            d3[i][j] = mxfuel - d[k][j]
                            d2[i][j] = d2[i][k] + 1
                    # 燃料の残り争い
                    elif d2[i][j] == d2[i][k] + d2[k][j] + 1:
                        # 回り道したほうが潤沢なら
                        if d3[i][j] < d3[i][k] - d[k][j]:
                            d3[i][j] = d3[i][k] - d[k][j]

        # print(d)
        # print(d2)
        # print(d3)

    return d, d2

re_ves, re_ves2  = warshall_floyd(vers, ver_dis, ver_res, l)
# print(re_ves)
# print(re_ves2)
Q = getN()
for _ in range(Q):
    a, b = getList()
    a,b = min(a,b), max(a,b)
    ans = (re_ves2[a-1][b-1])
    if ans == INF:
        print(-1)
    else:
        print(ans)
"""
4 4 5
1 2 3
2 3 3
3 4 3
2 4 8

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

5 4 4
1 2 2
2 3 2
3 4 3
4 5 2
"""

Submission status: Wrong Answer

Solution code:
import heapq as hq

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

out_link = {i: set() for i in range(N)}
min_length = {(i, j): -1 for i in range(N) for j in range(N)}


for _ in range(M):
    A, B, C = map(int, input().split())
    if C > L:
        continue

    A -= 1
    B -= 1
    out_link[A].add((B, C))
    out_link[B].add((A, C))


def should_supply(now_cost, next_cost):
    if now_cost % L == 0:
        return False

    return (now_cost - 1) // L != (next_cost - 1) // L


def search(S):
    already = set()
    H = [(0, S)]
    while H:
        c, p = hq.heappop(H)
        if p in already:
            continue

        already.add(p)
        min_length[(S, p)] = (c - 1) // L
        min_length[(p, S)] = (c - 1) // L

        for q, add_cost in out_link[p]:
            if q in already:
                continue
            next_cost = c + add_cost
            if should_supply(c, next_cost):
                next_cost = (c // L + 1) * L + add_cost

            hq.heappush(H, (next_cost, q))


calc = 0
calced_s = set()
Q = int(input())
ans = ""
for _ in range(Q):
    s, t = map(int, input().split())
    s -= 1
    t -= 1
    if s not in calced_s:
        search(s)
        calced_s.add(s)
        calc += 1
    res = min_length[(s, t)]
    ans += str(res) + "\n"

print(ans)
print(calc)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n, m, l = [ int(v) for v in input().split() ]
charge_list = [ [ [10**5, 0] for i in range(n) ] for j in range(n) ]
distance_list = [ [ -1 for i in range(n) ] for j in range(n) ]

for i in range(m): 
    a, b, d = [ int(v) for v in input().split() ]
    a, b = a-1, b-1
    if d <= l:
        charge_list[a][b] = [0, l-d]
        charge_list[b][a] = [0, l-d]
        distance_list[a][b] = d
        distance_list[b][a] = d

for k in range(n):
    for i in range(n):
        for j in range(n):
            a = charge_list[i][k][0] + charge_list[k][j][0] 
            if charge_list[i][k][1] + charge_list[k][j][1] >= l:
                b = 0
                c = charge_list[i][k][1] + charge_list[k][j][1] - l
            else:
                b = 1
                c = 0
            if charge_list[i][j][0] > a+b:
                charge_list[i][j][0] = a+b
                charge_list[i][j][1] = c
            elif charge_list[i][j][0] == a+b and charge_list[i][j][1] > c:
                charge_list[i][j][1] = c

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

Submission status: Wrong Answer

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


def main():
    mod = 10**10
    N, M, L = map(int, input().split())
    dist = [[float('inf') for _ in range(N+1)] for _ in range(N+1)]
    ans = [[float('inf') for _ in range(N+1)] for _ in range(N+1)]
    for i in range(1, N+1):
        dist[i][i] = 0
        ans[i][i] = 0
    for _ in range(M):
        a, b, c = map(int, input().split())
        if c <= L:
            dist[a][b] = c
            dist[b][a] = c

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

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
N, M, L = map(int, input().split())
d = [[float("inf")] * (N + 1) for _ in range(N + 1)]
prev = [[-1] * (N + 1) for _ in range(N + 1)]
for _ in range(M):
  u, v, c = map(int, input().split())
  d[u][v] = c
  d[v][u] = c
Q = int(input())
for k in range(1, N + 1):
  for i in range(1, N + 1):
    for j in range(1, N + 1):
      if d[i][j] > d[i][k] + d[k][j]:
        d[i][j] = d[i][k] + d[k][j]
        prev[i][j] = prev[i][k]
        if prev[i][j] == -1:
          prev[i][j] = k
#print(d)
#print(prev)
def check(s, t, l):
  if prev[s][t] == -1:
    if d[s][t] <= l:
      return 0
    elif d[s][t] <= L:
      return 1
    else:
      return -1
  else:
    ns = prev[s][t]
    nl = L
    temp2 = 0
    if d[s][ns] <= l:
      nl = l - d[s][ns]
    elif d[s][ns] <= L:
      nl = L - d[s][ns]
      temp2 += 1
    else:
      #print(s, t, l, ns, d[s][ns])
      return -1
    temp = check(ns, t, nl)
    if temp == -1:
      return -1
    return temp + temp2

for _ in range(Q):
  s, t = map(int, input().split())
  print(check(s, t, L))

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import floyd_warshall

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

d=[[float('inf')]*n for i in range(n)]
for i in range(n):
    d[i][i]=0
for i in l:
    d[i[0]-1][i[1]-1]=i[2]
    d[i[1]-1][i[0]-1]=i[2]
fw=floyd_warshall(d)

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

    if dist==float('inf'):
        print(-1)
        continue
    ans=int(dist)//L
    if int(dist)%L==0:
        ans-=1
    print(ans)

Submission status: Wrong Answer

Solution code:
import collections
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

N,M,L =  list(map(int,input().split(" ")))
graph = [[0 for _ in range(N + 1) ] for _ in range(N + 1)]
for i in range(M):
    a,b,c = list(map(int, input().split(" ")))
    if c <= L:
        graph[a][b] = c
        graph[b][a] = c

sp,pred = shortest_path(np.array(graph) , return_predecessors=True)

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


Q = int(input())
Qs = []
for _ in range(Q):
    s,t  = list(map(int, input().split(" ")))
    Qs.append((s,t))

for q in Qs:
    s,t = q
    ans = -1
    path = get_path(s, t, pred)
    l = len(path)
    if l == 0:
        print(-1)
        exit()

    life = L
    ans = 0
    for i in range(l - 1):
        s ,t= path[i],path[i+1]
        if life - graph[s][t] < 0:
            ans +=1
            life = L
        life -= sp[s][t]
    print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
#from scipy.sparse.csgraph import csgraph_from_dense
from scipy.sparse.csgraph import dijkstra
 
import sys
input = sys.stdin.readline
def main():
  [N,M,L]=list(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)]
  
  if M==0:
    for _ in range(Q):
      print(-1)
      exit()
  
  g=np.zeros((N,N))
  for road in abc:
    if road[2]<=L:
      g[road[0]-1][road[1]-1]=road[2]
      g[road[1]-1][road[0]-1]=road[2]
  
  for item in st:
    #csg=csgraph_from_dense(g,null_value=0) #重み0==ノードなし，とする
    #print(item)
    (d,path) = dijkstra(g,
                 indices = item[0]-1,
                 return_predecessors=True)
    #print(d,path)
    
    shouhi=[]
    s=item[1]-1
    while s!=-9999:
      shouhi.append(d[s])
      s=path[s]
    #shouhi=[shouhi[-i-1]-shouhi[-i] for i in range(1,len(shouhi))]
    #print(shouhi)
    if shouhi==[]:
      print(-1)
      continue
    
    ans=0
    lim=L
    for i in range(1,len(shouhi)):
      temporary_shouhi=shouhi[-i-1]-shouhi[-i]
      
      if lim<temporary_shouhi:
        lim=L
        ans=ans+1
        lim=lim-temporary_shouhi
      else:
        lim=lim-temporary_shouhi
    print(ans)

if __name__ == '__main__':
    main()