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
sys.setrecursionlimit(10**6)
INF = 10**10
 
def dfs(edge, visited, n):
    if visited[n]:
        return
    visited[n] = True
    for to, _ in edge[n]:
        dfs(edge, visited, to)

def bellman_ford(edge, mask):
    dist = [INF] * n
    dist[0] = 0

    for _ in range(n):
        update = False
        for i, es in enumerate(edge):
            if not mask[i]:
                continue
            for to, cost in es:
                if not mask[to]:
                    continue
                if dist[i] != INF and dist[i] + cost < dist[to]:
                    dist[to] = dist[i] + cost
                    update = True
        if not update:
            return dist
    else:
        
        return -INF

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    redge = [[] 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))
        redge[b].append((a, c)) 
    
    
    visited = [False] * n
    dfs(edge, visited, 0)
    
    rvisited = [False] * n
    dfs(redge, rvisited, n-1)
    mask = [forward and backward for forward, backward in zip(visited, rvisited)]

    dist = bellman_ford(edge, mask)
    if dist == -INF:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
INF = 10**10
 
def dfs(edge, visited, n):
    if visited[n]:
        return
    visited[n] = True
    for to, _ in edge[n]:
        dfs(edge, visited, to)

def bellman_ford(edge, mask):
    dist = [INF] * n
    dist[0] = 0

    for _ in range(n):
        update = False
        for i, es in enumerate(edge):
            if not mask[i]:
                continue
            for to, cost in es:
                if not mask[to]:
                    continue
                if dist[i] != INF and dist[i] + cost < dist[to]:
                    dist[to] = dist[i] + cost
                    update = True
        if not update:
            return dist
    else:
        
        return -INF

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    redge = [[] 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))
        redge[b].append((a, c)) 
    
    visited = [False] * n
    dfs(edge, visited, 0)
    rvisited = [False] * n
    dfs(redge, rvisited, n-1)
    mask = [forward and backward for forward, backward in zip(visited, rvisited)]
    dist = bellman_ford(edge, mask)
    if dist == -INF:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Solution (Python):
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]
d=[float("inf")]*n
d[0]=0

for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    d[e1]=min(d[e1],d[e0]+e2)
ans1=d[-1]
for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    if d[e1]>d[e0]+e2:
      d[e1]=-float("inf")
ans2=d[-1]
print(-1 if ans1!=ans2 else max(0,-ans1))

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):
import sys
 
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  
 
n, m, p = na()
 
def bf(es, n, start):
    d = [999999999999] * n
    d[start] = 0
 
    for r in range(n-1):
        updated = False
        for e in es:
            if d[e[0]] == 999999999999:
                continue
            if d[e[0]] + e[2] < d[e[1]]:
                d[e[1]] = d[e[0]] + e[2]
                updated = True
        if not updated:
            break
 
    for e in es:
        if d[e[0]] < 999999999999 and d[e[0]] + e[2] < d[e[1]]:
            return None
 
    return d
 
es = []
for i in range(m):
    a, b, c = na()
    es.append((a-1, b-1, -(c-p)))
 
import collections
q = collections.deque()
q.append(n-1)
 
valid = [False] * n
valid[n-1] = True
while len(q) > 0:
    cur = q.popleft()
    for e in es:
        if e[1] == cur and not valid[e[0]]:
            valid[e[0]] = True
            q.append(e[0])
 
nes = []
for e in es:
    if valid[e[0]] and valid[e[1]]:
        nes.append(e)
es = nes
 
d = bf(es, n, 0)
if not d:
    print(-1)
else:
    print(max(0, -d[n-1]))

Solution (Python):

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


def bellman_ford(v, s, t, e):
    
    d = [10**18] * v
    
    d[s] = 0
    
    for _ in range(v):
        f = False
        for a, b, c in e:
            
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        
        if not f:break
    else:
        
        return -1
    return max(-d[t], 0)

def main():
    import sys
    input = sys.stdin.readline
    n, m, p = map(int, input().split())
    edge = [[] for _ in range(n)]
    edge_rev = [[] for _ in range(n)]
    e = []
    for _ in range(m):
        a, b, c = map(int, input().split())
        edge[a-1].append(b-1)
        
        edge_rev[b-1].append(a-1)
        e.append((a-1, b-1, p-c))
    
    use = dfs(edge, 0) & dfs(edge_rev, n-1)
    
    
    e=[(a, b, c) for a, b, c in e if a in use and b in use]
    print(bellman_ford(n, 0, n-1, e))   
if __name__ == '__main__':
    main()

Solution (Python):
def main():
    def dfs(edge,s):
        use={s}
        q=[s]
        while q:
            v=q.pop()
            for w in edge[v]:
                if w in use:continue
                use.add(w)
                q.append(w)
        return use
    n,m,p,*t=map(int,open(0).read().split())
    edge=[[]for _ in range(n)]
    edge_rev=[[]for _ in range(n)]
    e=[]
    for a,b,c in zip(t[::3],t[1::3],t[2::3]):
        edge[a-1].append(b-1)
        edge_rev[b-1].append(a-1)
        e.append((a-1,b-1,p-c))
    use=dfs(edge,0)&dfs(edge_rev,n-1)
    e=[(a,b,c)for a,b,c in e if a in use and b in use]
    INF=10**18
    d=[0]+[INF]*(n-1)
    for _ in range(n):
        f=False
        for a,b,c in e:
            cost=d[a]+c
            if cost<d[b]:
                d[b]=cost
                f=True
        if not f:break
    else:
        print(-1)
        exit()
    print(max(-d[-1],0))
main()

Solution (Python):
def main():
    def dfs(edge,s):
        use={s}
        q=[s]
        while q:
            v=q.pop()
            for w in edge[v]:
                if w in use:continue
                use.add(w)
                q.append(w)
        return use
    n,m,p,*t=map(int,open(0).read().split())
    edge=[[]for _ in range(n)]
    edge_rev=[[]for _ in range(n)]
    e=[]
    for a,b,c in zip(t[::3],t[1::3],t[2::3]):
        edge[a-1].append(b-1)
        edge_rev[b-1].append(a-1)
        e.append((a-1,b-1,p-c))
    use=dfs(edge,0)&dfs(edge_rev,n-1)
    e=[(a,b,c)for a,b,c in e if a in use and b in use]
    INF=10**18
    d=[0]+[INF]*(n-1)
    for _ in range(n):
        f=False
        for a,b,c in e:
            cost=d[a]+c
            if cost<d[b]:
                d[b]=cost
                f=True
        if not f:break
    else:
        print(-1)
        exit()
    print(max(-d[-1],0))
main()

Solution (Python):
from collections import deque
def solve():
    N, M, P = map(int, input().split())
    G = [[] for i in range(N)]
    RG = [[] for i in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        G[a-1].append((b-1, P-c))
        RG[b-1].append((a-1, P-c))

    def chk(s, G):
        P = [0]*N
        que = deque([s])
        used = [0]*N
        used[s] = 1
        while que:
            v = que.popleft()
            P[v] = 1
            for w, c in G[v]:
                if used[w]:
                    continue
                que.append(w)
                used[w] = 1
        return P
    P0 = chk(0, G); P1 = chk(N-1, RG)
    F = [P0[i] == P1[i] == 1 for i in range(N)]
    I = [i for i in range(N) if F[i]]

    E0 = []
    for v in I:
        for w, c in G[v]:
            if not F[w]:
                continue
            E0.append((v, w, c))

    dist = [10**18]*N
    dist[0] = 0
    L = len(I)
    for i in range(L):
        update = 0
        for v, w, c in E0:
            x = c + dist[v]
            if x < dist[w]:
                dist[w] = x
                update = 1
        if not update:
            break
    else:
        print("-1")
        return

    print(max(-dist[N-1], 0))
solve()

Solution (Python):
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
import sys
INT_MAX = sys.maxsize 
    
def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                if dist[edge[0]] != INT_MAX:
                    dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for _ in range(N):
        for edge in edges:
            if dist[edge[0]] == INT_MAX:
                continue
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                negative[edge[1]] = True
            
            if negative[edge[0]]:
                negative[edge[1]] = True
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
ans = -1 * shortest_path[N]

if ans == -INT_MAX or ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Solution (Python):
def e_coins_respawn(N, M, P, Edges, INF=float('inf')):
    edges = [(a - 1, b - 1, P - c) for a, b, c in Edges]
    dist = [INF] * N
    dist[0] = 0

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

    
    is_negative = [False] * N
    for _ in range(N):
        for u, v, w in edges:
            if dist[u] == INF:
                continue
            if dist[v] > dist[u] + w:
                dist[v] = dist[u] + w
                is_negative[v] = True

            
            if is_negative[u]:
                is_negative[v] = True
    
    return -1 if is_negative[N - 1] else max(-ans_tmp, 0)

N, M, P = [int(i) for i in input().split()]
Edges = [[int(i) for i in input().split()] for j in range(M)]
print(e_coins_respawn(N, M, P, Edges))

Solution (Python):
import sys
sys.setrecursionlimit(1000000)




class Edge:
    def __init__(self, f: int, t: int, cost: int):
        self._t = t
        self._cost = cost
        self._f = f

    @property
    def t(self):
        return self._t

    @property
    def f(self):
        return self._f

    @property
    def cost(self):
        return self._cost


INF = 1 << 28



def bellman_ford(n: int, edges, s: int):
    dist = [INF for _ in range(n)]
    dist[s] = 0

    for i in range(2 * n):
        for e in edges:

            if dist[e.t] > dist[e.f] + e.cost:
                dist[e.t] = dist[e.f] + e.cost
                if i >= n - 1:
                    return None

    return dist


def visitable_node(n, g, rg):

    vis = [False] * n

    def dfs(idx):
        vis[idx] = True
        for e in g[idx]:
            if not vis[e]:
                dfs(e)

    dfs(0)

    rvis = [False] * n

    def rdfs(idx):
        rvis[idx] = True
        for e in rg[idx]:
            if not rvis[e]:
                rdfs(e)

    rdfs(n - 1)

    return [vis[i] & rvis[i] for i in range(n)]


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

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

visitable = visitable_node(n, g, rg)
updated = [e for e in edges if visitable[e.f] and visitable[e.t]]

dist = bellman_ford(n, updated, 0)

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

Solution (Python):

n,m,r=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]

g=[[] for _ in [0]*n]
[g[a-1].append([b-1,c]) for a,b,c in abc]


g2=[[] for _ in [0]*n]
[g2[b-1].append([a-1,c]) for a,b,c in abc]


def remove_edge(graph,start):
    q=[start]
    memo=[True for _ in range(n)]
    memo[start]=False
    while q:
        qq=q.pop()
        for i,j in graph[qq]:
            if memo[i]:
                q.append(i)
                memo[i]=False
    return {i for i,j in enumerate(memo) if j==True}


rmv=remove_edge(g,0)|remove_edge(g2,n-1)
for i in rmv:
    g[i]=[]
for i in range(n):
    for j in g[i]:
        if j[0] in rmv:
            g[i].remove(j)


dist=[-10**15 for _ in [0]*n]
dist[0]=0

for k in range(n):
    for p in range(n):
        for i,j in g[p]:
            dist[i]=max(dist[i],dist[p]+j-r)
    if k==n-2:
        d1=[t for t in dist]
    if k==n-1:
        d2=[t for t in dist]
        

if d1==d2:
    print(max(d1[-1],0))
else:
    print(-1)

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

edge_dic = {}

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



INF = 10 ** 10

ans_array = [-INF] * N
can_visit = [0] * N
ans_array[0] = 0
can_visit[0] = 1 
last_ans_change = -1

for i in range(N*2):
    change_flag = 0
    for key, value in edge_dic.items():
        if can_visit[key] == 0:
            continue
        for v in value:
            goal, cost = v
            if ans_array[goal] < ans_array[key] + cost:
                ans_array[goal] = ans_array[key] + cost
                if i >= N:
                    ans_array[goal] = INF
                can_visit[goal] = 1
                change_flag = 1
                if goal == N - 1:
                    last_ans_change = i
                    if i >= N:
                        print(-1)
                        exit()
    if change_flag == 0:
        break


ans = max(0,ans_array[N-1])

print(ans)

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

    
    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:
                if edge[1] == num_v:
                    return -1
                else:
                    dist[edge[1]-1] = -inf
                    flag = True
    if flag:
        for i in range(num_v):
            for edge in edges:
                if dist[edge[1]-1]>dist[edge[0]-1] + edge[2]:
                    dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
                    if edge[1] == num_v :
                        return -1

    return dist

N,M,P = [int(x) for x in input().split()]
gp = []
for _ in range(M):
    A,B,C = [int(x) for x in input().split()]
    gp.append([A,B,P-C])

li = BellmanFord(gp,N,1)
if(li==-1):
    print(-1)
else:
    print(max(0,-li[N-1]))

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

def chk(s, G):
    P = [0]*N
    que = deque([s])
    used = [0]*N
    used[s] = 1
    while que:
        v = que.popleft()
        P[v] = 1
        for w, c in G[v]:
            if used[w]:
                continue
            que.append(w)
            used[w] = 1
    return P
P0 = chk(0, G); P1 = chk(N-1, RG)
I = [i for i in range(N) if P0[i] == P1[i] == 1]

dist = [10**18]*N
dist[0] = 0
L = len(I)
for i in range(L+1):
    update = 0
    for v in I:
        d = dist[v]
        for w, c in G[v]:
            if d + c < dist[w]:
                dist[w] = d + c
                update = 1
    if not update:
        break
else:
    print("-1")
    exit(0)

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

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

v = [[] for _ in range(N)]
abc = []
for _ in range(M) :
    a, b, c = map(int, input().split())
    v[b-1].append((a-1, -(c-P)))
    
visited = [False] * N
visited[N-1] = True
queue = [N-1]
while queue :
    cur = queue.pop()
    for nex, cost in v[cur] :
        if not visited[nex] :
            queue.append(nex)
            visited[nex] = True
        abc.append((nex, cur, cost))
        
dist = [float('inf')] * N
dist[0] = 0

def bellmanford() :
    for i in range(N) :
        for a, b, c in abc :
            if dist[a] + c < dist[b] :
                dist[b] = dist[a] + c
                if i == N-1 :
                    return True
    return False
    
if bellmanford() :
    print(-1)
else :
    print(max(0, -dist[N-1]))

Solution (Python):
n, m, p = [ int(v) for v in input().split() ]
node_list = []
node_list_2 = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
    node_list_2.append((b-1,a-1,p-c))


def b_f(node_list,n,t):
    distance_list = [ 10**15 for i in range(n) ]
    distance_list[t] = 0

    for i in range(n):
        new_distanece_list = distance_list
        for j in node_list:
            a, b, c = j
            if distance_list[a] != 10**15:
                if new_distanece_list[b] > distance_list[a] + c:
                    new_distanece_list[b] = distance_list[a] + c
        distance_list = new_distanece_list

        if i == n-2:
            distance_list_n_minus_1 = [i for i in distance_list]
        elif i == n-1:
            distance_list_n = [i for i in distance_list]

    if distance_list_n_minus_1 == distance_list_n:
        negative_cycle = 0
    else:
        negative_cycle = 1

    return distance_list_n_minus_1, negative_cycle


point_list_s = b_f(node_list,n,0)[0]
point_list_g = b_f(node_list_2,n,n-1)[0]
point_list = [ True for i in range(n) ]

for i in range(n):
    if point_list_s[i] == 10**15 or point_list_g[i] == 10**15:
        point_list[i] = False

node_list_3 = [ i for i in node_list if point_list[i[0]] == True and point_list[i[1]] == True ]
ans = b_f(node_list_3,n,0)

if ans[1] == 0:
    print(-min(0,ans[0][-1]))
else:
    print(-1)

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]

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]*N
min_dis_list[vi] = 0
 
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
 
neg_loop_flag=[False]*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):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bellman_ford(N: int, edges: list, src: int) -> list:
    """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

    
    res = [INF] * N
    res[src] = 0
    
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    
    for i in range(N):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                
                res[dest] = -INF
                if dest == N-1:
                    
                    return []
    
    return res

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

res = bellman_ford(N, edges, 0)
if not len(res):
    print(-1)
else:
    
    ans = -res[N-1]
    
    print(max(0, ans))

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):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def BellmanFord(N, e, s, goal):
    dist = [sys.maxsize] * (N+1)
    dist[s] = 0
    for i in range(N+1):
        for u, v, c in e:
            if dist[v] > dist[u] + c:
                if i == N:
                    return 'inf'
                dist[v] = dist[u] + c
    return dist

@mt
def slv(N, M, P, ABC):
    g = [[] for _ in range(N+1)]
    for a, b, c in ABC:
        g[a].append(b)

    def r(s, e):
        q = deque()
        q.append(s)
        done = set([s])
        while q:
            u = q.pop()
            for v in g[u]:
                if v not in done:
                    done.add(v)
                    q.append(v)
        return done

    d = set()
    for i in range(2, N):
        reachable = r(i, N)
        if N not in reachable:
            d.add(i)
    
    e = []
    sr = r(1, N)
    for a, b, c in ABC:
        if a not in d and b not in d and a in sr and b in sr:
            e.append((a, b, -(c - P)))

    d = BellmanFord(N, e, 1, N)
    if d == 'inf':
        return -1
    return max(0, -d[N])


def main():
    N, M, P = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    print(slv(N, M, P, ABC))

    
    
    
    
    
    
    
    



if __name__ == '__main__':
    main()