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.

Solution (Python):
n,m,p = map(int, input().split())
edge = []
inv_link = [[] for _ in range(n)]
link = [[] for _ in range(n)]

for i in range(m):
    a,b,cost = list(map(int,input().split()))
    edge.append([a-1,b-1,p-cost])
    link[a-1].append(b-1)
    inv_link[b-1].append(a-1)

def bell(edges, start,num_v):
    cost = [float('inf')] * num_v
    cost[start] = 0
    for _ in range(num_v):
        updated = False
        for a, b, c in edges:
            if cost[b] > cost[a] + c:
                cost[b] = cost[a] + c
                updated = True
        if not updated: break
    else:
        return False,cost
    return True,cost

from collections import deque
Q = deque()
Q.append([n-1,0])
visited=[-1]*n
visited[n-1]=0
while Q:
    now,cnt = Q.popleft()
    for nxt in inv_link[now]:
        if visited[nxt]!=-1:
            continue
        visited[nxt]=cnt+1
        Q.append([nxt,cnt+1])

new_edge=[]
for a,b,c in edge:
    if visited[a]==-1 or visited[b]==-1:
        continue
    new_edge.append([a,b,c])
ret,cost = bell(new_edge,0,n)
if ret:
    print(max(0,-cost[-1]))
else:
    print(-1)

Solution (Python):
f=lambda: map(int,input().split())
    
V,E,P=f()
G=[]
for _ in range(E):
    s,t,d=f()
    G.append((s,t,-(d-P)))

INF=float('inf')
res=[INF]*(V+1)
res[1]=0

def Bellman_Ford():
    for s,t,d in G:
        res[t]=min(res[t],res[s]+d)
        
negative_flg=False
r=INF
for _ in range(V):
    tmp=res[:]
    Bellman_Ford()
    r=min(res[-1],r)
    if tmp==res:
        break
else:
    r0=res[-1]
    for _ in range(V):
        tmp=res[:]
        for s,t,d in G:
            if res[t]>res[s]+d:
                res[t]=-INF
    if r0!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-r,0))

Solution (Python):
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s):
    n=len(graph)
    INF=10**15
    dist = [INF]*n
    dist[s] = 0
    for _ in range(n-1):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for _ in range(n):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v]=-INF
    return dist
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))
d=BF(G,0)
if abs(d[-1])==10**15:
    print(-1)
else:
    print(max(0,-d[-1]))

Solution (Python):
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import csr_matrix

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(a)
  
  toflag[0]=True
  otflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  dic={}
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      if (a,b) in dic.keys():
        dic[(a,b)]=min(dic[(a,b)],c)
      else:
        dic[(a,b)]=c
        
  row=[]
  col=[]
  data=[]
  for (a,b),c in dic.items():
      row.append(a)
      col.append(b)
      data.append(c)
  g=csr_matrix((data,(row,col)), shape=(n,n))
  try:
    d=bellman_ford(g,indices=0).astype(int)
    print(max(0,-d[-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Solution (Python):
import sys
sys.setrecursionlimit(10**5)


def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def bellman_ford():
    for i in range(n):
        upd=False
        for a,b,c in edges:
            if d[b]>d[a]+c:
                upd=True
                d[b]=d[a]+c     
        if not upd:
            break
        if i == n-1:
            print(-1)
            exit()


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        edges.append([a,b,-(c+1-p)])
        to[a].append(b)
        ot[b].append(a)

    toflag[0]=True
    otflag[n-1]=True
    dfs(0) 
    rdfs(n-1) 
 
    for i in range(m):
        a,b,c=edges[i]
        if toflag[a] and otflag[a] and toflag[b] and otflag[b]: continue;
        edges[i]=[0,0,0]

    d[0]=0
    bellman_ford()
    print(max(0,-d[-1]))



if __name__=='__main__':
    n,m,p=map(int,input().split())
    edges=[]
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    d=[10**9]*n
    main()

Solution (Python):

import sys
from collections import deque

read = sys.stdin.read
INF = 1 << 60


def main():
    N, M, P, *ABC = map(int, read().split())

    G = [[] for _ in range(N)]
    G_rev = [[] for _ in range(N)]
    edge = []
    for a, b, c in zip(*[iter(ABC)] * 3):
        a -= 1
        b -= 1
        c = P - c
        G[a].append(b)
        G_rev[b].append(a)
        edge.append((a, b, c))

    
    reachable_1 = [False] * N
    reachable_N = [False] * N

    reachable_1[0] = True
    reachable_N[N - 1] = True

    queue = deque([0])
    while queue:
        v = queue.popleft()
        for nv in G[v]:
            if not reachable_1[nv]:
                reachable_1[nv] = True
                queue.append(nv)

    queue = deque([N - 1])
    while queue:
        v = queue.popleft()
        for nv in G_rev[v]:
            if not reachable_N[nv]:
                reachable_N[nv] = True
                queue.append(nv)

    ok = [reachable_1[i] and reachable_N[i] for i in range(N)]

    dist = [INF] * N
    dist[0] = 0

    for i in range(N):
        for a, b, c in edge:
            if not ok[a] or not ok[b]:
                continue
            if dist[b] > dist[a] + c:
                if i < N - 1:
                    dist[b] = dist[a] + c
                else:
                    print(-1)
                    return

    score = -dist[N - 1]
    print(max(score, 0))
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, P, *ABC = map(int, read().split())

    G = [[] for _ in range(N)]
    G_rev = [[] for _ in range(N)]
    edge = []
    for a, b, c in zip(*[iter(ABC)] * 3):
        a -= 1
        b -= 1
        c = P - c
        G[a].append(b)
        G_rev[b].append(a)
        edge.append((a, b, c))

    reachable_1 = [False] * N
    reachable_N = [False] * N

    reachable_1[0] = True
    reachable_N[N - 1] = True

    queue = deque([0])
    while queue:
        v = queue.popleft()
        for nv in G[v]:
            if not reachable_1[nv]:
                reachable_1[nv] = True
                queue.append(nv)

    queue = deque([N - 1])
    while queue:
        v = queue.popleft()
        for nv in G_rev[v]:
            if not reachable_N[nv]:
                reachable_N[nv] = True
                queue.append(nv)

    ok = [reachable_1[i] and reachable_N[i] for i in range(N)]

    dist = [INF] * N
    dist[0] = 0

    for i in range(N):
        for a, b, c in edge:
            if not ok[a] or not ok[b]:
                continue
            if dist[b] > dist[a] + c:
                if i < N - 1:
                    dist[b] = dist[a] + c
                else:
                    print(-1)
                    return

    score = -dist[N - 1]
    print(max(score, 0))
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, P, *ABC = map(int, read().split())
    edge = [0] * M
    for i, (a, b, c) in enumerate(zip(*[iter(ABC)] * 3)):
        edge[i] = (a - 1, b - 1, -(c - P))

    dist = [INF] * N
    dist[0] = 0

    for _ in range(N - 1):
        for a, b, c in edge:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c

    updated = [False] * N
    for _ in range(N):
        for a, b, c in edge:
            if dist[b] != INF and dist[b] > dist[a] + c:
                updated[b] = True
            if updated[a]:
                updated[b] = True

    if updated[N - 1]:
        print(-1)
    else:
        print(max(0, -dist[N - 1]))

    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, P, *ABC = map(int, read().split())
    edge = [0] * M
    for i, (a, b, c) in enumerate(zip(*[iter(ABC)] * 3)):
        edge[i] = (a - 1, b - 1, -(c - P))

    dist = [INF] * N
    dist[0] = 0

    for _ in range(N - 1):
        for a, b, c in edge:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c

    for _ in range(N):
        for a, b, c in edge:
            if dist[b] != INF and dist[b] > dist[a] + c:
                dist[b] = -INF

    score = -dist[N - 1]

    if score == INF:
        print(-1)
    else:
        print(max(0, score))

    return


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
n, m, p = map(int, input().split())
graph = [[] for _ in range(n+1)]
edge = []
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append((b, c))
    edge.append((a, b, -c+p))

q = deque([])
coins = [0] * (n+1)
ban = [False] * (n+1)

for i in range(1, n+1):
    q.append(i)
    time = [-1] * (n + 1)
    time[i] = 0
    while q:
        now = q.pop()
        for node, coin in graph[now]:
            if time[node] != -1:
                continue
            time[node] = time[now] + 1
            q.append(node)
    if i != 1:
        if time[n] == -1:
            ban[i] = True
    else:
        for j in range(2, n+1):
            if time[j] == -1:
                ban[j] = True


def bellman_ford(v, e_list, start, end):
    inf = 10**9
    dist = [inf] * (v+1)
    dist[start] = 0
    for j in range(v):
        for e in e_list:
            if ban[e[1]]:
                continue
            if dist[e[1]] > e[2] + dist[e[0]]:
                dist[e[1]] = e[2] + dist[e[0]]
                if j == v-1:
                    return -1, 0
    return dist[end], 1


ans, st = bellman_ford(n, edge, 1, n)
if st:
    print(max(-ans, 0))
else:
    print(-1)

Solution (Python):
import sys
 
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  
 
n, m, p = na()
 
def bf(es, n, start):
    d = [999999999999] * n
    d[start] = 0
 
    for r in range(n-1):
        updated = False
        for e in es:
            if d[e[0]] == 999999999999:
                continue
            if d[e[0]] + e[2] < d[e[1]]:
                d[e[1]] = d[e[0]] + e[2]
                updated = True
        if not updated:
            break
 
    for e in es:
        if d[e[0]] < 999999999999 and d[e[0]] + e[2] < d[e[1]]:
            return None
 
    return d
 
es = []
for i in range(m):
    a, b, c = na()
    es.append((a-1, b-1, -(c-p)))
 
import collections
q = collections.deque()
q.append(n-1)
 
valid = [False] * n
valid[n-1] = True
while len(q) > 0:
    cur = q.popleft()
    for e in es:
        if e[1] == cur and not valid[e[0]]:
            valid[e[0]] = True
            q.append(e[0])
 
nes = []
for e in es:
    if valid[e[0]] and valid[e[1]]:
        nes.append(e)
es = nes
 
d = bf(es, n, 0)
if not d:
    print(-1)
else:
    print(max(0, -d[n-1]))

Solution (Python):
import sys
from collections import deque

    
def dfs(x,s):
    used = {s}
    search = deque([s])
    while search:
        ss = search.pop()
        for sss in x[ss]:
            if sss in used:
                continue
            used.add(sss)
            search.append(sss)
    return used


def bellmanford(edges):
    coins = [-float("inf")] * N
    coins[0] = 0
    for _ in range(N):
        f = True
        for u,v,c in edges:
            if coins[u] + c > coins[v]:
                coins[v] = coins[u] + c
                f = False
        if f:
            return max(0, coins[-1])
    return -1

N,M,P = map(int, input().split())
ABC = []
Adake = [[] for _ in range(N)]
Bdake = [[] for _ in range(N)]
for _ in range(M):
    A,B,C = map(int, input().split())
    ABC.append((A-1,B-1,C-P))
    Adake[A-1].append(B-1)
    Bdake[B-1].append(A-1)

U = dfs(Adake,0) & dfs(Bdake,N-1)
ABC = [(a,b,c) for (a,b,c) in ABC if a in U and b in U]

print(bellmanford(ABC))

Solution (Python):
import sys
input = sys.stdin.readline
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

es = [[] for _ in range(N)]
rs = [[] for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    es[a].append(b)
    rs[b].append(a)

stack = [0]
vis_go = set([0])
while stack:
    v = stack.pop()
    for to in es[v]:
        if to in vis_go: continue
        vis_go.add(to)
        stack.append(to)
stack = [N-1]
vis_bk = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in vis_bk: continue
        vis_bk.add(to)
        stack.append(to)
use = vis_go & vis_bk

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for i in range(len(use)):
    for a,b,c in ABC:
        a,b,c = a-1,b-1,P-c
        if a not in use or b not in use: continue
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c
            if i==len(use)-1:
                print(-1)
                exit()
print(max(0,-dist[-1]))

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,m,p = map(int, input().split())
ns = [[] for _ in range(n)]
rns = [[] for _ in range(n)]

mc = -1
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    ns[u].append((p-c,v))
    rns[v].append(u)
q = [n-1]
seen = [False]*n
seen[n-1] = True
while q:
    u = q.pop()
    for v in rns[u]:
        if seen[v]:
            continue
        seen[v] = True
        q.append(v)
def bf(start):
    dist = [float("inf")]*n
    dist[start] = 0
    for i in range(n):
        for u in range(n):
            if dist[u]==float("inf"):
                continue
            for c,v in ns[u]:
                if dist[v] > dist[u] + c:
                    dist[v] = dist[u] + c
                    if i>=n-1 and seen[v]:
                        return -1
    return dist

dist = bf(0)
if dist==-1:
    ans = -1
else:
    ans = max(0, dist[n-1]*-1)
print(ans)

Solution (Python):
import math
from collections import deque

def BellmanFord(edges, N, M, start):
    dist = [math.inf]*N
    dist[start] = 0

    for i in range(N):
        for j in range(M):
            if is_valid(edges[j][0], edges[j][1]):
                if dist[edges[j][1]] > dist[edges[j][0]] + edges[j][2]:
                    dist[edges[j][1]] = dist[edges[j][0]] + edges[j][2]
                    if i == N - 1:
                        return False

    return dist

def dfs(graph, N, start):
    visited = [False]*N
    visited[start] = True
    q = deque([start])

    while q:
        v = q.pop()
        for n_v in graph[v]:
            if not visited[n_v]:
                visited[n_v] = True
                q.append(n_v)
    
    return visited

def is_valid(f, t):
    return can_from_start[f] and can_from_start[t] and can_to_goal[f] and can_to_goal[t]


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

for _ in range(M):
    A, B, C = map(int, input().split())
    graph[A - 1].append(B - 1)
    graph_inv[B - 1].append(A - 1)
    edges.append((A - 1, B - 1, - (C - P)))

can_from_start = dfs(graph, N, 0)
can_to_goal = dfs(graph_inv, N, N - 1)

dist = BellmanFord(edges, N, M, 0)

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

Solution (Python):
INF = 10**18
def bellman_ford(s, n, g): 
    d = [INF]*n
    d[s] = 0
    for i in range(n-1): 
        update = False
        for v_from, v_to, cost in g:
            if d[v_from] != INF and d[v_to] > d[v_from] + cost:
                d[v_to] = d[v_from] + cost
                update = True
        if not update:
            break

    for i in range(n-1): 
        update = False
        for v_from, v_to, cost in g:
            if d[v_from] != INF and d[v_to] > d[v_from] + cost:
                d[v_to] = -INF
                update = True
        if not update:
            break

    return d
    


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


d = bellman_ford(0,n,g)
if d[-1] == -INF: print(-1)
else:
    ans = -d[-1]
    ans = max(0,ans)
    print(ans)

Solution (Python):
from collections import deque
N,M,P = map(int,input().split())
INF = 10**18
edge = []
rev_edge = [[] for _ in range(N+1)]
dis = [INF]*(N+1)
dis[1] = 0
for i in range(M):
    A,B,C = map(int,input().split())
    edge.append((A,B,P-C))
    rev_edge[B].append(A)
d = deque()
can_arrive = set()
d.append(N)
can_arrive.add(N)
while d:
    x = d.popleft()
    for y in rev_edge[x]:
        if not y in can_arrive:
            d.append(y)
            can_arrive.add(y)

for i in range(N):
    update = False
    for j in range(M):
        A,B,cost = edge[j]
        if dis[A] != INF and dis[B] > dis[A]+cost:
            dis[B] = dis[A]+cost
            if B in can_arrive:
                update = True
ans = dis[N]
if update:
    print(-1)
else:
    print(max(0,-ans))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7
INF = float("inf")

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [INF]*N 
min_distance[0] = 0 

def Bellman_Ford(S,V,E,distance):
    flag = 0
    for _ in range(V):
        update = False
        for s,g,d in distance: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break
    return min_distance,flag

def Bellman_Ford2(S,V,E,distance):
    for _ in range(V):
        for s,g,d in distance: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -INF
                if g == N-1:
                    break
        else:
            continue
        break
    return min_distance

min_distance,flag = Bellman_Ford(1,N,M,line)

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    min_distance = Bellman_Ford2(1,N,M,line)
    ans = min_distance[N-1]
    if ans == -INF:
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7
INF = float("inf")

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [INF]*N 
min_distance[0] = 0 

def Bellman_Ford(S,V,E,distance):
    
    flag = 0
    for _ in range(V):
        update = False
        for s,g,d in distance: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break
    return min_distance,flag

def Bellman_Ford2(S,V,E,distance):
    for _ in range(V):
        for s,g,d in distance: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -INF
                if g == N-1:
                    break
        else:
            continue
        break
    return min_distance

min_distance,flag = Bellman_Ford(1,N,M,line)

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    min_distance = Bellman_Ford2(1,N,M,line)
    ans = min_distance[N-1]
    if ans == -INF:
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7
INF = float("inf")

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [INF]*N 
min_distance[0] = 0 

def Bellman_Ford():
    for _ in range(N):
        update = False
        for s,g,d in line: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break

def Bellman_Ford2():
    for _ in range(N):
        for s,g,d in line: 
            if min_distance[s] != INF and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -INF
                if g == N-1:
                    break
        else:
            continue
        break

flag = 0
Bellman_Ford()

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    Bellman_Ford2()
    ans = min_distance[N-1]
    if ans == -INF:
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [float("inf")]*N 
min_distance[0] = 0 

flag = 0
for _ in range(N):
        update = False
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    for _ in range(N):
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -float("inf")
                if g == N-1:
                    break
        else:
            continue
        break
    ans = min_distance[N-1]
    if ans == -float("inf"):
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [float("inf")]*N 
min_distance[0] = 0 

def Bellman_Ford():
    for _ in range(N):
        update = False
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break

def Bellman_Ford2():
    for _ in range(N):
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -float("inf")
                if g == N-1:
                    break
        else:
            continue
        break

flag = 0
Bellman_Ford()

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    Bellman_Ford2()
    ans = min_distance[N-1]
    if ans == -float("inf"):
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [float("inf")]*N 
min_distance[0] = 0 

def Bellman_Ford():
    flag = 0
    for _ in range(N):
        update = False
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break
    return min_distance,flag

def Bellman_Ford2():
    for _ in range(N):
        for s,g,d in line: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -float("inf")
                if g == N-1:
                    break
        else:
            continue
        break
    return min_distance

min_distance,flag = Bellman_Ford()

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    min_distance = Bellman_Ford2()
    ans = min_distance[N-1]
    if ans == -float("inf"):
        print(-1)
    else:
        print(max(-ans,0))

Solution (Python):
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

min_distance = [float("inf")]*N 
min_distance[0] = 0 

def Bellman_Ford(S,V,E,distance):
    
    flag = 0
    for _ in range(V):
        update = False
        for s,g,d in distance: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                update = True
        if not update:
            flag = 1
            break
    return min_distance,flag

def Bellman_Ford2(S,V,E,distance):
    for _ in range(V):
        for s,g,d in distance: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = -float("inf")
                if g == N-1:
                    print(-1)
                    exit()
                    break
        else:
            continue
        break
    return min_distance

min_distance,flag = Bellman_Ford(1,N,M,line)

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    min_distance = Bellman_Ford2(1,N,M,line)
    ans = min_distance[N-1]
    if ans == -float("inf"):
        print(-1)
    else:
        print(max(-ans,0))