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 bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


"""
def Bellman_Ford(S,V,E,distance,negative):
    negative = [False]*N
    count = 1
    while count < V:
        count += 1
        for s,g,d in distance: 
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: 
                min_distance[g] = min_distance[s] + d 
                negative[s],negative[g] = True,True
    return min_distance,negative

min_distance,negative = Bellman_Ford(1,N,M,line,negative)
ans = min_distance[N-1]

negative = [False]*N
min_distance,negative = Bellman_Ford(1,N,M,line,negative)
print(negative)
print(min_distance)

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

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

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

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

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [-10**18] * n
ok1 = [False] * n
ok2 = [False] * n
d[0] = 0
ok1[0] = True
ok2[-1] = True

for _ in range(n):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True
aa = d[:]

for _ in range(1):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True

bb = d[:]

ok = False
for i in range(n):
    if ok1[i] and ok2[i]:
        if aa[i] != bb[i]:
            ok = True
if ok:
    print("-1")
else:
    print(max(aa[-1], 0))

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

import sys
input = sys.stdin.readline

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

G = {}

for i in range(M):
  a,b,c = map(int, input().split())
  a,b,c = a-1, b-1, (-1) * (c-P) 
  if (a,b) in G and G[(a,b)] > c:
    G[(a,b)] = c
  elif (a,b) not in G:
    G[(a,b)] = c

A,B,C = [],[],[]
for k,v in G.items():
  a,b = k
  c = v
  
  A.append(a)
  B.append(b)
  C.append(c)
    
CC = [1] * len(A)



smat = bellman_ford(csr_matrix((CC, (A, B)), shape=(N, N)),
                    directed=True, unweighted=True, indices=0)
tmat = bellman_ford(csr_matrix((CC, (B, A)), shape=(N, N)),
                    directed=True, unweighted=True, indices=N-1)
r = set([i for i, v in enumerate(smat + tmat) if not np.isinf(v)])
A, B, C = zip(*[(a, b, c) for a, b, c in zip(A, B, C) if b in r])
try:
  csr_mat = csr_matrix((C, (A, B)), shape=(N, N))
  
  x = -int(bellman_ford(csr_mat, directed=True, indices=0)[N-1])
  if x < 0:
    x = 0
except NegativeCycleError:
  x = -1

print(x)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N,M,P = IL()

graph = [[] for i in range(N)]
for _ in range(M):
  a,b,c = IL()
  graph[a-1].append((b-1,-c+P))

s = 0
d = [INF] * N
d[s] = 0
update = True
for _ in range(N):
  update = False
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        d[t] = d[v] + cost
        update = True
  if not update:
    break
else:
  for _ in range(N):
    for v, e in enumerate(graph):
      for t, cost in e:
        if d[v] != INF and d[v] + cost < d[t]:
          d[t] = -INF
          if t==N-1:
            print(-1)
            exit()

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

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N,M,P = IL()

graph = [[] for i in range(N)]
for _ in range(M):
  a,b,c = IL()
  graph[a-1].append((b-1,-c+P))

s = 0
d = [INF] * N
d[s] = 0
update = True
for _ in range(N):
  update = False
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        d[t] = d[v] + cost
        update = True
  if not update:
    break
else:
  check = [False] * N
  for _ in range(N):
    update = False
    for v, e in enumerate(graph):
      for t, cost in e:
        if d[v] != INF and d[v] + cost < d[t]:
          check[t] = True
        if check[v]:
          check[t] = True

  for _ in range(N):
    for v, e in enumerate(graph):
      for t, cost in e:
        if d[v] != INF and d[v] + cost < d[t]:
          if t==N-1:
            print(-1)
            exit()
          d[t] = d[v] + cost
          check[t] = True
        if check[v]:
          check[t] = True
        
  if check[-1]:
      print(-1)
      exit()          

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

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N,M,P = IL()

graph = [[] for i in range(N)]
for _ in range(M):
  a,b,c = IL()
  graph[a-1].append((b-1,-c+P))

s = 0
d = [INF] * N
d[s] = 0
update = True
for _ in range(N):
  update = False
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        d[t] = d[v] + cost
        update = True
  if not update:
    break

check = [False] * N
for _ in range(N):
  update = False
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        check[t] = True
      if check[v]:
        check[t] = True

if check[-1]:
  print(-1)
  exit()
  
print(max(-d[-1],0))

Solution (Python):
'''
研究室PCでの解答
'''
import math

import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    n,m,p = map(int,ipt().split())

    way = [[] for i in range(n+1)]
    gway = [[] for i in range(n+1)]
    rway = [[] for i in range(n+1)]
    for i in range(m):
        a,b,c = map(int,ipt().split())
        way[a].append((b,p-c))
        rway[b].append(a)
        gway[a].append(b)

    ar = [True]*(n+1)
    ar[n] = False
    q = [n]
    while q:
        qi = q.pop()
        for j in rway[qi]:
            if ar[j]:
                ar[j] = False
                q.append(j)
    q = [1]
    ar2 = [True]*(n+1)
    ar2[1] = False
    while q:
        qi = q.pop()
        for j in gway[qi]:
            if ar2[j]:
                ar2[j] = False
                q.append(j)

    for i in range(1,n+1):
        if ar[i] or ar2[i]:
            way[i] = []

    def bellmanford(s,g,way):
        n = len(way)
        d = [10**18]*(n)
        d[s] = 0
        sl = 0
        re = True
        while re:
            re = False
            for i in range(1,n):
                for j,cj in way[i]:
                    if d[j] > d[i]+cj:
                         d[j] = d[i]+cj
                         re = True
            sl += 1
            if sl == n:
                d[g] = -10**18
                break
        return d[g]

    ans = bellmanford(1,n,way)
    if ans == -10**18:
        print(-1)
    else:
        print(max(0,-ans))

    return None

if __name__ == '__main__':
    main()

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    
    
    def BellmanFord(N, M, edges):
        
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if to[u] and to[v] and rto[u] and rto[v]:
                    if d[u] + c < d[v]:
                        d[v] = d[u] + c

        
        
        for (u, v, c) in edges:
            if to[u] and to[v] and rto[u] and rto[v]:
                if d[u] + c < d[v]:
                    return None
                
        return d[N-1]
    
    N,M,P=MI()
    edges=[]
    adj1=[[]for _ in range(N)]
    adj2=[[]for _ in range(N)]
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        edges.append([a,b,-1*c])
        adj1[a].append(b)
        adj2[b].append(a)
        
    
    
    import queue
    q=queue.Queue()
    
    to=[0]*N
    to[0]=1
    rto=[0]*N
    rto[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj1[v]:
            if to[nv]==0:
                to[nv]=1
                q.put(nv)
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in adj2[v]:
            if rto[nv]==0:
                rto[nv]=1
                q.put(nv)
                
    can=[0]*N
    for i in range(N):
        can[i]=to[i] and rto[i]
        
    newE=[]
    for (a,b,c) in edges:
        if can[a] and can[b]:
            newE.append((a,b,c))
        
    
    
    
    ans=BellmanFord(N,M,newE)
    
    if ans==None:
        print(-1)
    elif ans>=10**10:
        print(-1)
    else:
        print(max(-1*ans,0))
    
        

main()

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    
    
    def BellmanFord(N, M, edges):
        
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if to[u] and to[v] and rto[u] and rto[v]:
                    if d[u] + c < d[v]:
                        d[v] = d[u] + c

        
        
        for (u, v, c) in edges:
            if to[u] and to[v] and rto[u] and rto[v]:
                if d[u] + c < d[v]:
                    return None
                
        return d[N-1]
    
    N,M,P=MI()
    edges=[]
    adj1=[[]for _ in range(N)]
    adj2=[[]for _ in range(N)]
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        edges.append([a,b,-1*c])
        adj1[a].append(b)
        adj2[b].append(a)
        
    
    
    import queue
    q=queue.Queue()
    
    to=[0]*N
    to[0]=1
    rto=[0]*N
    rto[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj1[v]:
            if to[nv]==0:
                to[nv]=1
                q.put(nv)
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in adj2[v]:
            if rto[nv]==0:
                rto[nv]=1
                q.put(nv)
        
    
    
    
    ans=BellmanFord(N,M,edges)
    
    if ans==None:
        print(-1)
    elif ans>=10**10:
        print(-1)
    else:
        print(max(-1*ans,0))
    
        

main()

Solution (Python):

import sys
sys.setrecursionlimit(10**6)
n, m, p = map(int, input().split())
edges = []
to = [[] for _ in range(n)]
ot = [[] for _ in range(n)]
reachable_from_1 = [False] * n
reachable_to_n = [False] * n
ok = [False] * n
INF = float('inf')


def dfs(v):
    if reachable_from_1[v]:
        return
    reachable_from_1[v] = True
    for nv in to[v]:
        dfs(nv)


def rdfs(v):
    if reachable_to_n[v]:
        return
    reachable_to_n[v] = True
    for nv in ot[v]:
        rdfs(nv)


for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c -= p
    c = -c
    edges.append((a, b, c))
    to[a].append(b)
    ot[b].append(a)
dfs(0)
rdfs(n - 1)
for i in range(n):
    ok[i] = reachable_from_1[i] and reachable_to_n[i]
d = [INF] * n
d[0] = 0
upd = True
step = 0
while upd:
    upd = False
    for e in edges:
        frm, to, cost = e
        if not ok[frm]:
            continue
        if not ok[to]:
            continue
        nd = d[frm] + cost
        if nd < d[to]:
            d[to] = nd
            upd = True
    step += 1
    if step > n:
        print(-1)
        exit()
ans = -d[n - 1]
ans = max(0, ans)
print(ans)