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):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Bellman_Ford(s,n,w,es,ppp):
    
    
    d = [Max] * n
    
    d[s] = 0
    po = 0
    while po < 2*N + 2*M:
        update = False
        for p,q,r in es:
        
            if d[p] != Max and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
                if (ppp[q] != 0 and po > N):
                    d[-1] = None
                    update = False
                    break
        if not update:
            break
        po += 1
    return d

import heapq

def dijkstra(n,w,e):
    

    edge = [[] for i in range(n)]
    dg = 10**18
    
    for i in e:
        x,y = i
        z = 1
        x -= 1
        y -= 1
        edge[x].append(dg + y)
        
    
    s = w-1
    d = [-1]*n
    
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d




N,M,P = m()

es = []
ess = []

gr = [[] for i in range(N)]

ok = [0 for i in range(N)]

for _ in range(M):

    x,y,z = map(int,input().split())

    x -= 1
    y -= 1
    es.append([x,y,-z+P])
    gr[y].append(x)


ok[-1] = 1
po = cl.deque([N-1])
while po:
    o = po.popleft()
    
    for i in gr[o]: 
        if not ok[i]:
            po.append(i)
            ok[i] = 1





po = Bellman_Ford(0,N,M,es,ok)


print(-1 if po[-1] == None else -po[-1] if po[-1] <= 0 else 0)

Solution (Python):
import sys
sys.setrecursionlimit(100000)
from collections import defaultdict
edges = []
to = defaultdict(list) 
ot = defaultdict(list) 
N, M, P = map(int, input().split())
visited_toN = [False]*(N+1)
visited_fm1 = [False]*(N+1)    
for i in range(M):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append((a,b,-c+P))
    to[a].append(b)
    ot[b].append(a)

def dfs(v):
    global visited_fm1
    if visited_fm1[v]:return
    visited_fm1[v] = True
    for nxt in to[v]:
        dfs(nxt)
    
def dfs_r(v):
    global visited_toN
    if visited_toN[v]:return
    visited_toN[v] = True
    for nxt in ot[v]:
        dfs_r(nxt)
        
dfs(0)
dfs_r(N-1)
is_ok = []

for s, t in zip(visited_fm1,visited_toN):
    is_ok.append(s and t)



INF = 10 ** 18
def bellmanFord(n, edges, s, g):
    """
    input
        n : 頂点の数
        edges : (始点, 終点, コスト)のリスト
        s : 探索の始点
        g : 探索の終点
    output
        sから各点への最短距離
    """    
    d = [INF] * n
    d[s] = 0
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if not is_ok[a]:continue
            if not is_ok[b]:continue
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        
        if cnt > n:
            print(-1)
            exit()
        
    return d[g]



ans = bellmanFord(N,edges,0,N-1)
print(max(0,-ans))

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

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

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

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

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

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  
        self._E = 0  
        self._V = V  

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

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

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

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。
                     到達不可の場合、値はfloat("inf")
        """
        import heapq
        que = []  
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                
                e = self.G[v][i]  
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost  
                    heapq.heappush(que, (d[e.to], e.to))  
        return d

def BellmanFord(edges,num_v,source):
  
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0

  
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        if i==num_v-1: return -1

  return dist

N,M,P=map(int,input().split())
edges=[]
test=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    edges.append([a,b,P-c])
    test.add(b-1,a-1,1)

use=set([N-1])
t=test.shortest_path(N-1)
for i in range(0,N-1):
    if t[i]!=10**15:
        use.add(i)

useedges=[]
for i in range(0,M):
    a,b,c=edges[i]
    if a-1 in use and b-1 in use:
        useedges.append(edges[i])

ans=BellmanFord(useedges,N,1)
if ans==-1:
    print(-1)
else:
    if -ans[N-1]>=0:
        print(-ans[N-1])
    else:
        print(0)

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


N, M, P = map(int, readline().split())

EDGES = []
TO = [[] for _ in range(N + 1)]
RTO = [[] for _ in range(N + 1)]

for _ in range(M):
    a, b, c = map(int, readline().split())
    EDGES.append((a, b, c))
    TO[a].append(b)
    RTO[b].append(a)


REACH_FROM_1 = [False] * (N+1)
q = [1]
while q:
    u = q.pop()
    if REACH_FROM_1[u]:
        continue
    REACH_FROM_1[u] = True
    for v in TO[u]:
        q.append(v)


REACH_TO_N = [False] * (N + 1)
q = [N]
while q:
    u = q.pop()
    if REACH_TO_N[u]:
        continue
    REACH_TO_N[u] = True
    for v in RTO[u]:
        q.append(v)

STATE = [REACH_FROM_1[i] & REACH_TO_N[i] for i in range(N + 1)]


INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N):
    update = False
    for j in range(M):
        a, b, c = EDGES[j]
        if not STATE[a]:
            continue
        pt = - (c - P)
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i == N-1:
                print(-1)
                exit()

    if not update:
        break


pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Solution (Python):
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()

graph = [tuple(lr()) for _ in range(M)]

def bellmanford(start, N):
    INF = 10 ** 12
    dist = [-INF] * (N+1) 
    dist[start] = 0
    for i in range(N+N+5):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Solution (Python):
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()

graph = [lr() for _ in range(M)]

def bellmanford(start, N):
    INF = 10 ** 12
    dist = [-INF] * (N+1) 
    dist[start] = 0
    for i in range(N+N+5):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Solution (Python):
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()

graph = []
for _ in range(M):
    a, b, c = lr()
    graph.append((a, b, c))

def bellmanford(N, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) 
    dist[start] = 0
    for i in range(N+N+5):
        for (pre, ne, weight) in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(N, 1)
print(answer)

Solution (Python):




from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
import sys




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

idle_max=10**9




visited=set()
stack=[N]
while stack:
    a=stack.pop()
    for p in data[a]:
        if not p in visited:
            visited.add(p)
            stack.append(p)




data=[idle_max for i in range(N+1)]
data[1]=0
for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
predata=copy.copy(data)
value=data[N]
for i in range(N):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)

for i in visited:
    if predata[i]>data[i]:
        break
else:
    print(max(-value,0))
    exit()
print(-1)

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10**19
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[a] != INF and dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    dist = [float('inf')] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]


def bellmanford(s, g):
    dist = [float("inf")] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            cost = -(c - P)
            if dist[b] > dist[a] + cost:
                dist[b] = dist[a] + cost
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)

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


def bellman_ford(s, g):
    
    
    dist = [float("inf")] * n
    dist[s] = 0
    for i in range(2 * n):
        for a, b, c in abc:
            a -= 1
            b -= 1
            cost = -(c - p)

            if dist[b] > dist[a] + cost:
                dist[b] = dist[a] + cost
                if i >= n:
                    dist[b] = -float("inf")

    if dist[g] == -float("inf"):
        return -1

    else:
        return max(-dist[g], 0)


ans = bellman_ford(0, n - 1)
print(ans)

Solution (Python):
n,m,p=map(int,input().split())
def BellmanFord(edges,num_v,s):
  
  inf=float("inf")
  dist=[inf]*num_v
  dist[s]=0
  
  for i in range(num_v-1):
    for edge in edges: 
      if dist[edge[0]] != inf and dist[edge[1]] > dist[edge[0]] + edge[2]+p:
        dist[edge[1]] = dist[edge[0]] + edge[2]+p
  cnt1=-dist[n-1]
  neg=[False]*num_v
  for i in range(num_v):
    for edge in edges: 
      if dist[edge[1]] > dist[edge[0]] + edge[2]+p:
        dist[edge[1]] = dist[edge[0]] + edge[2]+p
        neg[edge[1]]=True
      if neg[edge[0]]:
        neg[edge[1]]=True
  if neg[n-1]:
    ans=-1
  else:
    ans=max(cnt1,0)
  return ans
edges=[]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c*=-1
  edges.append((a,b,c))
print(BellmanFord(edges,n,0))

Solution (Python):
from collections import deque

def dfs(edge, s):
    used = {s}
    que = deque([s])
    while que:
        v = que.pop()
        for u in edge[v]:
            if u in used:
                continue
            used.add(u)
            que.append(u)
    return used

def bellmanFord(edges):
    coins = [float('inf')] * N
    coins[0] = 0
    for _ in range(len(U)):
        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())
A = [[] for _ in range(N)]
A_rev = [[] for _ in range(N)]
E = [tuple()] * M
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = P - c
    A[a].append(b)
    A_rev[b].append(a)
    E[i] = (a, b, c)
U = dfs(A, 0) & dfs(A_rev, N-1)
F = [(a, b, c) for (a, b, c) in E if a in U and b in U]
print(bellmanFord(F))

Solution (Python):
from collections import deque

def dfs(edge, s):
    used = {s}
    que = deque([s])
    while que:
        v = que.pop()
        for u in edge[v]:
            if u in used:
                continue
            used.add(u)
            que.append(u)
    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())
A = [[] for _ in range(N)]
A_rev = [[] for _ in range(N)]
E = [tuple()] * M
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = P - c
    A[a].append(b)
    A_rev[b].append(a)
    E[i] = (a, b, c)
U = dfs(A, 0) & dfs(A_rev, N-1)
F = [(a, b, c) for (a, b, c) in E if a in U and b in U]
print(bellmanFord(F))

Solution (Python):
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def reachable_nodes(s, edges):
    cur = {s}
    reachable = set()
    while cur:
        reachable |= cur
        cur = set().union(*(edges[node] for node in cur)) - reachable
    return reachable


def solve():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        to[a - 1].append(b - 1)
        reverse_to[b - 1].append(a - 1)
    
    reachable = reachable_nodes(0, to) & reachable_nodes(N - 1, reverse_to)
    
    edge_dict = dict()
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            edge_dict[(a, b)] = min(c, edge_dict.get((a, b), 10 ** 6))
    AA, BB, CC = [], [], []
    for (a, b), c in edge_dict.items():
        AA.append(a)
        BB.append(b)
        CC.append(c)
    
    graph = csr_matrix((CC, (AA, BB)), shape=(N, N))
    try:
        bf = bellman_ford(graph, indices=[0])
        print(max(0, -int(bf[0][N - 1])))
    except NegativeCycleError:
        print(-1)


if __name__ == '__main__':
    solve()

Solution (Python):
def BF(v, start, edges):
    INF = 10**18
    nega = False
    d = [INF] * v
    d[start] = 0
    for _ in range(v):
        f = False
        for a, b, c in edges:
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        if not f:
            break
    else:
        nega = True
    return d, nega

from collections import deque
def BFS(N, graph, start):
    d = [-1 for i in range(N)]
    Q = deque([])
    Q.append(start)
    d[start] = 0
    while Q:
        v = Q.popleft()
        for u in graph[v]:
            if d[u] == -1:
                d[u] = d[v] + 1
                Q.append(u)
    return d

N, M, P = (int(i) for i in input().split())
graph = [[] for i in range(N)]
graphr = [[] for i in range(N)]
edges = []
for i in range(M):
    A, B, C = (int(i) for i in input().split())
    graph[A-1].append(B-1)
    graphr[B-1].append(A-1)
    edges.append((A-1, B-1, P-C))
d_start = BFS(N, graph, 0)
d_end = BFS(N, graphr, N-1)
nodes_start = [i for i in range(N) if d_start[i] >= 0]
nodes_end = [i for i in range(N) if d_end[i] >= 0]
new_edges = []
for A, B, C in edges:
    if A in nodes_start and B in nodes_start and A in nodes_end and B in nodes_end:
        new_edges.append((A, B, C))
d, Nega = BF(N, 0, new_edges)
if Nega == True:
    print(-1)
else:
    print(max(-d[N-1], 0))

Solution (Python):
from collections import deque

class GraphWeighted(): 
    def __init__(self,n,edge):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.deg = [0 for _ in range(n)]
        for e in edge:
            self.graph[e[0]-1].append((e[1]-1,e[2]))
            self.deg[e[1]-1] += 1
    def bellman_ford(self,s,INF=10**18):
        dist = [INF for _ in range(self.n)]
        dist[s] = 0
        update = True
        for i in range(self.n):
            update = False
            for node, g in enumerate(self.graph):
                for adj,adjcost in g:
                    if dist[node] != INF and dist[node]+adjcost < dist[adj]:
                        dist[adj] = dist[node]+adjcost
                        update = True
                        if i == self.n-1:
                            tmp = adj
            if not update:
                return dist
        visited = [0 for _ in range(self.n)]
        visited[tmp] = 1
        stack = [tmp]
        while stack:
            node = stack.pop()
            for adj,c in self.graph[node]:
                if not visited[adj]:
                    visited[adj] = 1
                    stack.append(adj)
        if visited[-1]:
            return -1
        else:
            return dist

class Graph(): 
    def __init__(self,n,edge):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.deg = [0 for _ in range(n)]
        for e in edge:
            self.graph[e[0]-1].append(e[1]-1)
            self.deg[e[1]-1] += 1
    def BFS(self,s):
        dist = [None for _ in range(self.n)]
        dist[s] = 0
        queue = deque([s])
        while queue:
            node = queue.popleft()
            for adj in self.graph[node]:
                if dist[adj] is not None:
                    continue
                dist[adj] = dist[node]+1
                queue.append(adj)
        return dist

INF = 10**18

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

rev = []
for e in E:
    rev.append((e[1],e[0]))

R = Graph(N,rev)
reachable = R.BFS(N-1)

edge = []
for e in E:
    if reachable[e[0]-1] is None or reachable[e[1]-1] is None:
        continue
    edge.append((e[0],e[1],P-e[2]))

G = GraphWeighted(N,edge)
A = G.bellman_ford(0)

print(max(-A[-1],0) if A!=-1 else -1)

Solution (Python):
N, M, P = map(int, input().split())

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


dist = [-float('inf')]*N
dist[0] = 0
for i in range(N):
  for a, b, c in abc:
    dist[b] = max(dist[b], dist[a] + c)


for a, b, c in abc:
  d = dist[a] + c
  if dist[b] < d:
    dist[b] = float('inf')

for i in range(N-1):
  for a, b, c in abc:
    dist[b] = max(dist[b], dist[a] + c)

if dist[-1] < float('inf'):
  ans = max(0, dist[-1])
else:
  ans = -1

print(ans)

Solution (Python):
from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)
N, M, P = map(int,input().split())
es = []
to = defaultdict(list)
rto = defaultdict(list)
rf = [False]*N
rt = [False]*N
for i in range(M):
  a, b, c = map(int, input().split())
  es += [(a-1,b-1,-c+P)]
  to[a-1] += [b-1]
  rto[b-1] += [a-1]

def dfs(v):
  if rf[v]:
    return
  rf[v] = True
  for u in to[v]:
    dfs(u)

def rdfs(v):
  if rt[v]:
    return
  rt[v] = True
  for u in rto[v]:
    rdfs(u)

dfs(0)
rdfs(N-1)
ok = [False]*N
for i in range(N):
  ok[i] = rf[i]&rt[i]

dist = [float('inf')]*N
dist[0] = 0
upd = True
cnt = 0
while upd:
  upd = False
  for j in range(M):
    f, t, c = es[j]
    if (not ok[f]) or (not ok[t]):
      continue
    if dist[t]>dist[f]+c:
      upd = True
      dist[t] = dist[f]+c
  cnt += 1
  if cnt>N:
    print(-1)
    break
else:
  print(max(0,-dist[N-1]))

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	
  
  dist=[inf for i in range(n)]
  dist[s]=0
  
  
  for i in range(2*n):
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n: dist[v]=-inf
  return dist

dist = BellmanFord(E,n,0)
if dist[n-1] == -inf:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	
  
  dist=[inf for i in range(n)]
  dist[s]=0
  
  
  for i in range(3*n):
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n: dist[v]=-inf
  return dist

dist = BellmanFord(E,n,0)
if dist[n-1] == -inf:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	
  
  dist=[inf for i in range(n)]
  dist[s]=0
  
  
  for i in range(n+10000):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n+5000: dist[v]=-inf
        update = True
  return dist
  
  

dist = BellmanFord(E,n,0)
if dist[n-1] == -inf:
	print(-1)
else:
	print(max(0,-dist[n-1]))

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


dist = [float('inf')] * N
dist[0] = 0

for i in range(2 * N):
    for fr, to, cost in Edges:
        if dist[to] > dist[fr] + cost:
            dist[to] = dist[fr] + cost
            if i >= N:
                dist[to] = -float('inf')


print(max(0, -dist[N - 1]) if -dist[N - 1] != float('inf') else -1)

Solution (Python):
INF = float('inf')
N, M, P = map(int, input().split())
edge = []
for i in range(M):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c - P))

d = [-INF] * N
d[0] = 0

for i in range(N - 1):
    for a, b, c in edge:
        if d[b] < d[a] + c:
            d[b] = d[a] + c

ans = d[-1]

for i in range(N - 1):
    for a, b, c in edge:
        if d[b] < d[a] + c:
            d[b] = INF

if ans != d[-1]:
    print(-1)
else:
    print(max(0, d[N - 1]))

Solution (Python):
INF = 10 ** 10
N, M, P = map(int, input().split())
edge = []
for i in range(M):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c - P))

d = [-INF] * N
d[0] = 0

for i in range(N - 1):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = d[a] + c

ans = d[-1]

for i in range(N - 1):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = INF

if ans != d[-1]:
    print(-1)
else:
    print(max(0, d[N - 1]))

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline


def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)

    
    
    
    visited1 = set() 
    visited2 = set()
    visited1.add(0)
    visited2.add(N-1)
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        for dest in g[v]:
            if dest in visited1:
                continue
            visited1.add(dest)
            Q.append(dest)
    
    Q.append(N-1)
    while Q:
        v = Q.popleft()
        for dest in rg[v]:
            if dest in visited2:
                continue
            visited2.add(dest)
            Q.append(dest)
    
    OK = visited1 & visited2
    
    flag = True
    d = [float('inf')] * N
    d[0] = 0
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    step = 0
    while flag:
        flag = False
        for A, B, C in edge:
            if not A in OK:
                continue
            if not B in OK:
                continue
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()
 
    print(max(0,-d[N-1]))


if __name__ == "__main__":
    main()