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(10000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from itertools import *
INF = float('inf')

def bellmanford(edges, s, t, se):
    N = len(edges)
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        update = False
        for v in range(N):
            if v in se and dist[v] == INF:
                continue
            for u, c in edges[v]:
                if u not in se:
                    continue
                d = dist[v] + c
                if d < dist[u]:
                    dist[u] = d
                    update = True
        if update == False:
            return max(0, -dist[t])
    else:
        return -1

N, M, P = map(int, input().split())
es = [[] for i in range(N)]
es_r = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    es[a-1].append((b-1, P-c))
    es_r[b-1].append(a-1)
reachable1 = [False] * N
def dfs(v):
    if reachable1[v]: return
    reachable1[v] = True
    for u, c in es[v]:
        dfs(u)
reachable2 = [False] * N
def rdfs(v):
    if reachable2[v]: return
    reachable2[v] = True
    for u in es_r[v]:
        rdfs(u)
dfs(0)
rdfs(N-1)
se = set()
for i in range(N):
    if reachable1[i] and reachable2[i]:
        se.add(i)
print(bellmanford(es, 0, N-1, se))

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

def belman(egdes, N, start, end):
    INF = int(1e10)
    cost = [INF] * N
    cost[start] = 0
    fin = False
    count = 0
    while True:
        no_change = True
        for edge in egdes:
            from_, to_, d = edge
            tmp = cost[from_] + d
            if cost[to_] > tmp:
                no_change = False
                cost[to_] = tmp
        count += 1
        if no_change:
            fin = True
            break
        elif count > N+1:
            break
    
    if fin:
        return max(0, -cost[end])
    else:
        return -1

def bfs(link, N, start):
    q = deque()
    check = [False] * N
    q.append(start)
    check[start] = True
    used = {start}
    while len(q) > 0:
        node = q.popleft()
        for next_ in link[node]:
            if not check[next_]:
                check[next_] = True
                q.append(next_)
                used.add(next_)
    return used
        

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

    link = [[] for i in range(N)]
    rlink = [[] for i in range(N)]
    edges = []

    for i in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        link[a].append(b)
        rlink[b].append(a)
        edges.append((a, b, -(c-P)))
    
    use_nodes = bfs(link, N, 0) & bfs(rlink, N, N-1)
    use_edges = [(a, b, c) for a, b, c in edges if a in use_nodes and b in use_nodes]
    print(belman(use_edges, N, 0, N-1))

if __name__ == "__main__":
    main()

Solution (Python):
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

def main():
    N, M, P = mis()
    
    to = [[] for _ in range(N)]
    ot = [[] for _ in range(N)]
    edges = []

    for i in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        c = -(c-P)
        
        to[a].append(b)
        ot[b].append(a)
        edges.append((a,b,c))

    reachableFrom0 = set()
    reachableToN = set()

    
    reachableFrom0.add(0)
    nodes = [0]
    while nodes:
        node = nodes.pop()
        for i in to[node]:
            if i not in reachableFrom0:
                nodes.append(i)
                reachableFrom0.add(i)

    
    reachableToN.add(N-1)
    nodes = [N-1]
    while nodes:
        node = nodes.pop()
        for i in ot[node]:
            if i not in reachableToN:
                nodes.append(i)
                reachableToN.add(i)


    ok = reachableFrom0 & reachableToN

    edges = tuple((a, b, c) for a, b, c in edges if a in ok and b in ok)

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

    def bf(n):
        for _ in range(n):
            upd = False
            for a, b, c in edges:
                if V[b] > V[a] + c:
                    V[b] = V[a] + c
                    upd = True
            if not upd:
                return False
        return True

    bf(N)

    if not bf(1):
        print(max(-V[-1], 0))
    else:
        print(-1)

main()

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


def BFord(n,es):
    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[:]
    v_cost = [-INF if prev[idx]!=v_cost[idx] else v_cost[idx] for idx in range(n)]
    return v_cost
    

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 = BFord(n,es)

    if v_cost[-1] == -INF:
        return -1

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


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

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

n, m, p = map(int, input().split())
routes =[]
bt = [[] for _ in range(n+1)]

for i in range(m):
    a, b, c = map(int, sys.stdin.readline().split())
    routes.append([a, b, -1 * (c - p)])
    bt[b].append(a)

enable = set()
enable.add(n)
for i in range(n):
    for j in range(1, n+1):
        if j in enable:
            for k in bt[j]:
                if not k in enable:
                    enable.add(k)

inf = float('inf')
costs = [inf for _ in range(n+1)]
costs[1] = 0
error = False
for i in range(n):
    for route in routes:
        if route[1] in enable and costs[route[0]] + route[2] < costs[route[1]]:
            costs[route[1]] = costs[route[0]] + route[2]
            if i == n-1:
                error = True
                break
if error == True:
    print(-1)
else:
    print(max(0, -1 * costs[n]))

Solution (Python):
from collections import deque
import math

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)   

def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): 
        updated = False
        for u,v,c in dist: 
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)     
    
use = bfs(edge1, 0) & bfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

Solution (Python):
from collections import deque
import math
    
def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): 
        updated = False
        for u,v,c in dist: 
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)    
        

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)    
    
use = bfs(edge1, 0) & bfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

Solution (Python):
from collections import deque
import math
    
def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): 
        updated = False
        for u,v,c in dist: 
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)    
        

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)    
    
use = dfs(edge1, 0) & dfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

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

ok = [False for i in range(2505)]
def Bellmanford(edges, n, s):
    d = [float("inf") for i in range(n)]
    d[s] = 0


    for i in range(n):
        for x, y, z in edges:
            if not ok[x] or not ok[y]:
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if i == n - 1:
                    print(-1)
                    exit()
    print(max(0, -d[n - 1]))


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

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

    
    can_reach_to = [False for i in range(n+1)]
    can_reach_rto = [False for i in range(n+1)]
    def todfs(i):
        if can_reach_to[i]:
            return 0
        can_reach_to[i] = True
        for v in to[i]:
            todfs(v)
    def rtodfs(i):
        if can_reach_rto[i]:
            return 0
        can_reach_rto[i] = True
        for v in rto[i]:
            rtodfs(v)
    todfs(0)
    rtodfs(n-1)
    for i in range(n):
        ok[i] = (can_reach_to[i] & can_reach_rto[i])

    d = Bellmanford(e, n, 0)


if __name__ == '__main__':
    main()

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


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

    
    return divisors


def factorize(n):
    fct = []  
    b, e = 2, 0  
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct


def is_prime(n):
    if n == 1:
        return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True


def primes(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5) + 1):
        if not is_prime[i]:
            continue
        for j in range(i * 2, n + 1, i):
            is_prime[j] = False
    return [i for i in range(n + 1) if is_prime[i]]


def modpow(a, n, mod):
    res = 1
    while n > 0:
        if n & 1:
            res = res * a % mod
        a = a * a % mod
        n >>= 1
    return res


def modinv(a, mod):
    return modpow(a, mod - 2, mod)


def cnk(a, b):
    MOD = 10**9+7
    ret = 1
    for i in range(b):
        ret *= (a-i)
        ret %= MOD
        ret = ret * modinv(i+1, MOD) % MOD
    return ret


def Dijkstra(n, start, e):
    
    
    
    
    n += 10

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

    pathnum = [0 for i in range(n)]
    pathnum[start] = 1

    visited = [False for i in range(n)]
    q = []
    heappush(q, (0, start))
    while len(q):
        now_distance, v = heappop(q)
        if visited[v]:
            continue
        visited[v] = True
        for next_v, next_distance in e[v]:
            if visited[next_v]:
                continue
            dd = now_distance + next_distance
            if d[next_v] > dd:
                d[next_v] = dd
                heappush(q, (dd, next_v))
            if d[next_v] == dd:
                pathnum[next_v] += pathnum[v]
                pathnum[next_v] %= MOD

    return d, pathnum


def warshall_floyd(d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    return d


class UnionFind:
    def __init__(self, n):
        self.sz = [-1 for i in range(n)]

    
    def find(self, x):
        if self.sz[x] < 0:
            return x
        else:
            self.sz[x] = self.find(self.sz[x])
            return self.sz[x]

    

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.sz[x] > self.sz[y]:
            x, y = y, x
        self.sz[x] += self.sz[y]
        self.sz[y] = x

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def size(self, x):
        return -self.sz[self.find(x)]


class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        
        self.weight = [0] * (n+1)

    
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]






@functools.lru_cache(maxsize=None)
class UNION_FIND(object):
    def __init__(self, n):
        self.parent = [-1 for i in range(n)]

    def root(self, x):
        if self.parent[x] < 0:
            return x
        else:
            self.parent[x] = self.root(self.parent[x])
            return self.parent[x]

    def size(self, x):
        return -self.parent[self.root(x)]

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return False
        if self.size(x) < self.size(y):
            x, y = y, x
        self.parent[x] += self.parent[y]
        self.parent[y] = x
        return True


def compute_mst_kruskal(max_v, edges):
    edges.sort(key=lambda x: x[2], reverse=1)
    uf = UNION_FIND(max_v)
    mst = []
    for (a, b, c, d) in edges:
        if uf.root(a-1) != uf.root(b-1):
            uf.union(a-1, b-1)
            mst += [d+1]
    return mst

















class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, s, t):
        self.level = level = [None]*self.N
        deq = deque([s])
        level[s] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10**9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow


































ok = [False for i in range(2505)]


def Bellmanford(edges, n, s):
    d = [float("inf") for i in range(n)]
    d[s] = 0

    
    
    
    for i in range(n):
        for x, y, z in edges:
            if not ok[x] or not ok[y]:
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if i == n - 1:
                    print(-1)
                    exit()
    
    
    
    
    
    
    
    print(max(0, -d[n - 1]))


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

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

    can_reach_to = [False for i in range(n+1)]
    can_reach_rto = [False for i in range(n+1)]

    def todfs(i):
        if can_reach_to[i]:
            return 0
        can_reach_to[i] = True
        for v in to[i]:
            todfs(v)

    def rtodfs(i):
        if can_reach_rto[i]:
            return 0
        can_reach_rto[i] = True
        for v in rto[i]:
            rtodfs(v)
    todfs(0)
    rtodfs(n-1)
    for i in range(n):
        ok[i] = (can_reach_to[i] & can_reach_rto[i])

    d = Bellmanford(e, n, 0)


if __name__ == '__main__':
    main()

Solution (Python):
n,m,p = map(int, input().split())
edge = []
e1 = [list() for _ in range(n+1)]
for _ in range(m):
  a,b,c = map(int, input().split())
  edge.append((a,b,p-c))
  e1[a].append(b)
dis = [float("inf")]*(n+1)
dis[1] = 0
t = []
for i in range(n):
  for a,b,c in edge:
    if dis[b] > dis[a] + c:
      dis[b] = dis[a] + c
      if i == n-1:
        t.append(b)
s = set(t)
while t:
  v = t.pop()
  for x in e1[v]:
    if x == n:
      print(-1)
      exit(0)
    if x in s:
      continue
    s.add(x)
    t.append(x)
print(max(0,-dis[n]))

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

sys.setrecursionlimit(10000000)

N,M,P=map(int,input().split())
INF = 1000000000
edge = []
to = [[] for _ in range(N)]
rto = [[] for _ in range(N)]
reachable_from1 = [False]*N
reachable_fromN = [False]*N
for i in range(M):
    a,b,c = map(int,input().split())
    a-=1
    b-=1
    c=-c
    to[a].append(b)
    rto[b].append(a)
    edge.append([a,b,c])

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

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

dfs(0)
rdfs(N-1)
ok = [False]*N
for i in range(N):
    ok[i] = reachable_from1[i]&reachable_fromN[i]

d = [INF]*N
d[0] = 0
update = True
step=0
while update:
    update = False
    for i in range(M):
        a,b,c=edge[i]
        if not(ok[a]): continue
        newD = d[a]+c+P
        if newD < d[b]:
            d[b] = newD
            update = True
    step+=1
    if step > N:
        print(-1)
        sys.exit()
print(max(0,-d[N-1]))

Solution (Python):
N, M, P = map(int, input().split())
E = dict()
for i in range(M):
    a, b, c = map(int, input().split())
    E[(i, a, b)] = c-P
INF = float('inf')

dist = {i: -INF for i in range(1, N+1)}
dist[1] = 0
ans = 0
for i in range(N*2):
    for iuv, c in E.items():
        _, u, v = iuv
        if dist[v] < dist[u] + c:
            dist[v] = dist[u] + c
            if i >= N:
                dist[v] = INF
    if i == N-1:
        ans = dist[N]

print(max(0, dist[N]) if ans == dist[N] else -1)

Solution (Python):



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

abc=[list(map(int,input().split())) for _ in range(m)]
abc=[[a,b,p-c] for a,b,c in abc]
def BF(edges,num_v,source):
    
    inf=float("inf")
    dist=[inf for i in range(num_v)]
    dist[source-1]=0
  
    
    neg=[False for _ in range(num_v)]
    for i in range(num_v-1):
        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]
    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]
                neg[edge[1]-1]=True
            if neg[edge[0]-1]==True:
                neg[edge[1]-1]=True
    return dist,neg
dis,neg=BF(abc,n,1)

print(-1 if neg[-1] else max(0,-dis[-1]))

Solution (Python):
def is_reachable(edges,start,end):
  g = {}
  for f,t,w in edges:
    if f in g: g[f].append(t)
    else: g[f] = [t]
  visiting = [start]
  visited = {}
  while visiting:
    v = visiting.pop()
    if v in visited: continue
    if v == end: return True
    visited[v] = True
    for v2 in g.get(v, ()):
      if v2 in visited or v2 in visiting: continue
      visiting.append(v2)
  return False

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

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

neg_inf = float("-Inf")
no_answer = False

start = 1
end = N

distance = {}
for i in range(1,N+1):
  distance[i] = neg_inf
distance[start] = 0

for i in range(N-1):
    for f,t,w in edges:
        if distance[f] + w - P > distance[t]:
            distance[t] = distance[f] + w - P

for f,t,w in edges:
    if distance[f] + w - P > distance[t] and is_reachable(edges,t,end):
        no_answer = True
        break

if no_answer:
    print(-1)
else:
    print(max(0,distance[end]))

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')


def bellmanford(edge,N):
    costs = [inf] * N
    costs[0] = 0
    exist_minus_cycle = False
    for i in range(N):
        update = False
        for from_, to, cost in edge:
            cost_to = costs[from_] + cost
            if cost_to < costs[to]:
                update = True
                costs[to] = cost_to
                
        if not update:
            break
        elif i==N-1:
            exist_minus_cycle = True

    
    minus_cycle = set()
    if exist_minus_cycle:
        for i in range(N+1):
            for from_, to, cost in edge:
                cost_to = costs[from_] + cost
                if from_ in minus_cycle:
                    minus_cycle.add(to)
                if cost_to < costs[to]:
                    minus_cycle.add(from_)
                    minus_cycle.add(to)
                    costs[to] = cost_to
    return costs, minus_cycle


def main():
    N,M,P = MI()
    edges = []
    for _ in range(M):
        A,B,C = MI_()
        cost = P - (C+1)
        edges.append((A,B,cost))

    
    costs,minus_cycle = bellmanford(edges,N)

    if N-1 in minus_cycle :
        print(-1)
    else:
        print(max(0,-costs[-1]))



if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque


def bellman_ford(start: int, goal: int, graph: list) -> list:
    '''bellman-ford法: 始点startから終点goalへの最小コストを求める
    重み付きグラフgraphは隣接リストで与えられ、辺のコストは負でも良い
    次の3種類のパターンが存在する
        1. 始点startから終点goalにたどり着くことが不可能である
           -> float("inf")を返す

        2. 始点startから終点goalにたどり着くことが可能であり、
           パス上に負閉路が存在する
           -> -float("inf")を返す

        3. 始点startから終点goalにたどり着くことが可能であり、
           パス上に負閉路が存在しない
           -> 最小コストを返す

    計算量: O(|E||V|)
    '''
    INF = float("inf")
    n = len(graph)

    
    is_reachable = [False] * n
    is_reachable[start] = True
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, _ in graph[pos]:
            if is_reachable[next_pos]:
                continue
            is_reachable[next_pos] = True
            q.append(next_pos)

    
    reverse_graph = [[] for i in range(n)]
    for pos, edge in enumerate(graph):
        for next_pos, cost in edge:
            reverse_graph[next_pos].append((pos, cost))

    is_rev_reachable = [False] * n
    is_rev_reachable[goal] = True
    q = deque([goal])
    while q:
        pos = q.popleft()
        for next_pos, _ in reverse_graph[pos]:
            if is_rev_reachable[next_pos]:
                continue
            is_rev_reachable[next_pos] = True
            q.append(next_pos)            

    is_on_the_path_from_start_to_goal = [False] * n
    for i in range(n):
        is_on_the_path_from_start_to_goal[i] = is_reachable[i] and is_rev_reachable[i]

    distance = [INF] * n
    distance[start] = 0
    for _ in range(n):
        is_updated = False
        for pos, edge in enumerate(graph):
            for next_pos, cost in edge:
                if not is_on_the_path_from_start_to_goal[next_pos]:
                    continue
                if distance[pos] != INF and distance[pos] + cost < distance[next_pos]:
                    distance[next_pos] = distance[pos] + cost
                    is_updated = True
        if not is_updated:
            return distance[goal]
    
    return -INF


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

graph = [[] for i in range(n)]
for i in range(m):
    a, b, c = info[i]
    graph[a - 1].append((b - 1, -(c - p)))
ans = bellman_ford(0, n-1, graph)

if ans == -float("inf"):
    print(-1)
else:
    print(max(-ans, 0))