Problem:


Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(10**10)

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    # print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    # print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    # rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * 2501

    print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * 2501

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * 2501
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * 2501

    print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * 2501

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * 2501
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next in graph[node]:
            dfs(next)

    dfs(0)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next in rev_graph[node]:
            rdfs(next)

    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0
    #
    # # bellman-ford
    # updated = True
    # while updated:
    #     updated = False
    #     for i in range(m):
    #         a, b, c = edges[i]
    #         if not valid[a]:
    #             continue
    #         if not valid[b]:
    #             continue
    #
    #         new_cost = scores[a] + c
    #         if new_cost < scores[b]:
    #             updated = True
    #             scores[b] = new_cost
    #
    #     loop += 1
    #     if loop > n:
    #         print(-1)
    #         return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next in graph[node]:
            dfs(next)

    dfs(0)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next in rev_graph[node]:
            rdfs(next)

    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachabel_from_start = [False] * n

    def dfs(node):
        if reachabel_from_start[node]:
            return
        reachabel_from_start[node] = True
        for next in graph[node]:
            dfs(next)

    dfs(0)

    reachabel_to_end = [False] * n

    def rdfs(node):
        if reachabel_to_end[node]:
            return
        reachabel_to_end[node] = True
        for next in rev_graph[node]:
            rdfs(next)

    rdfs(n-1)

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0
    # print(reachabelFromStart)
    # print(reachabelToEnd)
    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if reachabel_from_start[a] and reachabel_to_end[a] and reachabel_from_start[b] and reachabel_to_end[b]:
                new_cost = scores[a] + c
                if new_cost < scores[b]:
                    updated = True
                    scores[b] = new_cost
        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)
    coins = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        c = -(c-p)
        edges.append((a,b,c))
        graph[a].append(b)
        rev_graph[b].append(a)

    # pick up nodes on goal path
    reachabelFromStart = [False] * n

    def dfs(node):
        if reachabelFromStart[node]:
            return
        reachabelFromStart[node] = True
        for next in graph[node]:
            dfs(next)

    dfs(0)

    reachabelToEnd = [False] * n
    def rdfs(node):
        if reachabelToEnd[node]:
            return
        reachabelToEnd[node] = True
        for next in rev_graph[node]:
            rdfs(next)

    rdfs(n-1)

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0
    # print(reachabelFromStart)
    # print(reachabelToEnd)
    # bellman-ford
    while True:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if reachabelFromStart[a] and reachabelToEnd[a] and reachabelFromStart[b] and reachabelToEnd[b]:
                new_cost = scores[a] + c
                if new_cost < scores[b]:
                    updated = True
                    scores[b] = new_cost
        loop += 1
        if loop > n:
            if updated:
                print(-1)
                break
            else:
                print(max(0,-scores[-1]))
                break


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import collections
from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import bellman_ford

N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
G = lil_matrix((N + 1, N + 1))
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G[a, b] = P - c

dist_matrix = bellman_ford(G, directed=True, indices=1)
try:
    print(max(-int(dist_matrix[-1]), 0))
except:
    print(-1)

Submission status: Runtime Error

Solution code:
INFINITY = float("inf")

N, M, P = [int(e) for e in input().split()]
Es = [None] * M

for i in range(M):
    Es[i] = ([int(e) for e in input().split()])
    Es[i][2] = P - Es[i][2]

d = [INFINITY] * (M + 1)
d[1] = 0

for _ in range(M):
    for e in Es:
        u, v, w = e
        dd = d[u] + w
        if dd < d[v]:
            d[v] = dd

circle_exists = False

for e in Es:
    u, v, w = e

    if v != N:
        continue

    if d[u] + w < d[v]:
        circle_exists = True
        break


if circle_exists:
    print(-1)
else:
    print(max(0, -d[N]))

Submission status: Runtime Error

Solution code:
INFINITESIMAL = float("-inf")

N, M, P = [int(e) for e in input().split()]
Es = [None] * M

for i in range(M):
    Es[i] = ([int(e) for e in input().split()])
    Es[i][2] -= P

d = [INFINITESIMAL] * (M + 1)
d[1] = 0

for _ in range(M):
    for e in Es:
        u, v, w = e
        dd = d[u] + w
        if d[v] < dd:
            d[v] = dd

circle_exists = False

for e in Es:
    u, v, w = e

    if v != N:
        continue

    if d[v] < d[u] + w:
        circle_exists = True
        break


if circle_exists:
    print(-1)
elif d[N] < 0:
    print(0)
else:
    print(d[N])

Submission status: Runtime Error

Solution code:

N, M, P = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(M)]
inf = 10**9
reachable_from = [False for i in range(N)]
reachable_to = [False for i in range(N)]
reachable_from[0] = True
reachable_to[N-1] = True
edges.sort(key=lambda x: x[0])
for edge in edges:
    if reachable_from[edge[0]-1]:
        reachable_from[edge[1]-1] = True

edges.sort(key=lambda x: x[1], reverse=True)
for edge in edges:
    if reachable_to[edge[1]-1]:
        reachable_to[edge[0]-1] = True

reachable_edges = [edge for edge in edges if reachable_from[edge[0]-1] and reachable_to[edge[1]-1]]
cost_edge = [[edge[0], edge[1], -1*(edge[2]-P)] for edge in reachable_edges]
v = [inf for i in range(N)]
v[0] = 0
finish = True
for i in range(2N):
    for edge in cost_edge:
        if v[edge[1]-1] > v[edge[0]-1] + edge[2]:
            v[edge[1]-1] = v[edge[0]-1] + edge[2]
            if i >= N:
                finish = False
                break
if finish:
    print(max( -1*v[N-1], 0))
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import os

N, M, P = map(int, input().split())
edges = [list(map(int, input().split())) for i in range(M)]
inf = 10**9
reachable_from = [False for i in range(N)]
reachable_to = [False for i in range(N)]
reachable_from[0] = True
reachable_to[N-1] = True
edges.sort(key=lambda x:x[0])
for edge in edges:
    if reachable_from[edge[0]-1]:
        reachable_from[edge[1]-1] = True

edges.sort(key=lambda x:x[1], reverse=True)
for edge in edges:
    if reachable_to[edge[1]-1]:
        reachable_to[edge[0]-1] = True

reachable_edges = [edge for edge in edges if reachable_from[edge[0]-1] and reachable_to[edge[1]-1]]
cost_edge = [[edge[0], edge[1], -1*(edge[2]-P)] for edge in reachable_edges]
v = [inf for i in range(N)]
v[0] = 0

for i in range(N+1):
    for edge in cost_edge:
        if v[edge[1]-1] > v[edge[0]-1] + edge[2]:
            v[edge[1]-1] = v[edge[0]-1] + edge[2]
            if i == N:
                print(-1)
                os.sys.exit(-1)
print(max(-1*v[N-1], 0))

Submission status: Runtime Error

Solution code:
def validate(paths, start):
    """
    有効な経路をDFS(深さ優先探索)
    経路をsetで返す
    """

    valid_paths = {start}
    stack = [start]

    while stack:
        v = stack.pop()
        if v not in paths:
            continue
        for w in paths[v]:
            if w in valid_paths:
                continue
            valid_paths.add(w)
            stack.append(w)
    return valid_paths


def bellman_ford(edges, num_v, start, end):
    """
    有向グラフ(負閉路有り)の最短距離

    num_v: 頂点の数(number_of_vertex)
    edges: 頂点(from, to, cost)
    """

    # グラフの初期化
    dist = [10**18] * num_v
    # 始点は0にする
    dist[start] = 0

    # 辺の緩和
    # 負の閉路が無ければ、num_v-1回までで収束する
    for _ in range(num_v):
        updated = False
        for f, t, c in edges:
            if dist[f] == INF:
                continue

            # コストが以前のものより小さければ更新
            cost = dist[f] + c
            if cost < dist[t]:
                dist[t] = cost
                updated = True
        if not updated:
            break
    else:
        # num_v回の時に更新があるなら負閉路が存在する
        return -1

    return max(-dist[end], 0)


def main():
    from collections import defaultdict

    n, m, p, *tmp = map(int, open(0).read().split())

    paths_rev = defaultdict(list)
    edges = []
    for a, b, c in zip(*[iter(tmp)]*3):
        # 頂点nからの経路をdfsするため、辺の向きを逆にする
        paths_rev[b-1].append(a-1)
        edges.append((a-1, b-1, p-c))

    valid_paths = validate(paths_rev, n-1)
    edges = [
        (a, b, c)
        for a, b, c in edges
        if a in valid_paths and b in valid_paths
    ]
    res = bellman_ford(edges, n, 0, n-1)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf") # sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2
max_even = N // 2
max_odd = N - max_even

# def solve(pos, cnt, num_sum):
#     global cost

#     if not(pos in ABC_d): return
#     if cnt > N or num_sum > max_num_sum:
#         cost[pos-1] = f_inf;

#     for B, C in ABC_d[pos]:
#         if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
#             pass
#         elif cost[B - 1] < cost[pos - 1] + C:
#             cost[B - 1] = cost[pos - 1] + C
#             solve(B, cnt + 1, num_sum + B)

def solve(pos, odd_cnt, even_cnt, num_sum):
    global cost

    # if not(pos in ABC_d): return

    if odd_cnt + even_cnt > N or num_sum > max_num_sum:#  odd_cnt > max_odd or even_cnt > max_even or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            if B%2: odd_cnt += 1
            else: even_cnt += 1
            cost[B - 1] = cost[pos - 1] + C
            solve(B, odd_cnt, even_cnt, num_sum + B)


# solve(1, 1, 1)
solve(1, 1, 0, 1)

if (cost[-1] == f_inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for (s,t), cost in d.items():
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for _ in range(I-1):
        for (s,t), cost in d.items(): #d.keys()
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + cost
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]


cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[pos - 1] == inf: continue
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = np.inf
                solve(B, already)
        else:
            if cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = cost[pos - 1] + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, already2)


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Runtime Error

Solution code:
import numpy as np
N, M, P = map(int, input().split())
# ABC = [list(map(int, input().split())) for _ in range(M)]
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

# print (ABC_d)

cost = np.zeros(N, dtype = int)
looped = False

def solve(pos, c_cost, already):
    global cost
    global looped

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:

        if already[B - 1] == True:
            if cost[B - 1] < c_cost + C:
                looped = True
            else:
                pass
        else:
            if cost[B - 1] < c_cost + C:
                cost[B - 1] = c_cost + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, c_cost + C, already2)
            else:
                pass


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, 0, already)

if (looped == True):
    print (-1)
else:
    print (max(0, cost[-1]))