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 numpy as np
import sys
sys.setrecursionlimit(10000000)

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.empty(N, dtype = int) - np.inf

def solve(pos, c_cost, 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[B - 1] < c_cost + C:
                # looped = True
                cost[B - 1] = np.inf
            # 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 (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)
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]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(2*n):
        for e in E:
            if d[e[0]]!=inf and d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i>=n and e[1]==n-1:
                    d[e[1]] = -float('inf')
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, -C[i]+P])

d = BF(E,0,N)
if d[N-1]==-float('inf'):
    print(-1)
else:
    print(max(0,-d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(4*n):
        for e in E:
            if d[e[0]]!=inf and d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i>=n and e[1]==n-1:
                    return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, -C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,-d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(2*n):
        for e in E:
            if d[e[0]]!=inf and d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i>=n and e[1]==n-1:
                    return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, -C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,-d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(n+1):
        for e in E:
            if  d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
        if i==n-1:t=d[-1]
        if i==n and t!=d[-1]:
            return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, (-1)*C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,(-1)*d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(2*n+1):
        for e in E:
            if d[e[0]]!=inf and d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
        if i==2*n-1:t=d[-1]
        if i==2*n and t!=d[-1]:
            return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, (-1)*C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,(-1)*d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(n+1):
        for e in E:
            if d[e[0]]!=inf and d[e[1]]>d[e[0]]+e[2]:
                d[e[1]] = d[e[0]] + e[2]
        if i==n-1:t=d[-1]
        if i==n and t!=d[-1]:
            return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, (-1)*C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,(-1)*d[N-1]))

Submission status: Wrong Answer

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(n+1):
        for e in E:
            if e[0]!=inf and d[e[1]-1]>d[e[0]-1]+e[2]:
                d[e[1]-1] = d[e[0]-1] + e[2]
        if i==n-1:t=d[-1]
        if i==n and t!=d[-1]:
            return 'loop' #負のループ
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i], B[i], (-1)*C[i]+P])

d = BF(E,0,N)
if d=='loop':
    print(-1)
else:
    print(max(0,(-1)*d[N-1]))

Submission status: Wrong Answer

Solution code:
from collections import deque
NegInf = -float('inf')

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


def bellman_ford(vst, graph, node_num, NegInf):
    costs = [NegInf] * n
    costs[0] = 0
    v_nows = set([vst])
    for _ in range(n):
        v_changeds = set()
        for v_from in v_nows:
            for v_to, cost in graph[v_from]:
                if cost == NegInf:
                    continue
                if costs[v_from] + cost > costs[v_to]:
                    costs[v_to] = costs[v_from] + cost
                    v_changeds.add(v_to)
        v_nows = v_changeds



    if not v_changeds:
        return costs

    for i in v_nows:
        costs[i] = NegInf

    que = deque(v_nows)
    while que:
        v_from = que.popleft()
        for v_to, cost in graph[v_from]:
            if costs[v_to] != NegInf:
                costs[v_to] == NegInf
                que.append(v_to)
    return costs


costs = bellman_ford(0, graph, n, -float('inf'))
if costs[n-1] == NegInf:
    print(-1)
else:
    print(max(0, costs[n-1]))

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c - p


def bellman_ford(vst, graph, node_num):
    costs = [-float('inf')] * n
    costs[0] = 0
    v_nows = set([vst])
    for _ in range(n):
        v_changeds = set()
        for v_from in v_nows:
            for v_to, cost in enumerate(graph[v_from]):
                if cost == -float('inf'):
                    continue
                if costs[v_from] + cost > costs[v_to]:
                    costs[v_to] = costs[v_from] + cost
                    v_changeds.add(v_to)
        v_nows = v_changeds



    if not v_changeds:
        return costs

    for i in v_nows:
        costs[i] = -float('inf')

    que = deque(v_nows)
    while que:
        v_from = que.popleft()
        for v_to, cost in enumerate(graph[v_from]):
            if cost != -float('inf'):
                if costs[v_to] != -float('inf'):
                    costs[v_to] != -float('inf')
                    que.append(v_to)
    return costs


costs = bellman_ford(0, graph, n)
if costs[n-1] == -float('inf'):
    print(-1)
else:
    print(max(0, costs[n-1]))

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c - p


def bellman_ford(vst, graph, node_num):
    costs = [-float('inf')] * n
    costs[0] = 0
    v_nows = set([vst])
    for _ in range(n):
        v_changeds = set()
        for v_from in v_nows:
            for v_to, cost in enumerate(graph[v_from]):
                if cost == -float('inf'):
                    continue
                if costs[v_from] + cost > costs[v_to]:
                    costs[v_to] = costs[v_from] + cost
                    v_changeds.add(v_to)
        v_nows = v_changeds



    if not v_changeds:
        return costs

    for i in v_nows:
        costs[i] = -float('inf')

    que = deque(v_nows)
    while que:
        v_from = que.popleft()
        for v_to, cost in enumerate(graph[v_from]):
            if cost != -float('inf'):
                graph[v_from][v_to] = -float('inf')
                que.append(v_to)
    return costs


costs = bellman_ford(0, graph, n)
if costs[n-1] == -float('inf'):
    print(-1)
else:
    print(max(0, costs[n-1]))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.float128([p-c for c in t[2::3]])
rev = csr_matrix((data, (col, row)), (n, n))
use = set(csgraph.depth_first_order(rev, n-1, return_predecessors=False))
flag = np.array([r in use and c in use for r, c in zip(row, col)])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, indices=(0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([ r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-round(csgraph.bellman_ford(g, True, [0])[0, n-1]))))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([(r in use)and(c in use)for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
def bellman_ford(v, G):
    import copy
    INF = 10 ** 10
    ret = [INF] * len(G)
    ret[v] = 0

    for _ in range(len(G) - 1):
        for u, g in enumerate(G):
            for w, l in g:
                if not ret[u] == INF and ret[w] > ret[u] + l:
                    ret[w] = ret[u] + l

    for _ in range(len(G) - 1):
        for u, g in enumerate(G):
            for w, l in g:
                if not ret[w] == INF and ret[w] > ret[u] + l:
                    ret[w] = -INF

    return ret


N, M, P = map(int, input().split())
G = [[] for _ in range(N)]

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

ans = bellman_ford(0, G)[-1]
print("-1" if ans < -10 ** 10 else max(-ans, 0))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
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
    
    for _ in range(N):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(N):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    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: Wrong Answer

Solution code:
#import sys
#input = sys.stdin.readline
from collections import deque
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
    
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    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: Wrong Answer

Solution code:
def bellman_ford(v, G, confirm=False):
    ret = [10 ** 10] * len(G)
    ret[v] = 0

    for _ in range(len(G) - 1 if not confirm else (len(G) - 1) * 2):
        for u, g in enumerate(G):
            for w, l in g:
                if ret[w] > ret[u] + l:
                    ret[w] = ret[u] + l

    return ret


N, M, P = map(int, input().split())
G = [[] for _ in range(N)]

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

ans = bellman_ford(0, G)[-1]
if ans == bellman_ford(0, G, True)[-1]:
    print(max(-ans, 0))
else:
    print('-1')

Submission status: Wrong Answer

Solution code:
#import sys
#input = sys.stdin.readline
from collections import deque
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
    
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    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: Wrong Answer

Solution code:
#import sys
#input = sys.stdin.readline
def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None:
            continue
        if V[i] > W[i]:
            V[i] = 1
        else:
            V[i] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[t] == 1:
                continue
            if V[s] == 1:
                V[t] = 1
    if V[-1] == 1:
        print(-1)
    else:
        print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#import sys
#input = sys.stdin.readline
def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None:
            continue
        if V[i] > W[i]:
            V[i] = "a"
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == "a" or V[t] == "a":
                V[t] = "a"
    if V[-1] == "a":
        print(-1)
    else:
        print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]
    for e in d:
        s, t = e
        if V[s] == None:
            continue
        if V[t] == None:
            V[t] = V[s] + d[e]
            continue
        if V[s] + d[e] < V[t]:
            V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None or W[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = "a"
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == "a" or V[t] == "a":
                V[t] == "a"
                continue
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] == "a":
        print(-1)
    else:
        print(max(-W[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]

    for e in d:
        s, t = e
        if V[s] == None:
            continue
        if V[t] == None:
            V[t] = V[s] + d[e]
            continue
        if V[s] + d[e] < V[t]:
            V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = -10**14
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10**14:
        print(-1)
    else:
        print(max(-W[-1],0))
if __name__ == '__main__':
    main()