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:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    dis_table = [[10 ** 12 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        dis_table[i][i] = 0

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            dis_table[a][b] = c
            dis_table[b][a] = c

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

    #print(dis_table)

    nt = [[10 ** 12 for _ in range(N)] for _ in range(N)]


    for i in range(N):
        for j in range(N):
            if dis_table[i][j] <= L:
                nt[i][j] = 1

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

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

    #print(nt)


    q = iip(False)
    ans = []
    for i in range(q):
        a, b = iip()
        c = nt[a-1][b-1]
        ans.append(c)


    split_print_enter(ans)


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    edge = {}
    for i in range(N):
        edge[i] = []

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            edge[a].append((b, c))
            edge[b].append((a, c))

    ans_table = []
    for start_node in range(N):
        dis = [-1 for i in range(N)]
        fix = [0 for i in range(N)]
        dis[start_node] = 0

        q = [] # 距離を格納する
        heapq.heapify(q)

        d = {0:[start_node]} # 距離に対応したノードを格納する
        q.append(0)

        #print(ans_table)
        while q:
            cd = heapq.heappop(q)
            nodes = d[cd]
            nokori = L - cd % L

            for node in nodes:
                fix[node] = 1

            for node in nodes:
                for root in edge[node]:
                    nn = root[0]
                    rg = root[1]

                    if fix[nn]:
                        continue #確定済みのノードなら飛ばす

                    d_old = dis[nn]

                    if nokori >= rg:
                        d_new = cd + rg
                    else:
                        d_new = (cd // L + 1) * L + rg

                    if d_old == -1 or d_old > d_new:
                        dis[nn] = d_new
                        if not d_new in d:
                            d[d_new] = [nn]
                        else:
                            d[d_new].append(nn)
                        q.append(d_new)

        ans_table.append(dis)

    Q = iip(False)
    ans = []
    for i in range(Q):
        a, b = iip()
        a -=1
        b -=1
        c = ans_table[a][b]

        if c == 0:
            c = 0
        elif c == -1:
            c = -1
        elif c % L == 0:
            c = (c-1) // L
        else:
            c = c // L
        ans.append(c)

    split_print_enter(ans)



#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    edge = {}
    for i in range(N):
        edge[i] = []

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            edge[a].append((b, c))
            edge[b].append((a, c))

    Q = iip(False)
    st = []
    for i in range(Q):
        a, b = iip()
        st.append((a-1, b-1))

    dp = [[-1 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0
        for j in range(N):
            if j < i:
                dp[i][j] = -2


    for start_node in range(N):
        q = deque()
        q.append(start_node)

        #print(ans_table)
        while q:
            cn = q.pop()

            for root in edge[cn]:
                nn = root[0]
                rg = root[1]
                d_old = dp[start_node][nn]
                if d_old == -2:
                    continue

                cd = dp[start_node][cn]
                nokori = L - cd % L
                if nokori >= rg:
                    d_new = cd + rg
                else:
                    d_new = (cd // L + 1) * L + rg

                if d_old == -1 or d_old > d_new:
                    dp[start_node][nn] = d_new
                    q.append(nn)

        #print("")
        #for i in dp:
        #    print(i)


    #print(ans_table)
    ans = []
    for aa, bb in st:
        a, b = (min(aa, bb), max(aa, bb))
        c = dp[a][b]
        if c == -1:
            ans.append(-1)
        else:
            if c == 0:
                c = 0
            elif c % L == 0:
                c = c // L -1
            else:
                c = c // L
            ans.append(c)

    split_print_enter(ans)


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    edge = {}
    for i in range(N):
        edge[i] = []

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            edge[a].append((b, c))
            edge[b].append((a, c))

    Q = iip(False)
    st = []
    for i in range(Q):
        a, b = iip()
        st.append((a-1, b-1))

    dp = [[False for _ in range(N)] for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0

    for start_node in range(N):
        q = deque()
        q.append(start_node)

        #print(ans_table)
        while q:
            cn = q.pop()

            for root in edge[cn]:
                nn = root[0]
                rg = root[1]
                d_old = dp[start_node][nn]

                cd = dp[start_node][cn]
                nokori = L - cd % L
                if nokori >= rg:
                    d_new = cd + rg
                else:
                    d_new = (cd // L + 1)*L + rg

                if d_old is False or d_old > d_new:
                    dp[start_node][nn] = d_new
                    dp[nn][start_node] = d_new
                    q.append(nn)


    #print(ans_table)
    ans = []
    for a, b in st:
        c = dp[a][b]
        if c is False:
            ans.append(-1)
        else:
            if c == 0:
                c = 0
            elif c % L == 0:
                c = c // L -1
            else:
                c = c // L
            ans.append(c)

    split_print_enter(ans)


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, M, L = iip()

    edge = {}
    for i in range(N):
        edge[i] = []

    for i in range(M):
        a, b, c = iip()
        a -= 1
        b -= 1
        if c <= L:
            edge[a].append((b, c))
            edge[b].append((a, c))

    Q = iip(False)
    st = []
    for i in range(Q):
        a, b = iip()
        st.append((a-1, b-1))

    ans_table = []

    def solve2(start_node):
        q = deque()
        q.append(start_node)
        dp = [False for i in range(N)]
        dp[start_node] = 0

        #print(ans_table)
        while q:
            cn = q.pop()
            for j, hoge in enumerate(ans_table):
                dp[j] = hoge[start_node]

            for root in edge[cn]:
                nn = root[0]
                rg = root[1]
                d_old = dp[nn]

                cd = dp[cn]
                nokori = L - cd % L
                if nokori >= rg:
                    d_new = cd + rg
                else:
                    d_new = (cd // L + 1)*L + rg

                if d_old is False or d_old > d_new:
                    dp[nn] = d_new
                    q.append(nn)
        return [False if i is False else max(0, (i-1)) // L for i in dp]

    for i in range(N):
        ans_table.append(solve2(i))

    #print(ans_table)
    ans = []
    for a, b in st:
        c = ans_table[a][b]
        if c is False:
            ans.append(-1)
        else:
            ans.append(c)

    split_print_enter(ans)


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    def wf(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

    n,m,l = map(int,input().split())
    d = [[float("inf")]*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
    for i in range(n):
        d[i][i] = 0
    wf(d)
    for i in range(n):
        for j in range(n):
            if d[i][j]<=l:
                d[i][j]=1
            else:
                d[i][j]=0
    wf(d)
    for i in range(n):
        d[i][i] = 0

    q=int(input())
    ab=[list(map(int,input().split())) for _ in range(q)]
    for i in range(q):
        ans=d[ab[i][0]-1][ab[i][1]-1]
        if ans==float("inf"):
            print(-1)
        else:
            print(ans-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    def wf(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

    n,m,l = map(int,input().split())
    d = [[float("inf")]*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
    for i in range(n):
        d[i][i] = 0
    wf(d)
    for i in range(n):
        for j in range(n):
            if i==j:
                continue
            else:
                if d[i][j]<=l:
                    d[i][j]=1
    wf(d)
    for i in range(n):
        d[i][i] = 0

    q=int(input())
    ab=[list(map(int,input().split())) for _ in range(q)]
    for i in range(q):
        ans=d[ab[i][0]-1][ab[i][1]-1]
        if ans==float("inf"):
            print(-1)
        else:
            print(ans-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

inf = float('INF')
def bfs(graph, start, goal, n, l):
    queue = deque([])
    queue.append([start, 0, l])
    costs = [inf] * (n+1)
    residual = [0] * (n+1)
    costs[start] = True
    residual[start] = l

    while queue:
        parent, cnt, res = queue.popleft()
        if parent not in graph:
            continue
        for child, dist in graph[parent].items():
            cost = cnt + (1 if res < dist else 0)
            resi = (l - dist) if res < dist else (res - dist)
            if costs[child] <= cost and residual[child] >= resi:
                continue
            #print(child, parent, cost, )
            queue.append([child, cost, resi])
            if costs[child] > cost:
                costs[child] = cost
            if residual[child] < resi:
                residual[child] = resi
    # print(costs)
    # print(residual)
    return costs[goal] if costs[goal] != inf else -1


n,m,l = map(int, input().split())
graph = {}
# [0 for i in range(n)] for j in range(n)]

for _ in range(m):
    a,b,c = map(int, input().split())
    # a -= 1
    # b -= 1
    if c > l:
        continue
    if a not in graph:
        graph[a] = {}
    if b not in graph:
        graph[b] = {}
    graph[a][b] = graph[b][a] = c

q = int(input())
for _ in range(q):
    s,t = map(int, input().split())
    print(bfs(graph, s, t, n, l))

Submission status: Wrong Answer

Solution code:
from collections import deque

inf = float('INF')
def bfs(graph, start, goal, n, l):
    queue = deque([])
    queue.append([start, 0, l])
    costs = [inf] * (n+1)
    residual = [0] * (n+1)
    costs[start] = True
    residual[start] = l

    while queue:
        parent, cnt, res = queue.popleft()
        if parent not in graph:
            continue
        for child, dist in graph[parent].items():
            cost = cnt + (1 if res < dist else 0)
            resi = (l - dist) if res < dist else (res - dist)
            if costs[child] <= cost and residual[child] >= resi:
                continue
            #print(child, parent, cost, )
            queue.append([child, cost, resi])
            costs[child] = cost
            residual[child] = resi
    #print(costs)
    #print(residual)
    return costs[goal] if costs[goal] != inf else -1


n,m,l = map(int, input().split())
graph = {}
# [0 for i in range(n)] for j in range(n)]

for _ in range(m):
    a,b,c = map(int, input().split())
    # a -= 1
    # b -= 1
    if c > l:
        continue
    if a not in graph:
        graph[a] = {}
    if b not in graph:
        graph[b] = {}
    graph[a][b] = graph[b][a] = c

q = int(input())
for _ in range(q):
    s,t = map(int, input().split())
    print(bfs(graph, s, t, n, l))

Submission status: Wrong Answer

Solution code:
def main():
    def wf(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

    n,m,l = map(int,input().split())
    d = [[float("inf")]*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
    for i in range(n):
        d[i][i] = 0
    wf(d)
    for i in range(n):
        for j in range(n):
            if i==j:
                continue
            else:
                if d[i][j]<=l:
                    d[i][j]=1
    wf(d)
    for i in range(n):
        d[i][i] = 0

    q=int(input())
    ab=[list(map(int,input().split())) for _ in range(q)]
    for i in range(q):
        ans=d[ab[i][0]-1][ab[i][1]-1]-1
        if ans==float("inf"):
            print(-1)
        else:
            print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self,s):

        import heapq
        que=[]
        D=[(10**15,L)] * self.V
        D[s]=(0,0)
        heapq.heappush(que,((0,0),s))

        while len(que)!=0:
            cost,v=heapq.heappop(que)
            a,b=cost
            c,d=D[v]

            if a>c:
                continue
            elif a==c and b>d:
                continue

            for i in range(len(self.G[v])):
                e=self.G[v][i]
                a,b=D[e.to]
                nokori=L-cost[1]
                if nokori>=e.cost:
                    c,d=cost[0],cost[1]+e.cost
                else:
                    c,d=cost[0]+1,e.cost
                if a>c or (a==c and b>d):
                    D[e.to]=(c,d)
                    heapq.heappush(que,(D[e.to],e.to))

        return D

N,M,L=map(int,input().split())
city=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    if L>=c:
        city.add(a-1,b-1,c)
        city.add(b-1,a-1,c)

ans=[city.shortest_path(i) for i in range(0,N)]
exit()
p=[]

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

for i in range(0,Q):
    print(p[i])