Problem:
 Score : 500 points    Problem Statement There is a directed graph with N vertices numbered 1 to N and M edges.
The i -th edge is directed from Vertex A_i to Vertex B_i , and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N .  We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.  When you reach Vertex N , you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.  Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.      Constraints  2 \leq N \leq 2500  1 \leq M \leq 5000  1 \leq A_i, B_i \leq N  1 \leq C_i \leq 10^5  0 \leq P \leq 10^5  All values in input are integers.  Vertex N can be reached from Vertex 1 .         Input Input is given from Standard Input in the following format:  N  M  P  A_1  B_1  C_1  :  A_M  B_M  C_M       Output If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1 .        Sample Input 1 3 3 10
1 2 20
2 3 30
1 3 45      Sample Output 1 35   There are two ways to travel from Vertex 1 to Vertex 3 :   Vertex 1 \rightarrow 2 \rightarrow 3 : You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.  Vertex 1 \rightarrow 2 : You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.   Thus, the maximum score that can be obtained is 35 .       Sample Input 2 2 2 10
1 2 100
2 2 100      Sample Output 2 -1   The edge extending from Vertex 1 takes you to Vertex 2 . If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t . Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.       Sample Input 3 4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100      Sample Output 3 0   There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0 .  Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2 , but this is pointless since you can no longer reach Vertex 4 and end the game.

Solution (Python):

import sys

inf = float('inf')

def solve(N: int, M: int, P: int, a: "List[int]", b: "List[int]", c: "List[int]"):
    V = list(range(N))
    
    next_v = [[] for v in V]
    for i in range(M):
        next_v[a[i]-1].append((b[i]-1, c[i]))
    
    D = [-inf for v in V]
    D[0] = 0
    
    prev = [None for v in V]

    positive = [False for v in V]

    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    prev[v] = u
    ans = D[N-1]
    
    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    positive[v] = True
                if positive[u]:
                    positive[v] = True

    if positive[N-1]:
        print(-1)
    else:
        print(max(0, ans))
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    P = int(next(tokens))  
    A = [int()] * (M)  
    B = [int()] * (M)  
    C = [int()] * (M)  
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = (int(next(tokens))-P)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

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

def BellmanFord(Edges,num_v,source):
    inf=float('inf')
    dist=[inf for _ 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:
                    before_dist=dist[num_v-1]
                    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 before_dist!=dist[num_v-1]:
                        return -1
    return dist

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    Edges.append((a,b,-(c-p)))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

Solution (Python):

def bellman_ford(s):
    
    d = [inf] * n
    d[s] = 0

    ref = inf
    for cnt in range(n * 2):
        for s, t, w in g:
            if d[s] != inf and d[t] > d[s] + w:
                d[t] = d[s] + w
        if cnt == n - 1:
            ref = d[n - 1]

    if ref == d[n - 1]:
        return max(0, -ref)
    else:
        return -1


inf = float('inf')

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

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

ans = bellman_ford(0)
print(ans)

Solution (Python):






INF = 10 ** 15



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



G = []
for _ in range(M): 
    l, r, s = map(int, input().split()) 
    G += [[l-1, r-1, -(s-P)]] 
    



d = [0] * N 

def shortest_path(s): 
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): 
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                
        if not update: 
            return True
        if count == N - 1: 
            tmp = d[N -1]
        if count == 2 * N:
            if d[N - 1] == tmp:
                return True 
            else:
                return False 


if not shortest_path(1):
    print (-1)
    
    exit()


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

Solution (Python):
INF = 10**18
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))
 
dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n * 2):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        exit()
else:
    if terminal_update > 1:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

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

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

N, M, P = map(int, input().split())
edges = []
for m in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, -(C-P)])
dist = BellmanFord(edges, N, 1)
if dist == -1:
    print(-1)
else:
    print(max(-dist[N-1], 0))

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

for i in range(m):
    A[i][2] = - (A[i][2]-p)







S = [10**13 for i in range(n+1)]

S[1]=0
for i in range(m):
    if A[i][0] == 1:
        S[A[i][1]]=A[i][2]

for j in range(n-1):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])


ans1 = -S[n]

for j in range(n):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])

ans2 = -S[n]

if ans1 != ans2:
    print(-1)
else:
    print(max(0, ans1))

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

E = [[0, 0, 0] for m in range(M)]
for m in range(M):
    A, B, C = map(int, input().split())
    E[m][0] = A - 1
    E[m][1] = B - 1
    E[m][2] = P - C


def BellmanFord(edges, num_v, source, end):
    inf = 10 ** 12
    dist = [inf for i in range(num_v)]
    dist[source] = 0
    parent = [-1 for i in range(num_v)]

    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                parent[edge[1]] = edge[0]

    end1 = dist[end]
    trace1 = []
    r = end
    for n in range(num_v):
        trace1.append(r)
        r = parent[r]
        if r == -1:
            break

    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                parent[edge[1]] = edge[0]

    end2 = dist[end]
    trace2 = []
    r = end
    for n in range(num_v + 10):
        trace2.append(r)
        r = parent[r]
        if r == -1:
            break

    if trace2[-1] != source:
        return -1

    return max(0, -end1) if end1 == end2 else -1


res = BellmanFord(E, N, 0, N - 1)
print(res)

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

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

INF = 10 ** 18
dist = [INF] * (N+1)
dist[1] = 0

loop = False
for i in range(2*N+100):
    for a,b,c in ABC:
        x = dist[a] + P - c
        if dist[b] > x:
            dist[b] = x
            if b == N and i > N:
                loop = True

if loop:
    answer = -1
else:
    answer = -dist[N]
    if answer < 0:
        answer = 0

print(answer)

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


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

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

    if inf_flag == 0:
        return dist
    else:
        dist.append(-1)
        return dist


ans = BellmanFord(edges, N, 1)
if len(ans) != N:
    print(-1)
else:
    print(max(0, ans[-1] * -1))

Solution (Python):


from itertools import accumulate
from bisect import bisect, bisect_left
from collections import Counter, deque, defaultdict
from functools import reduce
from itertools import accumulate
from operator import itemgetter, xor
from string import ascii_lowercase as abc

from sys import setrecursionlimit
setrecursionlimit(10**9)
 
import sys

from collections import Counter
def inpl(): return list(map(int, input().split()))

N, M, P = inpl()
INF = 10**12
G = [[] for _ in range(N)]
E = []
G2 = [[] for _ in range(N)]
rG2 = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = inpl()
    G[a-1].append([b-1, -c+P])
    G2[a-1].append(b-1)
    rG2[b-1].append(a-1)
    E.append([a-1, b-1, -c+P])


def SCC(G, rG):
    N = len(G)
    def dfs(i):
        nonlocal t, rorder, searched
        searched[i] = True
        for j in G[i]:
            if not searched[j]:
                dfs(j)
        rorder[t] = i
        t += 1

    def rdfs(i):
        nonlocal t, group, g
        group[i] = g
        for j in rG[i]:
            if group[j] == -1:
                rdfs(j)

    t = 0
    rorder = [-1]*N
    searched = [0]*N
    group = [-1]*N

    for i in range(N):
        if not searched[i]:
            dfs(i)
    g = 0
    for i in range(N-1, -1, -1):
        if group[rorder[i]] == -1:
            rdfs(rorder[i])
            g += 1
    return group, g


def belman_ford(V, edges, r):
    "If glaph contains negative cycles then return True"
    D = [INF]*(V)
    D[r] = 0
    if V == 1:
        return False, [0]
    OK = True
    for _ in range(V-1):
        update = False
        for s, t, d in edges:
            if D[t] > D[s] + d:
                D[t] = D[s] + d
                update = True
        if not update:
            OK = False
    return OK, D

group, gsize = SCC(G2, rG2)
groups = [[] for _ in range(gsize)]
for i in range(N):
    groups[group[i]].append(i)

score = [10**12 for _ in range(N)]
negative_groups = [0]*N


for g in range(gsize):
    ggs = set(groups[g])
    s = groups[g][0]
    score[s] = 0
    Q = deque([s])
    while Q:
        p = Q.popleft()
        for q, c in G[p]:
            if not q in ggs:
                continue
            if score[p] + c < score[q]:
                score[q] = score[p] + c
                Q.append(q)
        if score[s] < 0:
            for g in ggs:
                negative_groups[g] = 1
            break

s = 0
Q = deque([s])
reach1 = [0]*N
reach1[0] = 1

while Q:
    p = Q.popleft()
    for q in G2[p]:
        if not reach1[q]:
            reach1[q] = 1
            Q.append(q)

s = N-1
Q = deque([s])
reachN = [0]*N
reachN[-1] = 1

while Q:
    p = Q.popleft()
    for q in rG2[p]:
        if not reachN[q]:
            reachN[q] = 1
            Q.append(q)

NEGATIVE, D = belman_ford(N, E, 0)

if any([reach1[i]&reachN[i]&negative_groups[i] for i in range(N)]) or reach1[-1]==0:
    print(-1)
else:
    print(max(0, -D[-1]))

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

def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math
import queue

NINF = -1000000000

def reachable(n, vtxs):
    visited = [0 for i in range(n)]
    visited[0] = 1

    qu = queue.Queue()
    qu.put(0)
    while(not qu.empty()):
        curr = qu.get()
        for next in vtxs[curr]:
            if visited[next] == 0:
                visited[next] = 1
                qu.put(next)

    return visited

def reachable_rev(n, revs):
    visited = [0 for i in range(n)]
    visited[n-1] = 1
    qu = queue.Queue()
    qu.put(n - 1)
    while(not qu.empty()):
        curr = qu.get()
        for next in revs[curr]:
            if visited[next] == 0:
                visited[next] = 1
                qu.put(next)

    return visited



def bellman(n, m, edges, vtxs, revs):
    cost = [NINF for i in range(n)]
    cost[0] = 0
    tgts = [0]
    loop = 0
    final = False
    reach = reachable(n, vtxs)
    revreach = reachable_rev(n, revs)
    while(True):
        flag = False
        if loop > n:
            final = True
            break
        for e in edges:
            
            if cost[e[1]] < cost[e[0]] + e[2]:
                point = e[1]
                ppoint = e[0]
                
                if reach[point] and revreach[point]:
                    if reach[ppoint] and revreach[ppoint]:
                        cost[e[1]] = cost[e[0]] + e[2]
                        flag = True
                        
        if not flag:
            break
        loop += 1
        


    
    if final:
        for e in edges:
            
            if cost[e[1]] < cost[e[0]] + e[2]:
                point = e[1]
                ppoint = e[0]
                
                if reach[point] and revreach[point]:
                    if reach[ppoint] and revreach[ppoint]:
                        return -1

    if reach[-1] == 0:
        return -1

    return max(0, cost[-1])

n, m , p= getList()
vtxs = [[] for i in range(n)]
revs = [[] for i in range(n)]
edges = []

for i in range(m):
    a, b, c = getList()
    vtxs[a-1].append(b-1)
    revs[b-1].append(a-1)
    edges.append((a-1, b-1, c - p))


print(bellman(n, m, edges, vtxs, revs))

Solution (Python):
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'


def BellmanFord(edges,num_v,source):
  
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0
  
  
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        if i==num_v-1 and ans!=dist[n-1]:
            0
    ans=dist[n-1]
  return dist

def shortest_path(s,n,w,es):
    
    
    d = [float("inf")] * n
    
    d[s] = 0
    while True:
        updata = False
        for i in range(w):
            e = es[i]
            ans=d[n-1]
            
            if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                updata = True
        if not updata:
            break
    return d

n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    
    g.append((a,b,p-c))
    

di=BellmanFord(g,n,1)
ans=di[n-1]
di_2=BellmanFord(g,n*2,1)

if ans!=di_2[n-1]:
    print(-1)
else:
    print(max(0,-di[n-1]))

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

def main():
    N,M,P = map(int,input().split())
    edges = []


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

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N-1):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
    ans = -1*dist[N-1]
    
    for i in range(N-1):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]]+edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
    ans2 = -1*dist[N-1]

    if ans2<=ans: 
        print(max(0,ans))         
    else:
        print(-1)

if __name__ == "__main__":
    main()

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 5 + 5)


def omit(n, links, parents):
    q = [0]
    visited_f = [False] * n
    while q:
        v = q.pop()
        if visited_f[v]:
            continue
        visited_f[v] = True
        q.extend(u for u in links[v] if not visited_f[u])

    q = [n - 1]
    visited_b = [False] * n
    while q:
        v = q.pop()
        if visited_b[v]:
            continue
        visited_b[v] = True
        q.extend(u for u in parents[v] if not visited_b[u])

    remains = [i for i, (f, b) in enumerate(zip(visited_f, visited_b)) if f and b]
    sr = set(remains)
    for v in remains:
        links[v] &= sr

    return remains


n, m, p = list(map(int, input().split()))
INF = 10 ** 12
costs = [[INF] * n for _ in range(n)]
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    parents[b].add(a)
    costs[a][b] = min(costs[a][b], p - c)
remains = omit(n, links, parents)

dist = [INF] * n
dist[0] = 0
for _ in range(n + 1):
    updated = False
    for v in remains:
        d = dist[v]
        if d == INF:
            continue
        cv = costs[v]
        for u in links[v]:
            if dist[u] > d + cv[u]:
                dist[u] = d + cv[u]
                updated = True
    
    if not updated:
        break
else:
    print(-1)
    exit()

print(max(0, -dist[n - 1]))

Solution (Python):
inf = 10 ** 18
n, m, p = map(int, input().split())
edge = []
d = [inf] * n
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = p - c
    edge.append((a, b, c))
d[0] = 0
for i in range(n-1):
    pre = d[n-1]
    for a, b, c in edge:
        if (d[a] != inf and d[b] > d[a] + c):
            d[b] = d[a] + c
            update = True

pre = d[n-1]
for i in range(n-1):
    for a, b, c in edge:
        if (d[a] != inf and d[b] > d[a] + c):
            d[b] = d[a] + c

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

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

N,M,P=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(M)]

for i in range(M):
    EDGE[i][2]-=P

from collections import deque

Q=deque([1])

ANS=[-float("inf")]*(N+1)
ANS[1]=0

for i in range(N+1):
    for a,b,p in EDGE:
        if ANS[a]+p>ANS[b]:
            ANS[b]=ANS[a]+p
    



import copy
ANS2=copy.deepcopy(ANS)

for i in range(N+1):
    for a,b,p in EDGE:
        if ANS2[a]+p>ANS2[b]:
            ANS2[b]=ANS2[a]+p
    


if ANS[N]<ANS2[N]:
    print(-1)
else:
    print(max(ANS2[N],0))

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

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

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


for i in range(N):
    for a, b, c in ABC:
        if d[b] <= d[a] + c:
            continue
        d[b] = d[a] + c
ans = d[N - 1]
for i in range(N):
    for a, b, c in ABC:
        if d[b] <= d[a] + c:
            continue
        d[b] = d[a] + c
if ans != d[N - 1]:
    print(-1)
else:
    print(max(0, -d[N - 1]))

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

Edgeinv = [[] for _ in range(N+1)]
Edge = [[] for _ in range(N+1)]
inf = 2*10**10
Edgenum = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
for a, b, c in Edgenum:
    Edgeinv[b].append(a)
    Edge[a].append(b)

used = set([N])
stack = [N]
while stack:
    vn = stack.pop()
    for vf in Edgeinv[vn]:
        if vf not in used:
            used.add(vf)
            stack.append(vf)

used2 = set([1])
stack = [1]
while stack:
    vn = stack.pop()
    for vf in Edge[vn]:
        if vf not in used2:
            used2.add(vf)
            stack.append(vf)

Edgenum = [(a, b, c) for a, b, c in Edgenum if a in used and b in used]

used &= used2

dp = [-inf]*(N+1)
dp[1] = 0
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp = dp[:]
for i in range(N):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

if any(Dp[i] < dp2[i] for i in used):
    print(-1)
else:
    print(max(0, Dp[N]))

Solution (Python):
N, M, P = map(int, input().split())
edges = []
edges1 = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edges1[b-1].append(a-1)
    edges.append((a-1, b-1, -c+P))
from collections import deque
que = deque([N-1])
flag = [True]*N
flag[-1] = False
while que:
    v = que.pop()
    for e in edges1[v]:
        if flag[e]:
            que.append(e)
            flag[e] = False
def f(n,w,es):
    
    
    d = [float("inf")] * n
    d[0] = 0 
    
    for i in range(n):
        for j in range(w):
            e = es[j]
            if flag[e[1]]:
                continue
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    return False
    return d
d = f(N, M, edges)
if d:
    print(max(-d[-1], 0))
else:
    print(-1)

Solution (Python):
N,M,P=map(int,input().split())
A=[0 for i in range(M)]
B=[0 for i in range(M)]
C=[0 for i in range(M)]
G=[dict() for i in range(N)]
H=[dict() for i in range(N)]
for i in range(M):
    A[i],B[i],C[i]=map(int,input().split())
    G[B[i]-1][A[i]-1]=C[i]
    H[A[i]-1][B[i]-1]=C[i]
reached1=[0 for i in range(N)]
q=[N-1]
while(len(q)>0):
    r=q.pop()
    reached1[r]=1
    for p in G[r]:
        if reached1[p]==0:
            q.append(p)
reached2=[0 for i in range(N)]
q=[0]
while(len(q)>0):
    r=q.pop()
    reached2[r]=1
    for p in H[r]:
        if reached2[p]==0:
            q.append(p)
reached=[reached1[i]*reached2[i] for i in range(N)]
vertex_list=[]
vertex_num=[-1 for i in range(N)]
tmp=1
for i in range(N):
    if reached[i]==1:
        vertex_list.append(i+1)
        vertex_num[i]=tmp
        tmp+=1
num_v=len(vertex_list)
edges=[]
for i in range(M):
    if reached[A[i]-1]==1 and reached[B[i]-1]==1:
        edges.append((vertex_num[A[i]-1],vertex_num[B[i]-1],P-C[i]))
inf=10**10
dist=[inf for i in range(num_v)]
dist[0]=0





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

Solution (Python):
inf = float('inf')
V,E,P = map(int,input().split())
edge = []
for i in range(E):
    A,B,C = map(int,input().split())
    edge.append([A-1,B-1,P-C])

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

ans = d[V-1]

for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break
loop = ans != d[V-1]

if loop:
    print(-1)

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

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

e_list = []
for i in range(M):
    A,B,C = list(map(int,input().split()))
    A,B = A-1,B-1
    e_list.append((A,B,P-C))
    



vi=0
min_dis_list = [10**27 for i in range(N)]
min_dis_list[vi] = 0
prev_list = [-1 for i in range(N)]

for i in range(N-1):
    for e in e_list:
        u,v,d = e
        if min_dis_list[v]>min_dis_list[u]+d:
            min_dis_list[v]=min_dis_list[u]+d
            prev_list[v]=u

neg_loop_flag=[False for i in range(N)]

for i in range(N):
    for e in e_list:
        u,v,d = e
        if min_dis_list[u] < 10**26:
            if min_dis_list[u] + d < min_dis_list[v]:
                neg_loop_flag[v]=True
                min_dis_list[v] = min_dis_list[u] + d
            if neg_loop_flag[u]:
                neg_loop_flag[v]=True


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

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.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 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():
    def f(s):
        res = [0]*m
        for i in s:
            res[alp.index(i)] += 1
        return res
    alp = list("abcdefghijklmnopqrstuvwxyz")
    m = len(alp)
    n = I()
    s = [input() for i in range(n)]
    d = defaultdict(lambda : 0)
    for i in s:
        d[tuple(f(i))] += 1
    ans = 0
    for i in d.values():
        ans += (i*(i-1))//2
    print(ans)
    return


def D():
    n,m = LI()
    g = LIR(n)
    g.sort(key = lambda x:x[0])
    ans = 0
    f = [1]*n
    j = 0
    q = []
    for i in range(m)[::-1]:
        while j < n and m-g[j][0] >= i:
            a,b = g[j]
            heappush(q,(-b,a))
            j += 1
        if q:
            x,a = heappop(q)
            if i+a <= m:
                ans -= x
    print(ans)
    return


def E():
    def dfs(x,f):
        for y,w in v[x]:
            if f[y]:
                if dp[y] < dp[x]+w:
                    f[y] = 0
                    dp[y] = dp[x]+w
                    dfs(y,f)
                    f[y] = 1
            else:
                if dp[y] < dp[x]+w:
                    dp[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        v[a].append((b,c-p))
    f = [1]*n
    dp = [-float("inf")]*n
    dp[0] = 0
    f[0] = 0
    dfs(0,f)
    ans = dp[n-1]
    if ans == float("inf") or ans == -float("inf"):
        print(-1)
    elif ans < 0:
        print(0)
    else:
        print(ans)
    return


def F():

    return


if __name__ == "__main__":
    E()

Solution (Python):
n,m,p = map(int, input().split())
es = []
g1 = [[]for _ in range(n)]
g2 = [[] for _ in range(n)]
li = []
for i in range(m):
  a,b,c = map(int, input().split())
  li.append((a - 1,b - 1,c))
  g1[a - 1].append((b - 1,(c-p)*-1))
  g2[b - 1].append((a - 1,(c-p)*-1))
done1 = [0] * n
done1[0] = 1
s = [0]
while s:
  d = s.pop()
  for node,_ in g1[d]:
    if not done1[node]:
      done1[node] = 1
      s.append(node)
done2 = [0] * n
done2[n - 1] = 1
s = [n - 1]
while s:
  d = s.pop()
  for node, _ in g2[d]:
    if not done2[node]:
      done2[node] = 1
      s.append(node)
done = [0] * n
for i in range(n):
  done[i] = done1[i] & done2[i]
for a,b,c in li:
  if done[a] & done[b]:
    es.append((a,b,(c-p)*-1))
m = len(es)
d = [0]*n
for i in range(n):
  for j in range(m):
    f, t, c = es[j]
    if d[t] > d[f] + c:
      d[t] = d[f] + c
      if i == n - 1:
        print(-1)
        exit(0)
d = [float('inf')] * n
d[0] = 0
while(True):
  update = False
  for i in range(m):
    f, t, c = es[i]
    if d[f] != float('inf') and d[t] > d[f] + c:
      d[t] = d[f] + c
      update = True
  if not update:
    break
print(max(0, -d[n - 1]))