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):
inf = float('inf')


class Bellmanford:
    def __init__(self, to : list, start : int, goal : int):
        self.N = len(to)
        self.to = [s[:] for s in to]
        self.start = start
        self.goal = goal
        self.dist = [inf] * self.N
        self.dist[start] = 0
    
    
    def update(self) -> None:
        for _ in range(self.N - 1):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
    
    
    def detection(self) -> bool:
        exists_negative_cycle = False
        for v, s in enumerate(self.to):
            if not s: continue
            for nv, w in s:
                if self.dist[nv] > self.dist[v] + w:
                    self.dist[nv] = self.dist[v] + w
                    exists_negative_cycle = True
        return exists_negative_cycle
    
    
    def detection_stog(self) -> bool:
        exists_negative_cycle_stog = False
        is_updated = [False] * self.N
        for _ in range(self.N):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
                        is_updated[nv] = True
                    if is_updated[v] is True:
                        is_updated[nv] = True
        exists_negative_cycle_stog = is_updated[self.goal]
        return exists_negative_cycle_stog

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

BF = Bellmanford(to, 0, N-1)
BF.update()

if BF.detection_stog():
    ans = -1
else:
    ans = max(-BF.dist[N-1], 0)

print(ans)

Solution (Python):
inf = float('inf')


class Bellmanford:
    def __init__(self, to : list, start : int, goal : int):
        self.N = len(to)
        self.to = [s[:] for s in to]
        self.start = start
        self.goal = goal
        self.dist = [inf] * self.N
        self.dist[start] = 0
        self.exists_negative_cycle = False
        self.exists_negative_cycle_stog = False
        self.is_updated = [False] * self.N
    
    
    def update(self) -> None:
        for _ in range(self.N - 1):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
    
    
    def detection(self) -> bool:
        for v, s in enumerate(self.to):
            if not s: continue
            for nv, w in s:
                if self.dist[nv] > self.dist[v] + w:
                    self.dist[nv] = self.dist[v] + w
                    self.exists_negative_cycle = True
        return self.exists_negative_cycle
    
    
    def detection_stog(self) -> bool:
        for _ in range(self.N):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
                        self.is_updated[nv] = True
                    if self.is_updated[v] is True:
                        self.is_updated[nv] = True
        self.exists_negative_cycle_stog = self.is_updated[self.goal]
        return self.exists_negative_cycle_stog

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

BF = Bellmanford(to, 0, N-1)
BF.update()

if BF.detection_stog():
    ans = -1
else:
    ans = max(-BF.dist[N-1], 0)

print(ans)

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

es = []

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

INF = float("inf")

d = [INF for _ in range(N)] 
d[0] = 0
"""
頂点Nに向かうまでに関係ない閉路に注意する

無限にコインを拾える場合、
・ある閉路を一周したときの得点と支払いの収支がプラス
・その閉路からゴールまで行ける
である。これがない場合、全てのノードを経由してゴールまで行く（N-1回移動）までにコインの枚数が最大になる
なので、一回ベルマンフォード法をやった後もう一回行って一回目と２回目でゴールまでのコイン枚数に変化があればゴ、
ールに行くまでの道に無限にコインをとれる閉路があるといえる

"""

def solve(start, f):
    for i in range(N):
        for a,b,c, in es:
            if d[a] != INF and d[a] + (-c) + P < d[b]:
                
                if f == 0:
                    d[b] = d[a] + (-c) + P
                else:
                    d[b] = -INF


    return d[-1]


first=solve(0,0)
second=solve(0, 1)
if first != second:
    print(-1)
else:
    print(max(-first, 0))

Solution (Python):
inf = float('inf')




def bellmanford(n : int, edges : list, start : int, goal : int) -> (list, bool):
    dist = [inf] * n
    dist[start] = 0
    exist_negative_cycle = False

    
    for _ in range(n-1):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w


    
    
    
    
    

    
    is_updated = [False] * n
    for _ in range(n):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w
                is_updated[nv] = True
            if is_updated[v] is True:
                is_updated[nv] = True

    exist_negative_cycle = is_updated[goal]

    return dist, exist_negative_cycle

N, M, P = map(int,input().split())
edges = []
for _ in range(M):
    A, B, C = map(int,input().split())
    A -= 1; B -= 1
    C = C - P
    edges.append((A, B, -C))
 
dist, exist_negative_cycle = bellmanford(N, edges, 0, N-1)
 
if exist_negative_cycle is True:
    ans = -1
else:
    ans = max(-dist[N-1], 0)
 
print(ans)

Solution (Python):
inf = float('inf')




def bellmanford(n : int, edges : list, start : int, goal : int) -> (list, bool):
    dist = [inf] * n
    dist[start] = 0
    exist_negative_cycle = True

    
    for _ in range(N-1):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w


    
    
    
    
    

    
    is_updated = [False] * n
    for _ in range(N):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w
                is_updated[nv] = True
            if is_updated[v] is True:
                is_updated[nv] = True

    exist_negative_cycle = is_updated[goal]

    return dist, exist_negative_cycle

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

dist, exist_negative_cycle = bellmanford(N, edges, 0, N-1)

if exist_negative_cycle is True:
    ans = -1
else:
    ans = max(-dist[N-1], 0)

print(ans)

Solution (Python):

def reachable_nodeset(start, inc):
  reachable = set()
  reachable.add(start)
  nodes = [start]
  
  while nodes:
    n = nodes.pop()
    for i in inc[n]:
      if i not in reachable:
        nodes.append(i)
        reachable.add(i)
  return reachable

def bellmanford(num, start, goal, edges):
  cost = [float('inf')]*num
  cost[start] = 0
  
  for _ in range(num):
    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 -1
  return max(0, -cost[goal])

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

for _ in range(M):
  a, b, c = map(int, input().split())
  a -= 1
  b -= 1
  c = -(c-P)
  
  to[a].append(b)
  ot[b].append(a)
  edges.append((a,b,c))
  
reachableFromZero = reachable_nodeset(0, to)  
reachableToN = reachable_nodeset(N-1, ot)  
ok = reachableFromZero.intersection(reachableToN)
edges = tuple((a,b,c) for a,b,c in edges if a in ok and b in ok)

print(bellmanford(N, 0, N-1, edges))

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
from collections import deque
def resolve():
    n,m,p=map(int,input().split())
    E=[[] for _ in range(n)]
    R=[[] for _ in range(n)]
    edges=[]
    for _ in range(m):
        a,b,c=map(int,input().split())
        a-=1; b-=1
        E[a].append(b)
        R[b].append(a)
        edges.append((a,b,p-c))

    state=[0]*n
    state[0]=1
    state[n-1]=2

    Q=deque([0])
    while(Q):
        v=Q.popleft()
        for nv in E[v]:
            if(state[nv]&1): continue
            state[nv]+=1
            Q.append(nv)

    Q=deque([n-1])
    while(Q):
        v=Q.popleft()
        for nv in R[v]:
            if(state[nv]&2): continue
            state[nv]+=2
            Q.append(nv)

    dist=[INF]*n
    dist[0]=0
    for k in range(n):
        for a,b,w in edges:
            if(state[a]!=3 or state[b]!=3): continue
            if(dist[b]>dist[a]+w):
                dist[b]=dist[a]+w
                if(k==n-1):
                    print(-1)
                    return
    print(max(-dist[-1],0))
resolve()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,m,p=map(int,input().split())
    E=[[] for _ in range(n)]
    R=[[] for _ in range(n)]
    edges=[]
    for _ in range(m):
        a,b,c=map(int,input().split())
        a-=1; b-=1
        E[a].append(b)
        R[b].append(a)
        edges.append((a,b,p-c))

    state=[0]*n

    def dfs(v):
        if(state[v]&1): return
        state[v]+=1
        for nv in E[v]: dfs(nv)
    dfs(0)

    def rdfs(v):
        if(state[v]&2): return
        state[v]+=2
        for nv in R[v]: rdfs(nv)
    rdfs(n-1)

    dist=[INF]*n
    dist[0]=0
    for k in range(n):
        for a,b,w in edges:
            if(state[a]!=3 or state[b]!=3): continue
            if(dist[b]>dist[a]+w):
                dist[b]=dist[a]+w
                if(k==n-1):
                    print(-1)
                    return
    print(max(-dist[-1],0))
resolve()

Solution (Python):
n,m,p=map(int,input().split())
data=[list(map(int,input().split())) for i in range(m)]
inf=float("inf")
dist=[-inf]*(n+1)
dist[1]=0
for i in range(n-1):
    for a,b,c in data:
        if dist[a]!=-inf:
            dist[b]=max(dist[b],dist[a]+c-p)
lst=[]
for a,b,c in data:
    if dist[b]<dist[a]+c-p:
        lst.append(b)

tag=[[] for i in range(n+1)]
for a,b,c in data:
    tag[a].append(b)
flag=[0]*(n+1)
for u in lst:
    if flag[u]==0:
        flag[u]=1
        que=[u]
        while que:
            h=que.pop()
            for v in tag[h]:
                if flag[v]==0:
                    que.append(v)
                    flag[v]=1
if flag[n]==1:
    print(-1)
else:
    print(max(0,dist[n]))

Solution (Python):
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];d=[0]*2+[9e99]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[d[a]-c+p,-9e99][i>n]
 if i==n:x=d[n]
print([max(-x,0),-1][d[n]!=x])

Solution (Python):
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];I=float('inf');d=[0]*2+[I]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[d[a]-c+p,-I][i>n]
 if i==n:x=d[n]
print([max(-x,0),-1][d[n]!=x])

Solution (Python):
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];I=float('inf');d=[0]*2+[I]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[min(d[b],d[a]-c+p),-I][i>n]
 if i==n:x=d[n]
print([max(-d[n],0),-1][d[n]!=x])

Solution (Python):
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
I=float('inf')
d=[0]*2+[I]*n
for i in range(n-1):
  for a,b,c in l:
    d[b]=min(d[b],d[a]-c+p)
x=d[n]
for i in range(n):
  for a,b,c in l:
    if d[b]>d[a]-c+p:d[b]=-I
print([max(-d[n],0),-1][d[n]!=x])

Solution (Python):
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
distance=[float('inf')]*n
distance[0]=0
for i in range(n-1):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=distance[l[j][0]-1]-l[j][2]+p
x=distance[n-1]
for i in range(n):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=-float('inf')
if distance[n-1]!=x:
  print(-1)
else:
  print(max(-distance[n-1],0))

Solution (Python):
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
distance=[float('inf')]*n
distance[0]=0
for i in range(n-1):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=distance[l[j][0]-1]-l[j][2]+p
x=distance[n-1]
for i in range(n):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=-float('inf')
if distance[n-1]!=x:
  print(-1)
elif x>0:
  print(0)
else:
  print(max(-distance[n-1],0))

Solution (Python):
INF = float("inf")

def bellman_ford(edges, n, s):
    d = [0] + [INF] * (n-1)
    for i in range(n):
        for f, t, c in edges:
            if d[f] == INF: continue
            if d[t] > d[f] + c:
                if i == n-1: d[t] = -INF
                else: d[t] = d[f] + c
    for i in range(n):
        for f, t, c in edges:
            if d[f] == INF: continue
            d[t] = min(d[t], d[f] + c)
    return d

n, m, p = map(int, input().split())
es = [None] * m
for i in range(m):
    f, t, c = map(int, input().split())
    es[i] = (f-1, t-1, -(c-p))

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

Solution (Python):
from collections import deque
n,m,p=map(int,input().split())
edges=[None for i in range(m)]
natural=[[] for i in range(n)]
reverse=[[] for i in range(n)]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1;b-=1;c-=p
  natural[a].append(b)
  reverse[b].append(a)
  edges[i]=(a,b,-c)
from0=set([0])
fromG=set([n-1])
visited=[False]*n
visited[0]=True
queue=deque([0])
while queue:
  v=queue.popleft()
  for i in natural[v]:
    if visited[i]:continue
    visited[i]=True
    from0.add(i)
    queue.append(i)
for i in range(n):
  visited[i]=False
visited[-1]=True
queue.append(n-1)
while queue:
  v=queue.popleft()
  for i in reverse[v]:
    if visited[i]:continue
    visited[i]=True
    fromG.add(i)
    queue.append(i)
points=from0&fromG
use=[]
for i in edges:
  if i[0] in points and i[1] in points:
    use.append(i)
def BellmanFord(edges,num_v,source):
  
  inf=10**15
  global dist
  dist=[inf for i in range(num_v)]
  dist[source]=0
  Ncycle=False
  
  for i in range(num_v):
    for edge in edges:
      if edge[0]!=inf and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1: return False
  
  return dist[-1]
flag=0
for i in use:
  if i[2]!=0:
    flag=1
    break
if flag==0:print(0);exit()
if BellmanFord(use,n,0)==False:print(-1)
else:
  print(max(0,-BellmanFord(use,n,0)))

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')


def A():
    a, b = LI()
    print(max(a + b, a - b, a * b))
    return


def B():
    k, x = LI()
    ans = []
    for i in range(x - k + 1, x + k):
        ans.append(i)
    print(*ans)
    return


def C():
    n = II()
    d = defaultdict(int)
    for _ in range(n):
        s = S()
        s.sort()
        d[tuple(s)] += 1
    ans = 0
    for i in d.values():
        ans += i * (i - 1) // 2
    print(ans)
    return





def D():
    n, m = LI()
    q = []
    d = defaultdict(list)
    ans = 0
    for _ in range(n):
        a, b = LI()
        d[a].append(b)
    for i in range(m):
        for di in d[i+1]:
            heappush(q, -di)
        if q:
            ans -= heappop(q)
    print(ans)
    return


def E():
    n,m,p = LI()
    dag = [-inf] * n
    edg = LIR_(m)
    dag[0] = 0
    for i in range(n):
        for a, b, c in edg:
            c += 1
            c -= p
            if dag[a] + c > dag[b]:
                dag[b] = dag[a] + c
    ans = dag[n - 1]
    for i in range(n):
        for a, b, c in edg:
            c += 1
            c -= p
            if dag[a] + c > dag[b]:
                dag[b] = inf
    if ans != dag[n - 1]:
        print(-1)
    else:
        print(max(ans, 0))

    return


def F():
    return


if __name__ == '__main__':
    E()

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

def main():
    N, M, P = map(int, input().split())
    Edges = [list(map(int, input().split())) for _ in range(M)]
    INF = 10**18

    graph1 = [[] for _ in range(N+1)]
    graph2 = [[] for _ in range(N+1)]
    for a, b, c in Edges:
        graph1[a].append(b)
        graph2[b].append(a)

    checked1 = [False]*(N+1)
    checked1[1] = True
    q = [1]
    while q:
        qq = []
        for p in q:
            for np in graph1[p]:
                if not checked1[np]:
                    checked1[np] = True
                    qq.append(np)
        q = qq
    
    checked2 = [False]*(N+1)
    checked2[N] = True
    q = [N]
    while q:
        qq = []
        for p in q:
            for np in graph2[p]:
                if not checked2[np]:
                    checked2[np] = True
                    qq.append(np)
        q = qq
    
    Canuse = [False]*(N+1)
    for i in range(1, N+1):
        if checked1[i] and checked2[i]:
            Canuse[i] = True



    D = [INF for _ in range(N+1)]
    D[1] = 0
    for i in range(2*N+100):
        update = False
        for a, b, c in Edges:
            if not Canuse[a] or not Canuse[b]: continue
            if D[b] > D[a] + P - c:
                D[b] = D[a] + P - c
                update = True


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

if __name__ == "__main__":
    main()

Solution (Python):


import sys
n,m,p = map(int, input().split( ))
E = [[] for _ in range(n)]
inf = 10**12
for _ in range(m):
    a,b,c = map(int, input().split( ))
    E[a-1].append([b-1,p-c])


D = [inf for _ in range(n)]
D[0] = 0
for _ in range(n):
    for ve in range(n):
        for ed in E[ve]:
            D[ed[0]] = min(D[ed[0]], D[ve] + ed[1])


for _ in range(n+10):
    for ve in range(n):
        for ed in E[ve]:
            if D[ed[0]] > D[ve] + ed[1] and D[ed[0]]<inf//10:
                
                D[ed[0]] = -inf

"""
for i in range(n):
    if E[i]:
        for ed in E[i]:
            if D[i] + ed[1] < D[ed[0]] and D[ed[0]]<inf//10:
                print(-1)
                sys.exit()
"""

if D[n-1]>-inf//10:
    print(max(0,-D[n-1]))
else:
    print(-1)

Solution (Python):




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

el = []
for _ in range(m):
    a,b,c = map(int,input().split())
    el.append((a-1,b-1,c-p))
cost = [-float("inf") for _ in range(n)]
cost[0] = 0
for i in range(2*n):
    for j in range(m):
        e = el[j]
        if cost[e[1]] < cost[e[0]] + e[2]:
            cost[e[1]] = cost[e[0]] + e[2]
            if i >= n:
                cost[e[1]] = float("inf")
    if i == n-1:
        ans = cost[-1]
        
              
if ans != cost[-1]:
    print(-1)
else:
    print(max(ans, 0))

Solution (Python):
N, M, P = map(int, input().split())
E = [None] * M
for i in range(M):
    a, b, c = map(int, input().split())
    E[i] = (a - 1, b - 1, P - c)
INF = float("inf")
d = [INF for _ in range(N)]
d[0] = 0
for i in range(2*N):
    for f, t, w in E:
        if d[t] > d[f] + w:
            d[t] = d[f] + w
            if i >= N:
                d[t] = -INF
    if i == N-1:
        dN = d[-1]
if dN != d[-1]:
    print(-1)
elif dN > 0:
    print(0)
else:
    print(-dN)

Solution (Python):
from collections import deque
N, M, P = map(int, input().split())
E1 = [[] for _ in range(N)]
E2 = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    E1[a-1].append((b-1, P-c))
    E2[b-1].append((a-1, P-c))

def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c, d in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return D

def bellman_ford_chk(n, E, s=0):
    D = [0] * n
    for k in range(n):
        for i in range(n):
            for j, c in E[i]:
                if D[j] > D[i] + c:
                    D[j] = D[i] + c
                    if k == n-1: return 1
    return 0
def bellman_ford_calc(n, E, s=0):
    D = [1<<100] * n
    D[s] = 0
    f = 1
    while f:
        f = 0
        for i in range(n):
            for j, c in E[i]:
                if D[i] < 1<<100 and D[j] > D[i] + c:
                    D[j] = D[i] + c
                    f = 1
    return D
D1 = BFS(N, E1, 0)
D2 = BFS(N, E2, N-1)
L = [i for i in range(N) if D1[i] >= 0 and D2[i] >= 0]

NN = len(L)
LL = [-1] * N
for i in range(NN):
    LL[L[i]] = i

E3 = [[(LL[a], c) for a, c in E1[i] if LL[a] >= 0] for i in range(N) if LL[i] >= 0]
if bellman_ford_chk(NN, E3, 0):
    print(-1)
else:
    print(max(-bellman_ford_calc(NN, E3, 0)[-1], 0))

Solution (Python):
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
c=[[] for i in range(N)]
v=[0]*N
for a,b,_ in ABC:
    c[a-1].append(b-1)
q=[0]
while q:
    p=q.pop()
    if v[p]==0:
        v[p]=1
        for n in c[p]:
            if n!=p:
                q.append(n)
inf=10**20
f=lambda i,j,w: [i-1,j-1,P-w]
edge=[f(i,j,w) for i,j,w in ABC if v[i-1]]
def bf(N,s):
    d=[inf]*N
    d[s]=0
    prev=[-1]*N
    for i in range(N-1):
        f=0
        for i,j,w in edge:
            if d[j]>d[i]+w:
                d[j]=d[i]+w
                prev[j]=i
                f=1
        if f==0:
            break
    while True:
        f=0
        for i,j,w in edge:
            if d[j]>d[i]+w and (d[j]!=-inf or d[i]!=-inf):
                d[i]=d[j]=-inf
                f=1
        if f==0:
            break
    return d
d=bf(N,0)
print(max(0,-d[-1]) if d[-1]>-inf else -1)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 18
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, m, p = LI()
G = [[] for _ in range(n)]
for i in range(m):
    a, b, c = LI()
    G[a - 1] += [(b - 1, c - p)]


def bellman_ford(G, start=0):
    n = len(G)
    costs = [-INF] * n
    costs[0] = 0
    v_nows = set([start])
    for _ in range(n):
        v_changeds = set()
        for u in v_nows:
            for v, c in G[u]:
                if costs[u] + c > costs[v]:
                    costs[v] = costs[u] + c
                    v_changeds.add(v)
        v_nows = v_changeds
    if not v_changeds:
        return costs[n - 1]

    for i in v_nows:
        costs[i] = -INF
    que = deque(v_nows)
    while que:
        u = que.popleft()
        for v, cost in G[u]:
            if costs[v] != -INF:
                costs[v] = -INF
                que += [v]
    return costs[n - 1]


cost = bellman_ford(G, 0)
if cost == -INF:
    print(-1)
else:
    print(max(0, cost))

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

adj = [list() for _ in range(N)]
inv = [list() for _ in range(N)]
edges = []

for _ in range(M):
    a,b,c = map(int,input().split())
    inv[b-1].append(a-1)
    adj[a-1].append(b-1)
    edges.append((a-1,b-1,P-c))

stack = [N-1]
reachable1 = {N-1}
while stack:
    v = stack.pop()
    for u in inv[v]:
        if u not in reachable1:
            stack.append(u)
            reachable1.add(u)

stack = [0]
reachable2 = {0}
while stack:
    v = stack.pop()
    for u in adj[v]:
        if u not in reachable2:
            stack.append(u)
            reachable2.add(u)

reachable = reachable1 & reachable2
edges = [(a,b,w) for a,b,w in edges if a in reachable and b in reachable]

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

for i in range(len(reachable)-1):
    for a,b,w in edges:
        dist[b] = min(dist[a]+w, dist[b])


for a,b,w in edges:
    if dist[b] > dist[a] + w:
        print(-1)
        break
else:
    print(max(0,-dist[-1]))

Solution (Python):

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

    
    buf = 0
    for i in range(num_v * 2):
        for edge in edges:
            if dist[edge[1] - 1] < dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i >= num_v:
                    dist[edge[1] - 1] = inf
        if i == num_v - 1:
            buf = dist[-1]
    if dist[-1] != buf or dist[-1] == -inf:
        return -1
    return max(dist[-1], 0)

import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = []

N, M, P = LI()
cou = int(0)
maxC = 10000
d = [[float("inf") for i in range(N)] for i in range(N)]

V = []*M
for i in range(M):
    a, b, c = list(map(int,input().split()))
    V.append((a,b,c-P))
print(BellmanFord(V, N, 1))

Solution (Python):

import sys
input = sys.stdin.buffer.readline


from collections import defaultdict
import queue
import copy

INF = float("inf")

def getlist():
	return list(map(int, input().split()))

def Bellman_Ford(N, E, G, dist):
	for i in range(N):
		for a, b, w in G:
			if dist[b] > dist[a] + w:
				dist[b] = dist[a] + w

class Graph(object):
    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, a, b):
        self.graph[a].append(b)

    def get_nodes(self):
        return self.graph.keys()

class BFS(object):
	def __init__(self, graph, s, N):
		self.g = graph.graph
		self.Q = queue.Queue()
		self.Q.put(s)
		self.dist = [INF] * N
		self.dist[s] = 0
		self.visit = ["No"] * N
		self.visit[s] = "Yes"
		while not self.Q.empty():
			v = self.Q.get()
			for i in self.g[v]:
				if self.visit[i] == "No":
					self.dist[i] = self.dist[v] + 1
					self.Q.put(i)
					self.visit[i] = "Yes"


def main():
	N, M, P = getlist()
	dist = [INF] * N
	dist[0] = 0
	G = []
	D = Graph()
	Drev = Graph()
	for i in range(M):
		a, b, w = getlist()
		G.append([a - 1, b - 1, P - w])
		D.add_edge(a - 1, b - 1)
		Drev.add_edge(b - 1, a - 1)
	
	
	BF = BFS(D, 0, N)
	BFrev = BFS(Drev, N - 1, N)
	check1 = BF.visit
	check2 = BFrev.visit
	judge = ["No"] * N
	for i in range(N):
		if check1[i] == "Yes" and check2[i] == "Yes":
			judge[i] = "Yes"

	
	Bellman_Ford(N, M, G, dist)
	d1 = copy.copy(dist)
	Bellman_Ford(N, M, G, dist)
	d2 = dist

	

	judge_ans = "No"
	for i in range(N):
		if judge[i] == "Yes" and d1[i] != d2[i]:
			judge_ans = "Yes"
			break
	if judge_ans == "Yes":
		print(-1)
	else:
		print(max(-dist[-1] , 0))

if __name__ == '__main__':
	main()