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

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
input = sys.stdin.readline


n, m, p = map(int, input().split())
l = np.zeros((n, n))
for i in range(m):
    a, b, c =map(int, input().split())
    c = p-c
    if c == 0:
        c = 10**(-7.9)
    if l[a-1][b-1] == 0:
        l[a-1][b-1] = c
    else:
        l[a-1][b-1] = min(l[a-1][b-1], c)
x = l[-1, 0]
l[-1][0] = 10**(-7.9)
n, labels = connected_components(l, connection="strong")
l = l[labels == labels[0]][:, labels == labels[0]]
l[-1, 0] = x
    
try:
    print(max(0, int(bellman_ford(l, indices=0)[-1])*(-1)))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    tree = [[] for _ in range(n)]
    point = [[0]*n for _ in range(n)]
    
    
    for i in range(m):
        a, b, c = map(int, input().split())
        point[a-1][b-1] = c
        tree[a-1].append(b-1)
    
    not_yet = deque([0])
    already = [False]*n
    already[0] = True
    inf_judge = [False]*n
    par = [0]*n
    dist = [0]*n
    point_sum = [0]*n
    par_list = [set() for _ in range(n)]
    
    while not_yet:
        key = not_yet.popleft()
        
        for v in tree[key]:
            if key == v:
                if point[key][v] > p:
                    inf_judge[key] = True
                    par_list[key] = par_list[key].union({v})
                continue
            if already[v]:
                if v in par_list[key]:
                    judge = (point_sum[key]-point_sum[v]+point[key][v])-(dist[key]-dist[v]+1)*p
                    if judge > 0:
                        sub = par[v]
                        par[v] = key
                        child = v
                        while True:
                            inf_judge[child] = True
                            if child == key:
                                break
                            child = par[child]
                            print(child)
                        par[v] = sub
                else:
                    judge1 = point_sum[v]-dist[v]*p
                    judge2 = point_sum[key]+point[key][v]-(dist[key]+1)*p
                    if judge1 < judge2:
                        dist[v] = dist[key]+1
                        point_sum[v] = point_sum[key]+point[key][v]
                        par[v] = key
                        not_yet.append(v)
                        par_list[v] = par_list[key].union({key})
                continue
            not_yet.append(v)
            par[v] = key
            dist[v] = dist[key]+1
            point_sum[v] = point_sum[key]+point[key][v]
            par_list[v] = par_list[key].union({key})
            already[v] = True

    for v in par_list[n-1]:
        if inf_judge[v]:
            print(-1)
            sys.exit()
    
    ans = point_sum[n-1]-p*dist[n-1]
    print(max(0,ans))
    
    
    
    
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    tree = [[] for _ in range(n)]
    point = [[0]*n for _ in range(n)]
    
    
    for i in range(m):
        a, b, c = map(int, input().split())
        point[a-1][b-1] = c
        tree[a-1].append(b-1)
    
    not_yet = deque([0])
    already = [False]*n
    already[0] = True
    inf_judge = [False]*n
    par = [0]*n
    dist = [0]*n
    point_sum = [0]*n
    par_list = [set() for _ in range(n)]
    
    while not_yet:
        key = not_yet.popleft()
        
        for v in tree[key]:
            if key == v:
                if point[key][v] > p:
                    inf_judge[key] = True
                    par_list[key] = par_list[key].union({v})
                continue
            if already[v]:
                if v in par_list[key]:
                    judge = (point_sum[key]-point_sum[v]+point[key][v])-(dist[key]-dist[v]+1)*p
                    if judge > 0:
                        sub = par[v]
                        par[v] = key
                        child = v
                        while True:
                            inf_judge[child] = True
                            if child == key:
                                break
                            child = par[child]
                            print(child)
                        par[v] = sub
                else:
                    judge1 = point_sum[v]-dist[v]*p
                    judge2 = point_sum[key]+point[key][v]-(dist[key]+1)*p
                    if judge1 < judge2:
                        dist[v] = dist[key]+1
                        point_sum[v] = point_sum[key]+point[key][v]
                continue
            not_yet.append(v)
            par[v] = key
            dist[v] = dist[key]+1
            point_sum[v] = point_sum[key]+point[key][v]
            par_list[v] = par_list[key].union({key})
            already[v] = True

    for v in par_list[n-1]:
        if inf_judge[v]:
            print(-1)
            sys.exit()
    
    ans = point_sum[n-1]-p*dist[n-1]
    print(max(0,ans))
    
    
    
    
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    import numpy as np
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
    smat = bellman_ford(csr_matrix((C, (A, B)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, unweighted=True, indices=1)
    tmat = bellman_ford(csr_matrix((C, (B, A)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, unweighted=True, indices=N)
    r = set([i for i, v in enumerate(smat + tmat) if not np.isinf(v)])
    try:
        csr_mat = csr_matrix(([P-c if a in r or b in r else np.inf for a, b, c in zip(A, B, C)], (A, B)),
                             shape=(N+1, N+1), dtype=np.float64)
        return -min(int(bellman_ford(csr_mat, directed=True, indices=1)[N]), 0)
    except NegativeCycleError:
        return -1

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
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
    P = 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))
    print(solve(N, M, P, A, B, C))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    import numpy as np
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
    smat = bellman_ford(csr_matrix((C, (A, B)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, indices=1)
    tmat = bellman_ford(csr_matrix((C, (B, A)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, indices=N)
    r = set([i for i, v in enumerate(smat + tmat) if not np.isinf(v)])
    try:
        csr_mat = csr_matrix(([P-c if b in r else np.inf for b, c in zip(B, C)], (A, B)),
                             shape=(N+1, N+1), dtype=np.float64)
        return max(-int(bellman_ford(csr_mat, directed=True, indices=1)[N]), 0)
    except NegativeCycleError:
        return -1

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
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
    P = 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))
    print(solve(N, M, P, A, B, C))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    import numpy as np
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
    smat = bellman_ford(csr_matrix((C, (A, B)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, indices=1)
    tmat = bellman_ford(csr_matrix((C, (B, A)), shape=(N+1, N+1), dtype=np.int32),
                        directed=True, indices=N)
    r = set([i for i, v in enumerate(smat + tmat) if not np.isinf(v)])
    try:
        csr_mat = csr_matrix(([P-c if b in r else np.inf for b, c in zip(B, C)], (A, B)),
                             shape=(N+1, N+1), dtype=np.float32)
        return max(-int(bellman_ford(csr_mat, directed=True, indices=1)[N]), 0)
    except NegativeCycleError:
        return -1

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
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
    P = 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))
    print(solve(N, M, P, A, B, C))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = -c+p

def bellmanFord(G, start_vertex):
    N = n
    distance = [float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[node] != float('inf') and distance[neighbor] > distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[node] = -float('inf')
                        distance[neighbor] = -float('inf')
        if i == N-1:
            prev = distance[N]
    if prev != distance[N]:
        return -1
    else:
        return -distance[N]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = -c+p

def bellmanFord(G, start_vertex):
    N = n
    distance = [float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] > distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[node] = -float('inf')
                        distance[neighbor] = -float('inf')
        if i == N-1:
            prev = distance[N]
    if prev != distance[N]:
        return -1
    else:
        return -distance[N]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = n
    distance = [-float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[node] = float('inf')
                        distance[neighbor] = float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = n
    distance = [-float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = n
    distance = [float('-inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if node != float('-inf') and distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = n
    distance = [float('-inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = -(c-p)

def bellmanFord(G, start_vertex):
    N = len(G)
    distance = [float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] > distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = -float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, -distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = -(c-p)

def bellmanFord(G, start_vertex):
    N = len(G)
    distance = [float('inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] > distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('-inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, -distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = len(G)
    distance = [float('-inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('inf')
        if i == N-1:
            prev = distance[n]
    if prev != distance[n]:
        return -1
    else:
        return distance[n]
distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c-p

def bellmanFord(G, start_vertex):
    N = len(G)
    distance = [float('-inf') for i in range(N+1)]
    distance[start_vertex] = 0
    for i in range(2*N):
        for node in G.keys():
            for neighbor in G[node]:
                cost= G[node][neighbor]
                if distance[neighbor] < distance[node] + cost:
                    if i < N:
                        distance[neighbor] = distance[node] + cost
                    else:
                        distance[neighbor] = float('inf')
            if i == N-1:
                prev = distance[-1]
    if prev != distance[N]:
        return -1
    else:
        return distance[N]

distance = bellmanFord(G, 1)
if distance == -1:
    ans = -1
else:
    ans = max(0, distance)
print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

def bellmanford(G, start_vertex):
    if start_vertex not in G:
        return -1,-1 # no key
    distances = {}
    parents   = {}
    for node in G:
        # distances[node] = float('inf')
        distances[node] = float('-inf')
        parents[node]   = None
    distances[start_vertex] = 0
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                # if distances[neighbor] > distances[node] + G[node][neighbor]:
                   distances[neighbor] = distances[node] + G[node][neighbor] - p
                   parents[neighbor]   = node

    prev = distances[n]
    # for node in G.keys():
    #     for neighbor in G[node]:
    #         if (distances[neighbor] < distances[node] + G[node][neighbor]):
    #         # if (distances[neighbor] > distances[node] + G[node][neighbor]):
    #             return -1,-1 # occurs recursion.
    # if you only need to check the recursion on right path
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                   distances[neighbor] = float('inf')

    if prev != distances[n]:
        return -1,-1

    return distances, parents
distances, parents = bellmanford(G, 1)

ans = 0
if distances == -1 or distances[n] == float('-inf'):
    print(-1, flush=True)
else:
    print(max(ans, distances[n]), flush=True)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

def bellmanford(G, start_vertex):
    if start_vertex not in G:
        return -1,-1 # no key
    distances = {}
    parents   = {}
    for node in G:
        # distances[node] = float('inf')
        distances[node] = float('-inf')
        parents[node]   = None
    distances[start_vertex] = 0
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                # if distances[neighbor] > distances[node] + G[node][neighbor]:
                   distances[neighbor] = distances[node] + G[node][neighbor] - p
                   parents[neighbor]   = node

    prev = distances[n]
    # for node in G.keys():
    #     for neighbor in G[node]:
    #         if (distances[neighbor] < distances[node] + G[node][neighbor]):
    #         # if (distances[neighbor] > distances[node] + G[node][neighbor]):
    #             return -1,-1 # occurs recursion.
    # if you only need to check the recursion on right path
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                   distances[neighbor] = float('-inf')

    if prev != distances[n]:
        return -1,-1

    return distances, parents
distances, parents = bellmanford(G, 1)

ans = 0
if distances == -1 or distances[n] == float('-inf'):
    print(-1, flush=True)
else:
    print(max(ans, distances[n]), flush=True)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

def bellmanford(G, start_vertex):
    if start_vertex not in G:
        return -1,-1 # no key
    distances = {}
    parents   = {}
    for node in G:
        # distances[node] = float('inf')
        distances[node] = float('-inf')
        parents[node]   = None
    distances[start_vertex] = 0
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                # if distances[neighbor] > distances[node] + G[node][neighbor]:
                   distances[neighbor] = distances[node] + G[node][neighbor] - p
                   parents[neighbor]   = node
    # for node in G.keys():
    #     for neighbor in G[node]:
    #         if (distances[neighbor] < distances[node] + G[node][neighbor]):
    #         # if (distances[neighbor] > distances[node] + G[node][neighbor]):
    #             return -1,-1 # occurs recursion.
    # if you only need to check the recursion on right path
    for _ in range(len(G)):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                   distances[neighbor] = float('-inf')

    return distances, parents
distances, parents = bellmanford(G, 1)

ans = 0
if distances == -1 or distances[n] == float('-inf'):
    print(-1, flush=True)
else:
    print(max(ans, distances[n]), flush=True)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

def bellmanford(G, start_vertex):
    if start_vertex not in G:
        return -1,-1 # no key
    distances = {}
    parents   = {}
    for node in G:
        # distances[node] = float('inf')
        distances[node] = float('-inf')
        parents[node]   = None
    distances[start_vertex] = 0
    for _ in range(len(G)-1):
        for node in G.keys():
            for neighbor in G[node]:
                if node != neighbor and distances[neighbor] < distances[node] + G[node][neighbor] - p:
                # if distances[neighbor] > distances[node] + G[node][neighbor]:
                   distances[neighbor] = distances[node] + G[node][neighbor] - p
                   parents[neighbor]   = node
    # for node in G.keys():
    #     for neighbor in G[node]:
    #         if (distances[neighbor] < distances[node] + G[node][neighbor]):
    #         # if (distances[neighbor] > distances[node] + G[node][neighbor]):
    #             return -1,-1 # occurs recursion.
    # if you only need to check the recursion on right path
    node = n
    while node != start_vertex:
        for neighbor in G[node]:
            if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                return -1,-1
        node = parents[node]
    return distances, parents
distances, parents = bellmanford(G, 1)

ans = 0
if distances == -1:
    print(-1, flush=True)
else:
    print(max(ans, distances[n]), flush=True)