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

Solution (Python):
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline

    inf = 1 << 60

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

    to = tuple(set() for _ in range(N))
    ot = tuple(set() for _ in range(N))
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        to[a].add((b, -(c - P)))  
        ot[b].add((a, -(c - P)))  

    def reach(s, g, result):
        dq = deque()
        dq.append(s)
        while dq:
            v = dq.popleft()
            for u, _ in g[v]:
                if result[u]: continue
                result[u] = 1
                dq.append(u)

    reachable_from_N = [0] * N
    reachable_from_N[N - 1] = 1
    reach(N - 1, ot, reachable_from_N)

    reachable_from_1 = [0] * N
    reachable_from_1[0] = 1
    reach(0, to, reachable_from_1)

    unreachable = tuple(1 ^ (rn & r1) for rn, r1 in zip(reachable_from_N, reachable_from_1))

    def bellman_ford(dist):
        for _ in range(N):
            not_updated = True
            for v in range(N):
                for u, c in to[v]:
                    if unreachable[u]: continue
                    if (dist[v] == inf) or (dist[v] + c >= dist[u]): continue
                    dist[u] = dist[v] + c
                    not_updated = False
            if not_updated: return False

        for v in range(N):  
            for u, c in to[v]:
                if unreachable[u]: continue
                if (dist[v] == inf) or (dist[v] + c >= dist[u]): continue
                return True
        return False

    dist = [inf] * N
    dist[0] = 0
    cond = bellman_ford(dist=dist)

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


if __name__ == '__main__':
    main()

Solution (Python):
def Bellman_Ford(s, g, inf=1 << 60):
    
    N = len(g)
    dist = [inf] * N
    dist[s] = 0
    for _ in range(N):
        not_updated = True
        for v in range(N):
            for u, c in g[v]:
                if (dist[v] == inf) or (dist[v] + c >= dist[u]): continue
                dist[u] = dist[v] + c
                not_updated = False

        if not_updated:
            return max(0, -dist[N - 1])

    
    for _ in range(N):
        not_updated = True
        for v in range(N):
            for u, c in g[v]:
                if (dist[v] == inf) or (dist[v] + c >= dist[u]): continue
                dist[u] = -inf
                not_updated = False
        if not_updated: break

    if dist[N - 1] == -inf:
        return -1
    else:
        return max(0, -dist[N - 1])


def main():
    import sys
    input = sys.stdin.readline

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

    g = tuple(set() for _ in range(N))
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        g[a].add((b, -(c - P)))  

    ret = Bellman_Ford(0, g)
    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):

import sys
sys.setrecursionlimit(10**7)
from collections import deque
N, M, P = map(int, input().split())
graph = []
d = deque()



from_1 = [[] for i in range(N+1)]
from_N = [[] for i in range(N+1)]

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


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True


while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        graph.append((p, q, weight))




def bellman_ford(s,n):
    dist = [10**20 for i in range(n+1)]
    dist[s] = 0
    for i in range(1, n+1):
        flag = False
        for some in graph:
            a, b, d = some[0], some[1], some[2]
            newlen = dist[a]+d
            if newlen < dist[b]:
                flag = True
                dist[b] = newlen
        if not flag:
            break
        if i == n:
            return False
    return dist

K=bellman_ford(1,N)
if K==False:
     print(-1)
else:
    print(max(0,-K[N]))

Solution (Python):
N, M, P = map(int, input().split())
from collections import deque,defaultdict
edge1 = [[] for _ in range(N)]
edge2 = [[] for _ in range(N)]
for i in range(M):
    a,b,c= map(int, input().split())
    edge1[a-1].append([b-1,P-c])
    edge2[b-1].append([a-1,P-c])
edges1 = set()
d = deque([0])
visited1 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge1[v]:
        if visited1[w*10**8+v*10**4+u] == False:
            visited1[w*10**8+v*10**4+u] = True
            edges1.add(w*10**8+v*10**4+u)
            d.append(u)
edges2 = set()
d = deque([N-1])
visited2 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge2[v]:
        if visited2[w*10**8+u*10**4+v] == False:
            visited2[w*10**8+u*10**4+v] = True
            edges2.add(w*10**8+u*10**4+v)
            d.append(u)
new_edge = list(edges1&edges2)
d = [10**10]*N
d[0] = 0
n = 0
while True:
    n += 1
    update = False
    for e in new_edge:
        w = e//10**8
        v = e%10**8//10**4
        u = e%10**4
        if d[u]>d[v]+w:
            d[u] = d[v]+w
            update = True
    if update == False:
        break
    if n==N and update==True:
        print(-1)
        exit()
print(max(0,-d[-1]))

Solution (Python):
N, M, P = map(int, input().split())
Edges = []
pos = [[] for _ in range(N)]
neg = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    Edges.append((a-1, b-1, P-c))
    pos[a-1].append(b-1)
    neg[b-1].append(a-1)

from collections import deque

def dfs(s, lis):
    checked = [0]*N
    stack = deque([(s, 0)])
    while stack:
        v, c = stack.pop()
        if checked[v]!=0:
            continue
        checked[v] = 1
        for i in lis[v]:
            if checked[i]==0:
                stack.append((i, c+1))
    return checked

posc = dfs(0, pos)
negc = dfs(N-1, neg)
used = [0]*N
for i, (p, n) in enumerate(zip(posc, negc)):
    if p and n:
        used[i] = 1

def BellmanFord(s):
    inf = 10**18
    dist=[inf for i in range(N)]
    dist[s]=0
    for i in range(N):
        for edge in Edges:
            if used[edge[0]]==0 or used[edge[1]]==0:
                continue
            if edge[0] != inf and dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                if i>=N-1:
                    return []
    return dist

d = BellmanFord(0)
if len(d)==0:
    print(-1)
else:
    print(max(0, -d[-1]))

Solution (Python):
def shortest_path(s):
  dist[s]=0
  for _ in range(n):
    for fr,to,cost in edge:
      if dist[fr]!=inf and dist[to]>dist[fr]+cost:
        dist[to]=dist[fr]+cost

def find_negative_loops():
  for _ in range(n):
    for fr,to,cost in edge:
      if dist[fr]!=inf and dist[to]>dist[fr]+cost:
        dist[to]=dist[fr]+cost
        negative[to]=True
      if negative[fr]:negative[to]=True

n,m,p=map(int,input().split())
edge=[]
for i in range(m):
  a,b,c=map(int,input().split())
  edge.append([a-1,b-1,-c+p])
inf=float("inf")
dist=[inf]*n
negative=[False]*n
shortest_path(0)
find_negative_loops()
print(-1) if negative[-1] else print(max(-dist[-1],0))

Solution (Python):
n,m,p=map(int,input().split())
E=[list(map(int,input().split())) for i in range(m)]
INF=float("inf")
dist=[INF]*n
dist[0]=0
prev=0

for i in range(2*n):
  for fr,to,cost in E:
    fr,to=fr-1,to-1
    cost*=-1
    cost+=p
    if dist[fr]!=INF and dist[to]>dist[fr]+cost:
      dist[to]=dist[fr]+cost
      if i>=n:
        dist[to]=-float("inf")
    if i==n-1:
      prev=dist[n-1]
if prev==dist[n-1]:
  print(max(-dist[n-1],0))
else:
  print(-1)

Solution (Python):
import sys
sys.setrecursionlimit(500000) 
N,M,P = map(int,input().split())
N-=1 
INF = float("inf")
edge = []
to = [[] for _ in range(N+1)] 
rto = [[] for _ in range(N+1)] 
reachablefrom = [False for _ in range(N+1)] 
reachableto = [False for _ in range(N+1)] 
OK = [False for _ in range(N+1)] 
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 
  c-=P 
  c = -c 
  edge.append((a,b,c))
  to[a].append(b)
  rto[b].append(a)

def dfs(v):
  if reachablefrom[v]:
    return
  reachablefrom[v] = True
  for u in to[v]:
    dfs(u)

def rdfs(v):
  if reachableto[v]:
    return
  reachableto[v] = True
  for u in rto[v]:
    rdfs(u)
    
dfs(0)
rdfs(N)
for i in range(len(OK)): 
  OK[i] = reachablefrom[i]&reachableto[i]

d = [INF for _ in range(N+1)]
d[0] = 0 
upd = True 
step = 0
while upd:
  upd = False
  for i in range(M):
    a,b,c = edge[i]
    if not OK[a] or not OK[b]:
      continue
    new = d[a]+c
    if new < d[b]: 
      upd = True
      d[b] = new
  step += 1
  if step > N+10: 
    print("-1")
    sys.exit()
ans = -d[N] 
ans = max(0,ans)
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(500000) 
N,M,P = map(int,input().split())
N-=1 
INF = float("inf")
edge = []
to = [[] for _ in range(N+1)] 
rto = [[] for _ in range(N+1)] 
reachablefrom = [False for _ in range(N+1)] 
reachableto = [False for _ in range(N+1)] 
OK = [False for _ in range(N+1)] 
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 
  c-=P 
  c = -c 
  edge.append((a,b,c))
  to[a].append(b)
  rto[b].append(a)

def dfs(v):
  if reachablefrom[v]:
    return
  reachablefrom[v] = True
  for u in to[v]:
    dfs(u)

def rdfs(v):
  if reachableto[v]:
    return
  reachableto[v] = True
  for u in rto[v]:
    rdfs(u)
    
dfs(0)
rdfs(N)
for i in range(len(OK)): 
  OK[i] = reachablefrom[i]&reachableto[i]

d = [INF for _ in range(N+1)]
d[0] = 0 
upd = True 
step = 0
while upd:
  upd = False
  for i in range(M):
    a,b,c = edge[i]
    if not OK[a] or not OK[b]:
      continue
    new = d[a]+c
    if new < d[b]: 
      upd = True
      d[b] = new
  step += 1
  if step > N+1:
    print("-1")
    sys.exit()
ans = -d[N] 
ans = max(0,ans)
print(ans)

Solution (Python):


import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))


def resolve():
    N,M,P=pin()
    edge=[]
    for i in range(M):
        a,b,c=pin()
        edge.append((a-1,b-1,P-c))
    
    
    
    inf = float("inf")
    ans=[inf]*N
    ans[0]=0

    for i in range(N*2):
        for j in range(M):
            t,f,p=edge[j]
            ans[f]=min(ans[f],ans[t]+p)
            if  ans[f]>ans[t]+p:
                ans[f]=0-inf
    
        if i==N:
            temp=ans[-1]
        if i==N*2-1:
            if ans[-1]<temp:
                ans[-1]=0-inf
    t=(0-ans[-1])
    



    if t==inf:s=-1
    elif t<0:s=0
    else:s=t
    print(s)

resolve()

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

used1 = [0]*N
used1[0] = 1
from collections import deque
q = deque()
q.append(0)
while q:
    u = q.pop()
    for e in E[u]:
        if used1[e[0]] == 1:
            continue
        used1[e[0]] = 1
        q.append(e[0])

used2 = [0]*N
used2[N-1] = 1
q.append(N-1)
while q:
    u = q.pop()
    for e in E2[u]:
        if used2[e] == 1:
            continue
        used2[e] = 1
        q.append(e)

L = [0]*N
for i in range(N):
    L[i] = used1[i] & used2[i]
        
def BellmanFord(E, N, source):
    inf = 10**12
    d = [inf for _ in range(N)]
    d[source] = 0
    
    for i in range(N):
        for j in range(N):
            for edge in E[j]:
                if d[edge[0]] > d[j] + edge[1]:
                    d[edge[0]] = d[j] + edge[1]
                    if i == N-1 and L[edge[0]]== 1:
                        return -1
    
    return d

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

Solution (Python):
from collections import deque

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

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

def canVisit(start, edges):
    st = deque([start])
    minDist = [10**18] * N
    minDist[start] = 0

    while st:
        now = st.popleft()
        d = minDist[now] + 1
        for to in edges[now]:
            if minDist[to] > d:
                minDist[to] = d
                st.append(to)

    return [True if minDist[to] < 10**18 else False for to in range(N)]

canForward = canVisit(0, edges)
canBack = canVisit(N - 1, revEdges)

minDist = [10**18] * N
minDist[0] = 0
for i in range(N + 1):
    for fr, to, cost in E:
        d = minDist[fr] + cost
        if minDist[to] > d:
            if i == N and canForward[fr] and canBack[to]:
                print(-1)
                exit()

            minDist[to] = d

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

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
MOD = 10 ** 9 + 7
INF = 10 ** 18

N, M, P = map(int, input().split())
G = []
G_append = G.append

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

d = [INF] * (N + 1) 
d[1] = 0
def find_negative_loop1(): 
    for i in range(N):
        for j in range(M): 
            e = G[j]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                
                if i == N-1:
                    return True 
    return False 

def find_negative_loop2(): 
    check = [False] * (N + 1)
    for _ in range(N):
        for j in range(M): 
            e = G[j]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                check[e[1]] = True
            if check[e[0]]:
                check[e[1]] = True
    return check[N]


if find_negative_loop1():
    if find_negative_loop2():
        print (-1)
    else:
        print (max(0, -d[N]))
else:
    print (max(0, -d[N]))

Solution (Python):
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

es = [[] for _ in range(N)]
bs = [[] for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    es[a].append((b,c-P))
    bs[b].append((a,c-P))

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

bk_set = set([N-1])
stack = [N-1]
while stack:
    v = stack.pop()
    for to,_ in bs[v]:
        if to in bk_set: continue
        bk_set.add(to)
        stack.append(to)

use = go_set & bk_set
K = len(use)
INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(K):
    for v in range(N):
        if v not in use: continue
        for to,c in es[v]:
            if to not in use: continue
            if d[to] > d[v] - c:
                d[to] = d[v] - c
                if i==K-1:
                    print(-1)
                    exit()
print(max(0, -d[-1]))

Solution (Python):
import heapq
import sys
from collections import deque
input = sys.stdin.readline

INF = float('inf')

class Edge():
    def __init__(self, start, end, cost):
        self.start = start
        self.end = end
        self.cost = cost

def dijkstra(n, G, s):
    dist = [INF] * n
    dist[s] = 0
    h = []
    heapq.heappush(h, (0, s))

    while h:
        
        d, v = heapq.heappop(h)
        if dist[v] < d:
            continue
        
        for e in G[v]:
            if dist[e.end] > dist[v] + e.cost:
                dist[e.end] = dist[v] + e.cost
                heapq.heappush(h, (dist[e.end], e.end))
    return dist

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

g1 = [[] for _ in range(n)]
g2 = [[] for _ in range(n)]
es = []

abc = []

for _ in range(m):
    a, b, c = map(int, input().split())
    abc.append((a-1, b-1, c))
    g1[a-1].append(Edge(a-1, b-1, 1))
    g2[b-1].append(Edge(b-1, a-1, 1))

dist1 = dijkstra(n, g1, 0)
dist2 = dijkstra(n, g2, n-1)




ng = set({})

for i in range(n):
    if dist1[i] == INF or dist2[i] == INF:
        ng.add(i)

for a, b, c in abc:
    if a in ng or b in ng:
        continue
    es.append(Edge(a, b, p-c))

def bellman_ford(n, es, s):
    dist = [INF] * n
    dist[s] = 0
    
    
    
    while True:
        update = False
        
        for e in es:
            
            if dist[e.start] != INF and dist[e.end] > dist[e.start] + e.cost:
                dist[e.end] = dist[e.start] + e.cost
                update = True
        
        if not update:
            break
    return dist

def find_negative_loop(n, es):
    dist = [0] * n
    for i in range(n):
        for e in es:
            if dist[e.end] > dist[e.start] + e.cost:
                dist[e.end] = dist[e.start] + e.cost
                if i == n - 1:
                    return True
    return False

if find_negative_loop(n, es):
    print(-1)
    sys.exit()

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

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

grafo = []

for x in range(m):
    a,b,c = map(int,input().split())
    grafo.append((a-1,b-1,c-p))

def bellman_ford(v):
    distancia = [float("inf")] * n
    distancia[v] = 0
    for i in range(2 * n):
        for a,b,c in grafo:
            if distancia[b] > distancia[a] - c:
                distancia[b] = distancia[a] - c
                if i == n - 1:
                    distancia[b] = -float("inf")
    return distancia

distancia = bellman_ford(0)

if distancia[-1] ==  -float("inf"):
    print(-1)
else:
    if distancia[-1] > 0:
        print(0)
    else:
        print(-1 * distancia[-1])

Solution (Python):
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""
import sys
sys.setrecursionlimit(10**6)

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

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i 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) 
    rto[b].append(a) 
    
dfs(0)
rdfs(n-1)
for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] 

def main():
    global edges, ok
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    return
    
main()

Solution (Python):
n,m,p=map(int,input().split())
edge=[]
for i in range(m):
    a,b,c=map(int,input().split())
    edge.append((a,b,p-c))
INF=float('inf')
def bellmanford(s,n):
    d = [INF for i in range(n+1)]
    d[s]=0
    for i in range(n-1):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
    for i in range(n-1):
         for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=-INF
    return d
d=bellmanford(1,n)
if d[n]==-INF:
    print(-1)
elif d[n]>=0:
    print(0)
else:
    print(-d[n])

Solution (Python):
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product

def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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


def find_negative_loop1(n,w,es):
    
    
    d = [float("inf")] * n
    d[0] = 0
    infdic=defaultdict(int)
    
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    infdic[e[0]]=1
    return infdic

def find_negative_loop2(n,w,es,infd):
    
    
    d = [float("inf")] * n
    d[0] = 0
    for i in infd.keys():
        d[i]=-float('inf')
    
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                
                
    return d



w = m
es = [[] for i in range(w)] 
for i in range(w):
    x,y,z = abc[i]
    es[i] = [x-1,y-1,p-z]



tmp=find_negative_loop1(n,w,es)

tmp2=find_negative_loop2(n,w,es,tmp)

if tmp2[-1]==-float('inf'):
    print(-1)
else:
    print(-min(tmp2[-1],0))

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
INF = 10 ** 18


def reachable_nodes(s, edges):
    cur = {s}
    reachable = set()
    while cur:
        reachable |= cur
        cur = set().union(*(edges[node] for node in cur)) - reachable
    return reachable


def bellman_ford(n, edges, s):
    dists = [INF] * n
    dists[s] = 0
    for cnt in range(n):
        for u, v, cost in edges:
            if dists[u] != INF and dists[u] + cost < dists[v]:
                if cnt == n - 1:
                    return -1
                dists[v] = dists[u] + cost
    return dists


def solve():
    N, M, P = map(int, rl().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, rl().split())
        a, b = a - 1, b - 1
        A[i], B[i], C[i] = a, b, P - c
        to[a].append(b)
        reverse_to[b].append(a)
    
    reachable = reachable_nodes(0, to) & reachable_nodes(N - 1, reverse_to)
    
    edge_dict = dict()
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            edge_dict[(a, b)] = min(c, edge_dict.get((a, b), 10 ** 6))
    edges = [(u, v, cost) for (u, v), cost in edge_dict.items()]
    
    dists = bellman_ford(N, edges, 0)
    if dists == -1:
        print(-1)
    else:
        print(max(0, -dists[-1]))


if __name__ == '__main__':
    solve()

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

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

d = [float("inf") for _ in range(n)]
d[0] = 0



for i in range(n*2):
    for now, next, weight in edge:
        if d[next] > d[now] + weight + p:
            d[next] = d[now] + weight + p
            
            if i > n-1:
                d[next] = -float("inf")
                
        if i == n-1:
            prev = d[-1]
            
            
        



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

Solution (Python):
from collections import deque
def use_path(n,start,es):
    q = deque()
    chk = [False] * n
    q.append(start)
    chk[start] = True
    used = {start}
    while len(q) > 0:
        node = q.popleft()
        for nex in es[node]:
            if not chk[nex]:
                chk[nex] = True
                q.append(nex)
                used.add(nex)
    return used
  
def belman(s,g,n,es):
    d = [10**10] * n
    d[s] = 0
    fin = False
    cnt = 0
    while True:
      update = False
      for p,q,r in es:
        if d[p] != 10**10 and d[q] > d[p] + r:
          d[q] = d[p] + r
          update = True
      cnt += 1
      if not update:
        fin = True
        break
      if cnt > n+1:
          break      
    if fin:
        return max(0,-d[g])
    else:
        return -1   
  
n,m,p = map(int, input().split())

l = [[] for i in range(n)]
r = [[] for i in range(n)]
edges = []

for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    l[a].append(b)
    r[b].append(a)
    edges.append((a,b,-c+p))
    
use_nodes = use_path(n,0,l) & use_path(n,n-1,r)
es = [(a,b,c) for a,b,c in edges if a in use_nodes and b in use_nodes]
print(belman(0,n-1,n,es))

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

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

INF = 10**10

edges = [] 

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    if reachableFrom1[v]:
        return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    if reachableToN[v]:
        return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

for i 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)
    rto[b].append(a)


dfs(0)
rdfs(N-1)
for i in range(N):
    ok[i] = reachableFrom1[i] & reachableToN[i]


d = [INF for _ in range(N)]
d[0] = 0
upd = True
step = 0
flag = True
while upd:
    upd = False
    for i in range(M):
        a, b, c = edges[i]
        if not ok[a]:
            continue
        if not ok[b]:
            continue
        newD = d[a]+c
        if newD < d[b]:
            upd = True
            d[b] = newD
    step += 1
    if step > N:
        flag = False
        break
if flag:
    ans = -d[N-1]
    ans = max(ans, 0)
    print(ans)
else:
    print(-1)

Solution (Python):
INF = 10 ** 15
MOD = 10 ** 9 + 7

def beruman(n,X,edges,start = 0,negative_loop = False):
    ans = False 
    dist = [INF] * n
    dist[start] = 0

    for i in range(X):
        update = False
        for a,b,c in edges:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c
                update = True

        if not update:
            break
        if i == X - 1:
            ans = True
    
    if negative_loop:
        return dist,ans
    else:
        return dist

def dfs(G,can_reach,start):
    stack = [start]
    can_reach[start] = True
    while stack:
        v = stack.pop()
        for e in G[v]:
            if can_reach[e]:
                continue
            stack.append(e)
            can_reach[e] = True
    return can_reach

def main():
    N,M,P = map(int,input().split())
    edges = []
    G = [[] for _ in range(N)]
    G_inv = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = map(int,input().split())
        a -= 1
        b -= 1
        edges.append((a,b,P - c))
        G[a].append(b)
        G_inv[b].append(a)
    
    can_reach_from_start = [False] * N
    can_reach_from_goal = [False] * N
    dfs(G,can_reach_from_start,0)
    dfs(G_inv,can_reach_from_goal,N - 1)
    in_route = [False] * N
    X = 0
    for i in range(N):
        if can_reach_from_goal[i] and can_reach_from_start[i]:
            in_route[i] = True
            X += 1
        
    edge = []
    for a,b,c in edges:
        if in_route[a] and in_route[b]:
            edge.append((a,b,c))

    dist,flag = beruman(N,X,edge,0,True)
    if flag:
        print(-1)
    else:
        print(max(-dist[-1],0))
if __name__ == '__main__':
    main()