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):
def bellmanford(v,s,path):
    
    d = [float('inf')]*v

    
    d[s] = 0
    for j in range(v):
        update = False

        
        
        for a,b,c in path:
            if d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True

        
        if not update:
            break
        
        
        elif j == v-1:
            return -1

    return d

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

path = [[] for i in range(n)]
path_inv = [[] for i in range(n)]

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

a = [0]*n
s = 0
a[0]=1
stack = [s]
while stack:
    p = stack.pop()
    for q,r in path[p]:
        if a[q]==0:
            a[q]=1
            stack.append(q)

b = [0]*n
g = n-1
b[n-1]=1
stack = [g]
while stack:
    p = stack.pop()
    for q,r in path_inv[p]:
        if b[q]==0:
            b[q]=1
            stack.append(q)

c = [i for i in range(n) if a[i]==b[i]==1]

path2 = []
for i in c:
    for to,cost in path[i]:
        path2.append([i,to,cost])

d = bellmanford(n,0,path2)
if d==-1:
    print(-1)
else:
    print(max(0,-d[-1]))

Solution (Python):
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

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


reach1 = [False] * (N + 1)
reach1[1] = True
node = [1]
while node:
    s = node.pop()
    for t, _ in edge[s]:
        if not reach1[t]:
            reach1[t] = True
            node.append(t)

reach2 = [False] * (N + 1)
reach2[N] = True
node = [N]
while node:
    s = node.pop()
    for t in ein[s]:
        if not reach2[t]:
            reach2[t] = True
            node.append(t)

can_go = []
Vertices = []
for i, (x, y) in enumerate(zip(reach1, reach2)):
    can_go.append(x & y)
    if x & y:
        Vertices.append(i)


inf = 10**18
cost = [inf] * (N + 1)
cost[1] = 0
for _ in range(M + 5):
    update = False
    for s in Vertices:
        now = cost[s]
        for t, c in edge[s]:
            if not can_go[t]:
                continue
            if cost[t] > now + c:
                cost[t] = now + c
                update = True


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

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

def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return -1
  return max(-d[n-1],0)

from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

def glaph_bfs(s,n,e):
  ans=[0]*n
  Q=[s]
  visited={s}
  while Q:
    P=[]
    for i in Q:
      ans[i]=1
      for j in e[i]:
        if j in visited:continue
        visited.add(j)
        P.append(j)
    Q=P
  return ans

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append((a,b,c))
eff=glaph_bfs(0,n,ef)
eef=glaph_bfs(n-1,n,ee)
ee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    ee.append((a,b,-c))
print(find_negative_loop(n,ee))

Solution (Python):

import sys
input=sys.stdin.readline
sys.setrecursionlimit(10000000)



def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return -1
  return max(-d[n-1],0)




from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append((a,b,c))
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
ee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    ee.append((a,b,-c))
print(find_negative_loop(n,ee))

Solution (Python):


def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False




from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t




def bellman_ford(s,n,e):
	inf=10**20;d=[inf]*n;d[s]=0
	while 1:
		f=True
		for i,j,k in e:
			if d[i]!=inf and d[j]>d[i]+k:d[j]=d[i]+k;f=False
		if f:break
	return d



def glaph_bfs(s,n,e):
  ans=[0]*n
  Q=[s]
  visited={s}
  while Q:
    P=[]
    for i in Q:
      ans[i]=1
      for j in e[i]:
        if j in visited:continue
        visited.add(j)
        P.append(j)
    Q=P
  return ans

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append([a,b,c])
eff=glaph_bfs(0,n,ef)
eef=glaph_bfs(n-1,n,ee)
edge=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    edge.append([a,b,-c])
if find_negative_loop(n,edge):print(-1);exit()
print(max(-bellman_ford(0,n,edge)[n-1],0))

Solution (Python):




def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False




from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t




def bellman_ford(s,n,e):
	inf=10**20;d=[inf]*n;d[s]=0
	while 1:
		f=True
		for i,j,k in e:
			if d[i]!=inf and d[j]>d[i]+k:d[j]=d[i]+k;f=False
		if f:break
	return d

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append([a,b,c])
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
edge=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    edge.append([a,b,-c])
if find_negative_loop(n,edge):print(-1);exit()
print(max(-bellman_ford(0,n,edge)[n-1],0))

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

N, M, P = map(int, input().split())
edges = [None] * M
for i in range(M):
    A, B, C = map(int, input().split())
    edges[i] = (A, B, P-C)

dist = [float('inf')] * (N+1)
dist[1] = 0
for i in range(N-1):
    for u, v, weight in edges:
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
negative = [False] * (N+1)
for i in range(N):
    for u, v, weight in edges:
        if negative[u]:
            negative[v] = True
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
            negative[v] = True
print(max(-dist[N], 0) if not negative[N] else -1)

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

def dfs(edges, s):
    use = {s}
    stack = [s]
    while stack:
        v = stack.pop()
        for w in edges[v]:
            if w in use: continue
            use.add(w)
            stack.append(w)
    return use

def bellmanford(num_v, edges, source):
    inf = float('inf')
    dist = [inf] * num_v
    dist[source] = 0
    for i in range(num_v):
        flag = False
        for s, t, cost in edges:
            if dist[s] == inf: continue
            if dist[s] + cost < dist[t]:
                dist[t] = dist[s] + cost
                flag = True
        if not flag: break
    else:
        return False
    return dist

def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    G_rev = [[] for _ in range(N)]
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append(b)
        G_rev[b].append(a)
        edges.append((a, b, P-c))
    
    use = dfs(G_rev, N-1)
    edges = [(a, b, c) for a, b, c in edges if a in use and b in use]
    dist = bellmanford(N, edges, 0)
    if dist:
        print(max(0, -dist[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Solution (Python):
N, M, P = map(int, input().split())
INF = 10**18

edges = []
E = [[] for _ in range(N)]
R = [[] for _ in range(N)]
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    edges.append((fr, to, -(c - P)))
    E[fr].append(to)
    R[to].append(fr)

def existsPath(s, edges):
    visited = [False] * N
    visited[s] = True
    st = [s]
    while st:
        now = st.pop()
        for to in edges[now]:
            if visited[to]:
                continue
            st.append(to)
            visited[to] = True
    return visited

canGoFrom1 = existsPath(0, E)
canGoFromN = existsPath(N - 1, R)

minDist = [INF] * N
minDist[0] = 0
for i in range(N):
    for fr, to, c in edges:
        d = minDist[fr] + c
        if minDist[to] > d:
            if i == N - 1 and canGoFrom1[fr] and canGoFromN[to]:
                print('-1')
                exit()
            minDist[to] = d

print(max(0, -minDist[N - 1]))

Solution (Python):
from collections import deque


def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if (not reach[nxt_v]) or (not rev_reach[nxt_v]):
                    continue
                if dist[v] != INF and dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            return dist[n - 1]
    return -INF


n, m, p = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
rev_graph = [[] for i in range(n)]
for a, b, cost in info:
    a -= 1
    b -= 1
    graph[a].append((b, -(cost - p)))
    rev_graph[b].append(a)

reach = [False] * n
reach[0] = True
q = deque([0])
while q:
    v = q.popleft()
    for nxt_v, _ in graph[v]:
        if reach[nxt_v]:
            continue
        reach[nxt_v] = True
        q.append(nxt_v)
        
rev_reach = [False] * n
rev_reach[n - 1] = True
q = deque([n - 1])
while q:
    v = q.popleft()
    for nxt_v in rev_graph[v]:
        if rev_reach[nxt_v]:
            continue
        rev_reach[nxt_v] = True
        q.append(nxt_v)

dist = bellman_ford(0, graph)
if dist == -float("inf"):
    print(-1)
else:
    print(max(-dist, 0))

Solution (Python):
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,P-c))
    rs[b].append(a)

stack = [0]
govisit = set([0])
while stack:
    v = stack.pop()
    for to,_ in es[v]:
        if to in govisit: continue
        govisit.add(to)
        stack.append(to)

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

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for fr,e in enumerate(es):
        if fr not in use: continue
        for to,c in e:
            if to not in use: continue
            if dist[to] > dist[fr] + c:
                dist[to] = dist[fr] + c
                if i==N-1:
                    print(-1)
                    exit()
print(max(0,-dist[-1]))

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

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


def find_negative_loop(s,n,w,es):
    
    
    
    

    
    inf = float('inf')
    d = [inf for _ in range(n)]
    d[s] = 0
    for i in range(2*n):
        for j in range(w):
            p, q, r = es[j]
            if d[p] != inf and (d[q] > d[p] + r):
                d[q] = d[p] + r
                if i >= n:
                    d[q] = (-1)*inf
        if i == n-1:
            temp = d[-1]
    return temp, d[-1]

temp, d = find_negative_loop(0, n, m, es)
if temp == d:
    if temp > 0:
        print(0)
    else:
        print(-temp)
else:
    print(-1)

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
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)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dfs(x,f):
        dx = d[x]
        for y,c in v[x]:
            if not f[y]:
                nd = dx+c
                if d[y] < nd:
                    d[y] = nd
                    f[y] = 1
                    dfs(y,f)
                    f[y] = 0
            else:
                nd = dx+c
                if nd > d[y]:
                    d[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        w = c-p
        v[a].append((b,w))
    d = [-float("inf")]*n
    d[0] = 0
    f = [0]*n
    f[0] = 1
    dfs(0,f)
    ans = d[n-1]
    if ans == float("inf") or ans == -float("inf"):
        print(-1)
    else:
        print(max(0,ans))
    return


if __name__ == "__main__":
    solve()

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


def BellmanFord(edges, v, source):
    INF = float("inf")
    dist = [INF for _ in range(v)]
    dist[source] = 0
    for i in range(2 * v + 1):
        for now, fol, cost in edges:
            if dist[now] != INF and dist[fol] > dist[now] + cost:
                dist[fol] = dist[now] + cost
                if i >= v:
                    dist[fol] = -INF
    if dist[-1] == -INF:
        return -1
    else:
        return max(0, -dist[-1])


n, m, p = map(int, readline().split())
abc = [list(map(int, readline().split())) for i in range(m)]
edges = []
for a, b, c in abc:
    edges.append((a - 1, b - 1, p - c))
print(BellmanFord(edges, n, 0))

Solution (Python):
import queue as qu
def BFS(connectinons:list,N):
    bfs_connections=[[] for _ in range(N)]
    reverse_connections=[[] for _ in range(N)]


    for A,B,_ in connectinons:
        bfs_connections[A].append(B)
        reverse_connections[B].append(A)
    
    reachable= [False]*N
    rev_reachable=[False]*N

    q = qu.Queue()
    q.put(0)

    while not q.empty():
        node = q.get()
        if reachable[node]:
            continue
        reachable[node]=True

        for B in bfs_connections[node]:
            q.put(B)
    
    q = qu.Queue()
    q.put(N-1)

    while not q.empty():
        node = q.get()
        if rev_reachable[node]:
            continue
        rev_reachable[node]=True

        for B in reverse_connections[node]:
            q.put(B)

    use=set()
    for i in range(N):
        if reachable[i] and rev_reachable[i]:
            use.add(i)
        
    return [[a,b,c] for a,b,c in connectinons if a in use and b in use]









def b_ford(connections:list,N):
    inf=float('inf')
    cost =[inf]*N
    cost[0]=0
    newchanged = set()
    oldchanged = set()

    for i in range(N):
        oldchanged=newchanged
        newchanged= set()
        for A,B,C in connections:
            if cost[A]+C < cost[B]:
                newchanged.add(B)
                cost[B]=cost[A]+C
        
        if not newchanged:
            if cost[-1] > 0:
                print(0)
            else:
                print(-cost[-1])
            return
    print(-1)







def resolve():
    N,M,P = map(int,input().split())
    
    connections = []
    for i in range(M):
        A,B,C = map(int,input().split())
        
        connections.append([A-1,B-1,P-C])
    
    connections = BFS(connections,N)
    
    b_ford(connections,N)

resolve()

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

from collections import deque



def bellman_ford(links, start, end, n):
    inf = 10**10
    d = [inf] * (n+1)
    d[start] = 0
    parent = [-1] * (n+1)

    for _ in range(n):
        update = False
        for i in range(1,n+1):
            for j in links[i]:
                cost,neigh = j
                if(d[neigh] > d[i] + cost):
                    d[neigh] = d[i] + cost
                    parent[neigh] = i
                    update = True

        if(not update):
            
            route = [end]
            now = end
            while(now != start):
                now = parent[now]
                route.append(now)

            return d,route[::-1]

    
    return -1,-1

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

can_go_1 = set()
can_go_n = set()

d = deque()
d.append(1)
while(d):
    tmp = d.pop()
    can_go_1.add(tmp)
    for i in graph[tmp]:
        if(not i in can_go_1):
            d.append(i)

d = deque()
d.append(n)
while(d):
    tmp = d.pop()
    can_go_n.add(tmp)
    for i in graph_rev[tmp]:
        if(not i in can_go_n):
            d.append(i)

can_go = can_go_1 & can_go_n

graph2 = [[] for _ in range(n+1)]
for tmp in abc:
    a,b,c = tmp
    if(a in can_go)&(b in can_go):
        graph2[a].append((c,b))

d , _ = bellman_ford(graph2, 1, n, n)
if(d == -1):
    print(-1)
else:
    ans = d[n] * -1
    print(max(0,ans))

Solution (Python):
import sys
input = sys.stdin.readline
n, m, p = map(int, input().split())
edges = []
forward_edges = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append((a, b, p-c))
    forward_edges[a].append(b)


can_reach = [0]*n
stack = [0]
while stack:
    v = stack.pop()
    if can_reach[v]:
        continue
    can_reach[v] = 1
    for v2 in forward_edges[v]:
        if can_reach[v2]:
            continue
        stack.append(v2)


INF = 10**10
dist = [INF]*n
dist[0] = 0
for i in range(n):
    for v, v2, c in edges:
        if dist[v2] <= dist[v]+c:
            continue
        dist[v2] = dist[v]+c

negative = [0]*n
for i in range(n):
    for v, v2, c in edges:
        if dist[v2] <= dist[v]+c:
            continue
        if not can_reach[v2]:
            continue
        dist[v2] = -INF
        negative[v2] = 1

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

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

def main():
    N,M,P = map(int,input().split())
    
    def BellmanFord(edges,v,source):
        INF = float("inf")
        dist = [INF for _ in range(v)]
        dist[source] = 0
        for i in range(2*v+1):
            for now,fol,cost in edges:
                if (dist[now] != INF and dist[fol]>dist[now]+cost):
                    dist[fol] = dist[now]+cost
                    if i >= v:
                        dist[fol] = -INF
        if dist[v-1] == -INF:
            return -1
        else:
            return max(0,-1*dist[v-1])
    
    edges = []
    for _ in range(M):
        a,b,c = map(int,input().split())
        edges.append((a-1,b-1,P-c))
    
    print(BellmanFord(edges,N,0))

if __name__ == "__main__":
    main()

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

def main():
    N,M,P = map(int,input().split())
    
    def BellmanFord(edges,v,source):
        INF = float("inf")
        dist = [-INF for _ in range(v)]
        dist[source-1] = 0
        for i in range(2*v+1):
            for now,fol,cost in edges:
                b = dist[v-1]
                if (dist[now] != -INF and dist[fol]<dist[now]+cost):
                    dist[fol] = dist[now]+cost
                    if i > v-1:
                        dist[fol] = INF
        if dist[N-1] == INF:
            return -1
        else:
            return max(0,dist[N-1])
    
    edges = []
    for _ in range(M):
        a,b,c = map(int,input().split())
        edges.append((a-1,b-1,c-P))
    
    print(BellmanFord(edges,N,1))

if __name__ == "__main__":
    main()

Solution (Python):
n, m, p = map(int, input().split())
abcs = [list(map(int, input().split())) for _ in range(m)]
distance = [-1000000 * n] * (n + 1)

distance[1] = 0
reachable1 = set([1])
reachableN = set([n])
for _ in range(n + 1):
    for a, b, c in abcs:
        if distance[b] < distance[a] + c - p:
            distance[b] = distance[a] + c - p
        
        if a in reachable1:
            reachable1.add(b)
        if b in reachableN:
            reachableN.add(a)

for a, b, c in abcs:
    if (distance[b] < distance[a] + c - p) and (a in reachable1) and (b in reachableN):
        print(-1)
        exit(0)

print(max(distance[n], 0))

Solution (Python):
import sys
input = sys.stdin.readline
n,m,p = map(int,input().split())
abd = [list(map(int,input().split())) for i in range(m)]
come = [[] for i in range(n+1)]
for a,b,d in abd:
  come[b].append(a)
visitable = [0]*(n+1)
stack = [n]
visitable[n] = 1
while stack:
  x = stack.pop()
  for y in come[x]:
    if visitable[y] == 0:
      visitable[y] = 1
      stack.append(y)
score = [10**15 for i in range(n+1)]
score[1] = 0
for j in range(n+1):
  flg = 0
  for i in range(m):
    v1,v2,e = abd[i]
    if visitable[v1] & visitable[v2] == 0:
      continue 
    e = -e+p
    if score[v1] != 10**15 and score[v2] > score[v1]+e:
      score[v2] = score[v1]+e
      flg = 1
      if j == n-1:
        last = score[:]
      if j == n:
        onemore = score[:]
  if flg == 0:
    break
if flg == 0:
  print(max(0,-score[n]))
else:
  if last == onemore:
    print(max(last[n],0))
  else:
    print(-1)

Solution (Python):

"""
1の移動に対してpだけコストを支払うと考える事ができる。
pを考慮しても無限にコインを増やすような閉路が存在する場合、-1を出力、そうでないならばコストが最大と
なるようにゴールに行くことが最適である。
すべての辺上のコインをマイナス値でもって、pを足し合わせることによってこれが達成できる。
ベルマンフォード法を用いて負の重みを扱えるようにする。
この時、負の閉路の検出が可能だが、この問題では1→Nへの道とは関係ない場所に負の閉路が存在しても、
それは無限にコインを増やせるとは言わない。
よって、まず1と関係する辺をすべて求めた後、Nと関係する逆辺を求める事により、どちらもに該当しない辺を除去することで達成できる。
"""
import sys
from collections import deque
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n,m,p = map(int,readline().split())
g = [[] for i in range(n)]
rev = [[] for i in range(n)] 
for i in range(m):
	x,y,w = map(int,readline().split())
	x,y,w = x-1,y-1,-w
	g[x].append((y,w+p))
	rev[y].append((x,w+p))

res1 = [0]
queue = deque([0])

while True:
	if len(queue) <= 0:
		break
	v = queue.pop()
	for e in g[v]:
		if e[0] not in res1:
			res1.append(e[0])
			queue.append(e[0])
		else:
			continue

res2 = [n-1]
queue = deque([n-1])

while True:
	if len(queue) <= 0:
		break
	v = queue.pop()
	for e in rev[v]:
		if e[0] not in res2:
			res2.append(e[0])
			queue.append(e[0])
		else:
			continue
itr = set([i for i in range(n)])
res3 = itr - (set(res1) & set(res2))

def BellmanFord(edges,num_v,source): 
	
	inf=float("inf")
	dist=[inf for i in range(num_v)]
	dist[source]=0
	
	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 [] 
  
	return dist

edges = []
for i in range(n):
	if i in res3:
		continue
	for j in g[i]:
		if j[0] in res3:
			continue
		edges.append([i,j[0],j[1]])

dist = BellmanFord(edges,n,0)

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

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
n,m,p = map(int,input().split())
E1 = [[] for i in range(n)]
E2 = [[] for i in range(n)]
edge = []
for i in range(m):
    a,b,c = map(int,input().split())
    c = p-c
    a -= 1
    b -= 1
    E1[a].append(b)
    E2[b].append(a)
    edge.append((a,b,c))

dis1 = [False]*n
def dfs1(x):
    if dis1[x] == False:
        dis1[x] = True
        for nex in E1[x]:
            dfs1(nex)

dis2 = [False]*n
def dfs2(x):
    if dis2[x] == False:
        dis2[x] = True
        for nex in E2[x]:
            dfs2(nex)

dfs1(0)
dfs2(n-1)

ok = []
for i in  range(n):
    if dis1[i] and dis2[i]:
        ok.append(True)
    else:
        ok.append(False)
nedge = []
for a,b,c in edge:
    if ok[a] and ok[b]:
        nedge.append((a,b,c))

def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in nedge:
            
            if dis[a] != float("INF") and dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n+1 and check:
            return float("INF")
    
    return -dis[-1]

ans = belw()
if ans == float("INF"):
    print(-1)
else:
    print(max(ans,0))