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):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,M,P = inpl()
lines = defaultdict(set)

for _ in range(M):
    a,b,c = inpl()
    a,b = a-1,b-1
    lines[a].add((b,-c+P))


def BellmanFord(Start,Goal):
    Costs=[INF]*N
    Costs[Start] = 0
    upd8s = [True]*N
    for i in range(2*N): 
        will_upd8s = [False]*N
        for s in range(N):
            if not upd8s[s]: continue    
            for t,c in lines[s]:
                if c + Costs[s] < Costs[t]:
                    Costs[t] = Costs[s]+c
                    will_upd8s[t] = True 
                    if i >= N:
                        Costs[t] = -INF

        if i == N-1: 
            tmp = Costs[Goal]

        upd8s = will_upd8s[:]

    if tmp != Costs[Goal]:
        return -INF
    else:
        return Costs[Goal]

ans = -BellmanFord(0,N-1)
if ans == INF:
    print(-1)
else:
    print(max(0,ans))

Solution (Python):
INF = float('inf')

def main():
    n, m, p = map(int,input().split())
    es = []
    for _ in range(m):
        e = list(map(int,input().split()))
        es.append([e[0]-1,e[1]-1,- e[2] + p])

    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
        if v == n-1:
            prev = v_cost[-1]

    if prev != v_cost[-1]:
        return -1

    return max(0,-v_cost[-1])
   

if __name__ =="__main__":
    print (main())

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
INF = float('inf')

def main():
    n, m, p = map(int,input().split())
    es = []
    for _ in range(m):
        e = list(map(int,input().split()))
        es.append([e[0]-1,e[1]-1,- e[2] + p])

    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
        if v == n-1:
            prev = v_cost[-1]

    if prev != v_cost[-1]:
        return -1

    return max(0,-v_cost[-1])
   

if __name__ =="__main__":
    print (main())

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
INF = float('inf')

def main():
    n, m, p = map(int,input().split())
    es = []
    for _ in range(m):
        e = list(map(int,input().split()))
        es.append([e[0]-1,e[1]-1,- e[2] + p])

    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
            if v == n-1:
                prev = v_cost[-1]
                
    if prev != v_cost[-1]:
        return -1

    return max(0,-v_cost[-1])
   

if __name__ =="__main__":
    print (main())

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

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, -c+P])


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c
                if i >= N:
                    dist[d] = -float('inf')

            if i == N-1:
                prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Solution (Python):
def validate(paths, start):
    """
    有効な経路をDFS(深さ優先探索)
    経路をsetで返す
    """

    valid_paths = {start}
    stack = [start]

    while stack:
        v = stack.pop()
        if v not in paths:
            continue
        for w in paths[v]:
            if w in valid_paths:
                continue
            valid_paths.add(w)
            stack.append(w)
    return valid_paths


def bellman_ford(edges, num_v, start, end):
    """
    有向グラフ(負閉路有り)の最短距離

    num_v: 頂点の数(number_of_vertex)
    edges: 頂点(from, to, cost)
    """

    
    INF = 10**18
    dist = [INF] * num_v
    
    dist[start] = 0

    
    
    for _ in range(num_v):
        updated = False
        for f, t, c in edges:
            if dist[f] == INF:
                continue

            
            cost = dist[f] + c
            if cost < dist[t]:
                dist[t] = cost
                updated = True
        if not updated:
            break
    else:
        
        return -1

    return max(-dist[end], 0)


def main():
    from collections import defaultdict

    n, m, p, *tmp = map(int, open(0).read().split())

    paths_rev = defaultdict(list)
    edges = []
    for a, b, c in zip(*[iter(tmp)]*3):
        
        paths_rev[b-1].append(a-1)
        edges.append((a-1, b-1, p-c))

    valid_paths = validate(paths_rev, n-1)
    edges = [
        (a, b, c)
        for a, b, c in edges
        if a in valid_paths and b in valid_paths
    ]
    res = bellman_ford(edges, n, 0, n-1)
    print(res)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque, defaultdict

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

edge_dic = defaultdict(lambda: [])
reverse_edge_dic = defaultdict(lambda: [])

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

forward_set = set()
node_deque = deque()
node_deque.append(0)
forward_set.add(0)
while len(node_deque):
    edge = node_deque.pop()
    for v in edge_dic[edge]:
        goal, cost = v
        if goal not in forward_set:
            forward_set.add(goal)
            node_deque.append(goal)

backward_set = set()
node_deque = deque()
node_deque.append(N-1)
backward_set.add(N-1)
while len(node_deque):
    edge = node_deque.pop()
    for v in reverse_edge_dic[edge]:
        goal, cost = v
        if goal not in backward_set:
            backward_set.add(goal)
            node_deque.append(goal)
can_use = forward_set & backward_set


new_edge_dic = {i: edge_dic[i] for i in can_use}

INF = 10 ** 10

ans_array = [-INF] * N
ans_array[0] = 0


for i in range(len(can_use)+1):
    change_flag = 0
    for key, value in new_edge_dic.items():
        for v in value:
            goal, cost = v
            if ans_array[goal] < ans_array[key] + cost:
                ans_array[goal] = ans_array[key] + cost
                change_flag = 1
    if change_flag == 0:
        break
else:
    print(-1)
    exit()

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

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    
    
    dist = [-float('inf') for _ in range(num_v)]
    
    dist[start] = 0
    flg = 0
    for i in range(num_v):
        update = False
        for edge in edges:
            e_from, e_to, e_cost = edge
            if e_from != -float('inf') and visited[e_to] and dist[e_to] < dist[e_from] + e_cost:
                dist[e_to] = dist[e_from] + e_cost
                update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
f = defaultdict(dict)
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
    f[b-1][a-1] = 1
visited = [False]*n
def dfs(x):
    visited[x] = True
    for t in f[x].keys():
        if not visited[t]:
            dfs(t)
dfs(n-1)
d,f = Bellman_Ford(edge,n,0)
if not f:
    print(-1)
else:
    print(max(0,d[-1]))

Solution (Python):
from collections import deque, defaultdict

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

edge_dic = defaultdict(lambda: [])
reverse_edge_dic = defaultdict(lambda: [])

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



INF = 10 ** 10

ans_array = [-INF] * N
ans_array[0] = 0

for i in range(N+1):
    change_flag = 0
    for key, value in edge_dic.items():
        for v in value:
            goal, cost = v
            if ans_array[goal] < ans_array[key] + cost:
                ans_array[goal] = ans_array[key] + cost
                change_flag = 1
    if change_flag == 0:
        break
else:
    forward_set = set()
    node_deque = deque()
    node_deque.append(0)
    forward_set.add(0)
    while len(node_deque):
        edge = node_deque.pop()
        for v in edge_dic[edge]:
            goal, cost = v
            if goal not in forward_set:
                forward_set.add(goal)
                node_deque.append(goal)

    backward_set = set()
    node_deque = deque()
    node_deque.append(N-1)
    backward_set.add(N-1)
    while len(node_deque):
        edge = node_deque.pop()
        for v in reverse_edge_dic[edge]:
            goal, cost = v
            if goal not in backward_set:
                backward_set.add(goal)
                node_deque.append(goal)
    can_use = forward_set & backward_set
    

    new_edge_dic = {i: edge_dic[i] for i in can_use}

    ans_array = [-INF] * N
    ans_array[0] = 0
    for i in range(len(can_use)+1):
        change_flag = 0
        for key, value in new_edge_dic.items():
            for v in value:
                goal, cost = v
                if ans_array[goal] < ans_array[key] + cost:
                    ans_array[goal] = ans_array[key] + cost
                    change_flag = 1
        if change_flag == 0:
            break
    else:
        print(-1)
        exit()
    
ans = max(0, ans_array[N-1])
print(ans)

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

f_inf = float("inf") 

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append((B, C - P))
    else:
        ABC_d[A] = [(B, C - P)]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2

def solve(pos, cnt, num_sum):
    global cost

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum + B)

solve(1, 1, 1)

if (cost[-1] == f_inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

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

f_inf = sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt > N: cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)

solve(1, 1)

if (cost[-1] == sys.maxsize):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Solution (Python):
words = lambda t : list(map(t, input().split()))
n,m,p = words(int)

w_edges = []
f_edges = [[] for _ in range(n)]
b_edges = [[] for _ in range(n)]

for i in range(m):
    a,b,c = words(int)
    w_edges.append((a-1,b-1,c))
    f_edges[a-1].append((b-1))
    b_edges[b-1].append((a-1))

from queue import Queue
def bfs(edges,stt):
    visited = [False] * n
    q = Queue()
    q.put(stt)
    visited[stt] = True
    while not q.empty():
        v = q.get()
        for c in edges[v]:
            if not visited[c]:
                visited[c] = True
                q.put(c)
    return visited

f_visited = bfs(f_edges, 0)
b_visited = bfs(b_edges, n-1)

edges = []
for a,b,c in w_edges:
    if f_visited[a] and b_visited[a] and f_visited[b] and b_visited[b]:
        edges.append((a,b,p-c))

def bellman_ford(edges, num_v, stt):
    inf = float('inf')
    dist = [inf]*num_v
    dist[stt] = 0
    for i in range(num_v+1):
        for a,b,c in edges:
            prev = dist[b]
            dist[b] = min(dist[b], dist[a]+c)
            if i == num_v and prev != dist[b]:
                return -1
    return dist

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

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    E = []
    rE = [[] for _ in range(N)]
    
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        E.append((a,b,c-P))
        rE[b].append(a)
    
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in rE[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for s, t, cost in E:
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) 
    for _ in range(I-1):
        for s, t, cost in E:
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    for i in range(N):
        if W[i] == None or G[i] == False:
            continue
        if V[i] > W[i]: 
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Solution (Python):
import sys
def main():
    N, M, P = map( int, input().split())
    INF = 1e18
    d = list()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d.append((a,b,P-c))
    V = [INF]*N
    V[0] = 0
    for _ in range(N):
        for (s,t,cost) in d:
            if V[s] != INF:
                V[t] = min(V[t], V[s] + cost)

    for _ in range(N):
        for (s,t,cost) in d:
            if V[s] != INF:
                if V[t] > V[s] + cost:
                    V[t]=-INF

    if V[-1] == -INF:
        print(-1)
    else:
        print( max(-V[-1], 0))
if __name__ == '__main__':
    main()

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

    edges = []
    for i in range(m):
        edges.append(tuple(map(int, input().split())))

    edges.sort(key=lambda x: x[1])
    dist = [float('inf') for i in range(n)]
    dist[0] = 0

    for i in range(n):
        for e in edges:
            if dist[e[1]-1] > dist[e[0]-1] - (e[2] - p):
                dist[e[1]-1] = dist[e[0]-1] - (e[2] - p)

    for i in range(n):
        for e in edges:
            if dist[e[1] - 1] > dist[e[0] - 1] - (e[2] - p):
                dist[e[1]-1] = float('-inf')

    if dist[n-1] == float('-inf'):
        print(-1)
    else:
        print(-dist[n-1] if -dist[n-1] >= 0 else 0)


if __name__ == '__main__':
    e()

Solution (Python):

import sys
import math
from collections import defaultdict


sys.setrecursionlimit(10**7)


mod = 10**9 + 7


def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))



def BF(E,s,n):
    inf=float("inf")
    d=[inf for _ in range(n)]
    d[s]=0
    for i in range(2*n):
        for e in E:
            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:
                    d[e[1]] = -float('inf')
    return d

N,M,P = II()
A,B,C = Line(M)
E = []
for i in range(M):
    E.append([A[i]-1, B[i]-1, -C[i]+P])

d = BF(E,0,N)
if d[N-1]==-float('inf'):
    print(-1)
else:
    print(max(0,-d[N-1]))

Solution (Python):
import sys
sys.setrecursionlimit(10**9)

N,M,P = map(int,input().split())
edges = []
to = [[] for i in range(N)]
rto = [[] for i in range(N)]
for i in range(M) :
    u,v,cost = map(int,input().split())
    u -= 1
    v -= 1
    cost -= P
    cost *= -1
    edges.append([u,v,cost])
    to[u].append(v)
    rto[v].append(u)

canVisitFromS = [False]*N
canVisitFromG = [False]*N

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

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

dfs(0)
rdfs(N-1)

OK = [canVisitFromS[i]*canVisitFromG[i] for i in range(N)]

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

ans = 0
step = 0
update = True
while update :
    update = False
    for i in range(M) :
        u,v,cost = edges[i]
        if OK[u]*OK[v] == 0 : continue
        if dist[v] > dist[u] + cost :
            dist[v] = dist[u] + cost
            update = True
    step += 1
    if step > N :
        ans = -1
        break

if ans != -1 :
    ans = max(0, dist[N-1]*(-1))

print(ans)

Solution (Python):
from collections import deque
NegInf = -float('inf')


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


def bellman_ford(vst, graph, node_num, NegInf):
    costs = [NegInf] * node_num
    costs[0] = 0
    v_nows = set([vst])
    for _ in range(n):
        v_changeds = set()
        for v_from in v_nows:
            for v_to, cost in graph[v_from]:
                c2 = costs[v_from] + cost
                if c2 > costs[v_to]:
                    costs[v_to] = c2
                    v_changeds.add(v_to)
        v_nows = v_changeds



    if not v_changeds:
        return costs

    for i in v_nows:
        costs[i] = NegInf

    que = deque(v_nows)
    while que:
        v_from = que.popleft()
        for v_to, cost in graph[v_from]:
            if costs[v_to] != NegInf:
                costs[v_to] = NegInf
                que.append(v_to)
    return costs


costs = bellman_ford(0, graph, n, -float('inf'))
if costs[n-1] == NegInf:
    print(-1)
else:
    print(max(0, costs[n-1]))

Solution (Python):
import sys
N, M, P = map(int, input().split())
Edge = []
G = [[] for i in range(N)]
G_rev = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, sys.stdin.readline().split())
    a, b = a - 1, b - 1
    c = -(c - P)
    Edge.append([a, b, c])
    G[a].append(b)
    G_rev[b].append(a)



def dfs(g, stack):
    can_reach = set()
    while stack:
        n = stack.pop()
        can_reach.add(n)
        for to in g[n]:
            if to in can_reach:
                continue
            stack.append(to)
    return can_reach


can_reach_from_0 = dfs(G, [0])
can_reach_from_N = dfs(G_rev, [N - 1])

can_reach_from_0_and_N = can_reach_from_0 & can_reach_from_N
EdgeShifted = []
for a, b, c in Edge:
    if (a in can_reach_from_0_and_N) and (b in can_reach_from_0_and_N):
        EdgeShifted.append([a, b, c])



dist = [float('inf')] * N
dist[0] = 0

for n in range(len(can_reach_from_0_and_N)):
    for fr, to, cost in EdgeShifted:
        if dist[to] > dist[fr] + cost:
            dist[to] = dist[fr] + cost
            
            if n == len(can_reach_from_0_and_N) - 1:
                print(-1)
                exit()

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

Solution (Python):
def bellman_ford(v, G):
    import copy
    INF = 10 ** 10
    ret = [INF] * len(G)
    ret[v] = 0

    for _ in range(len(G) - 1):
        for u, g in enumerate(G):
            for w, l in g:
                if not ret[u] == INF and ret[w] > ret[u] + l:
                    ret[w] = ret[u] + l

    for _ in range(len(G) - 1):
        for u, g in enumerate(G):
            for w, l in g:
                if not ret[w] == INF and ret[w] > ret[u] + l:
                    ret[w] = -INF

    return ret


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

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

ans = bellman_ford(0, G)[-1]
print("-1" if ans == -10 ** 10 else max(-ans, 0))

Solution (Python):
import sys
sys.setrecursionlimit(10**9)

N,M,P = map(int,input().split())
edges = []
L = [[] for i in range(N)]
utov = [[] for i in range(N)]
vtou = [[] for i in range(N)]

for i in range(M) :
    u,v,cost = map(int,input().split())
    u -= 1
    v -= 1
    cost -= P
    cost *= -1
    edges.append([u,v,cost])
    utov[u].append(v)
    vtou[v].append(u)

reachableFromS = [False]*N
reachableFromG = [False]*N

def dfs(u) :
    if reachableFromS[u] :
        return
    reachableFromS[u] = True
    for v in utov[u] :
        dfs(v)

def dfs2(v) :
    if reachableFromG[v] :
        return
    reachableFromG[v] = True
    for u in vtou[v] :
        dfs2(u)

dfs(0)
dfs2(N-1)

OK = [reachableFromS[i] * reachableFromG[i] for i in range(N)]

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

ans = 0
step = 0
update = True

while update :
    update = False
    for i in range(M) :
        u,v,cost = edges[i]
        if OK[u] * OK[v] == 0 :
            continue
        if dist[v] > dist[u] + cost :
            dist[v] = dist[u] + cost
            update = True
    
    step += 1
    if step > N :
        ans = -1
        break

if ans != -1 :
    ans = max(0, dist[N-1] * (-1))
print(ans)

Solution (Python):
from collections import deque
N,M,P = map(int, input().split())
R = []
R2 = {}
R3 = {}
OPT = [float("inf")]*(N+1)
for _ in range(M):
    A,B,C = map(int, input().split())
    R.append([A,B,-C+P])
    if not B in R2:
        R2[B] = []
    if not A in R3:
        R3[A] = []
    R3[A].append(B)
    R2[B].append(A)

visited_N = [0]*(N+1)
visited_N[N] = 1
queue = deque()
queue.append(N)

while queue != deque():
    tmp = queue.pop()
    if tmp in R2:
        for i in R2[tmp]:
            if visited_N[i] == 0:
                visited_N[i] = 1
                queue.append(i)    

visited_1 = [0]*(N+1)
visited_1[1] = 1
queue = deque()
queue.append(1)

while queue != deque():
    tmp = queue.pop()
    if tmp in R3:
        for i in R3[tmp]:
            if visited_1[i] == 0:
                visited_1[i] = 1
                queue.append(i)    

visited = [0]*(N+1)
for i in range(N):
    visited[i+1] = visited_N[i+1]*visited_1[i+1]
                
OPT[1] = 0
OPT_tmp = OPT

for _ in range(N-1):
    for i in range(M):
        tmp_r = R[i]
        if visited[tmp_r[0]] == 1 and visited[tmp_r[1]] == 1:
            if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
                OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
tmp_opt = OPT[N]

flag = 0
for i in range(M):
    tmp_r = R[i]
    if visited[tmp_r[0]] == 1 and visited[tmp_r[1]] == 1:
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            flag = 1
    
if flag:
    answer = -1
else:
    answer = max(0,-tmp_opt)

print(answer)

Solution (Python):
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
revedgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  revedgedict[t-1][f-1] = 1


visited = [False] * N
def dfs(f):
  visited[f] = True
  for t in revedgedict[f].keys():
    if not visited[t]:
      dfs(t)
dfs(N-1)


INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(N):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and visited[t] and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Solution (Python):
import sys
sys.setrecursionlimit((10 ** 6))
input = sys.stdin.readline
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for e in range(N):
        for w, c in G[e]:
            if dist[e] != INF and dist[w] > dist[e] + c:
                dist[w] = dist[e] + c

ans = -dist[N - 1]
is_negative = [False] * N
for i in range(N):
    for e in range(N):
        for w, c in G[e]:
            if dist[e] != INF and dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                is_negative[w] = True

            if is_negative[e]:
                is_negative[w] = True

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

Solution (Python):
from collections import deque

def BellmanFord(adjList, vSt, INF):
    numV = len(adjList)
    negINF = -INF
    costs = [INF] * numV
    costs[vSt] = 0
    vNows = set([vSt])

    for _ in range(numV):
        vChangeds = set()
        for vFr in vNows:
            costFr = costs[vFr]
            for vTo, wt in adjList[vFr]:
                c2 = costFr + wt
                if c2 < costs[vTo]:
                    costs[vTo] = c2
                    vChangeds.add(vTo)
        if not vChangeds:
            return costs
        vNows = vChangeds

    for v in vNows:
        costs[v] = negINF

        Q = deque(vNows)
    while Q:
        vFr = Q.popleft()
        for vTo, wt in adjList[vFr]:
            if costs[vTo] == negINF: continue
            costs[vTo] = negINF
            Q.append(vTo)

    return costs


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

costs = BellmanFord(adjL, 0, float('inf'))

if costs[N-1] == -float('inf'):
    print(-1)
else:
    print(max(0, -costs[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):
    INF = 10**18
    
    d = [INF] * v
    
    d[s] = 0
    
    for _ in range(v):
        f = False
        for a, b, c in e:
            if d[a]==INF:continue
            
            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)
    
    
    """
    
    use = 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()