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.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
from heapq import heappop, heappush
import sys
input = sys.stdin.readline

N, M, P = map(int, input().split())
d = defaultdict(list)
candidate = []
l = []

for _ in range(M):
    a, b, c = map(int, input().split())
    
    if a==b:
        if P-c<0:
            candidate.append(a)
    else:
        l.append((a, b, P-c))
        d[a].append((P-c, b))

def check():
    if candidate:
        visited = [False]*(N+1)
        visited[1] = True
        q = deque([1])
        while q:
            s = q.popleft()
            for _, t in d[s]:
                if visited[t]:continue
                visited[t] = True
                q.append(t)
        
        candidate2 = [i for i in candidate if visited[i]]
        for i in candidate2:
            visited = [False]*(N+1)
            visited[i] = True
            q = deque([i])
            while q:
                s = q.popleft()
                for _, t in d[s]:
                    if visited[t]:continue
                    visited[t] = True
                    q.append(t)
            if visited[N]:
                return False
    return True

def shortest_path(s):
    INF = 10**18
    dist = [INF]*(N+1)
    dist[s] = 0

    while 1:
        update = False

        for a, b, c in l:
            if dist[a]!=INF and dist[b]>dist[a]+c:
                dist[b] = dist[a]+c
        if not update:
            break
    return dist

if check():
    d1 = shortest_path(1)
    dN = shortest_path(N)
    if d1[N]+dN[1]<0:
        print(-1)
    elif d1[N]<0:
        print(-d1[N])
    else:
        print(0)


else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import sys
input = sys.stdin.readline


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

    edges = []
    routes = [[] for _ in range(n)]
    rev_routes = [[] for _ in range(n)]


    def get_reachable_nodes(start, routes):
        seen = {start}
        todo = []
        for to in routes[start]:
            todo.append(to)
            seen.add(to)

        while todo:
            node = todo.pop()
            for to in routes[node]:
                if to in seen:
                    continue
                todo.append(to)
                seen.add(to)
        return seen


    for _ in range(m):
        node1, node2, value = map(int, input().split())
        node1, node2, value = node1 - 1, node2 - 1, value - p
        edges.append([node1, node2, value])
        routes[node1].append(node2)
        rev_routes[node2].append(node1)

    from_start = get_reachable_nodes(0, routes)
    if n-1 not in from_start:
        print(-1)
        return

    to_goal = get_reachable_nodes(n-1, rev_routes)

    from_start_to_goal = from_start & to_goal

    values = []
    rows = []
    cols = []

    for row, col, value in edges:
        if {row, col} <= from_start_to_goal:
            rows.append(row)
            cols.append(col)
            values.append(-value)

    graph = coo_matrix((values, (rows, cols)), shape=(n, n))
    try:
        bf = bellman_ford(graph, indices=[0])
        print(max(0, -int(bf[0][n - 1])))
    except NegativeCycleError:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import sys
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    edges = []
    routes = [[] for _ in range(n)]
    rev_routes = [[] for _ in range(n)]
    
    
    def get_reachable_nodes(start, routes):
        seen = {start}
        todo = []
        for to in routes[start]:
            todo.append(to)
            seen.add(to)
    
        while todo:
            node = todo.pop()
            for to in routes[node]:
                if to in seen:
                    continue
                todo.append(to)
                seen.add(to)
        return seen
    
    
    for _ in range(m):
        node1, node2, value = map(int, input().split())
        node1, node2, value = node1 - 1, node2 - 1, value - p
        edges.append([node1, node2, value])
        routes[node1].append(node2)
        rev_routes[node2].append(node1)
    
    from_start = get_reachable_nodes(0, routes)
    if n-1 not in from_start:
        print(-1)
        return
    
    to_goal = get_reachable_nodes(n-1, rev_routes)
    
    from_start_to_goal = from_start & to_goal
    
    values = []
    rows = []
    cols = []
    
    for row, col, value in edges:
        if {row, col} <= from_start_to_goal:
            rows.append(row)
            cols.append(col)
            values.append(-value)
    
    graph = csr_matrix((values, (rows, cols)), shape=(n, n))
    try:
        bf = bellman_ford(graph, indices=[0])
        print(max(0, -int(bf[0][n - 1])))
    except NegativeCycleError:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
def bellman_ford(s):
    d = [float('inf')]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        e=0
        for x, y, z in g:
            if d[y] > d[x] + z and d[x] != float('inf'):
                d[y] = d[x] + z
                e+=1
        # 負閉路が存在
        if i == n - 1 and y==n-1 and e>0 :
            return -1
    return (-1)*d[n-1]

n, m ,p= map(int,input().split()) # n:頂点数, w:辺の数
g = []
for k in range(m):
    a, b, c = map(int,input().split()) # 始点,終点,コスト
    g.append([a-1, b-1, -(c-p)])
if bellman_ford(0)==-1:
 print(-1)
else:
 print(max(bellman_ford(0),0))

Submission status: Wrong Answer

Solution code:
def bellman_ford(s):
    d = [float('inf')]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        e=0
        for x, y, z in g:
            if d[y] > d[x] + z and d[x] != float('inf'):
                d[y] = d[x] + z
                e+=1
        # 負閉路が存在
        if i == n - 1 and y==n-1 and e>0 :
            return -1
    return (-1)*d[n-1]

n, m ,p= map(int,input().split()) # n:頂点数, w:辺の数
g = []
for k in range(m):
    a, b, c = map(int,input().split()) # 始点,終点,コスト
    g.append([a-1, b-1, -(c-p)])
if bellman_ford(0)==-1:
 print(-1)
else:
 print(max(bellman_ford(0),0))

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import csr_matrix

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

fwd = [[] for _ in range(n + 1)]
rev = [[] for _ in range(n + 1)]

for a, b, c in abc:
    fwd[a].append(b)
    rev[b].append(a)


def dfs(s, adj):
    stack = [s]
    arrived = [False] * (n + 1)
    arrived[s] = True
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if not arrived[v]:
                arrived[v] = True
                stack.append(v)

    return arrived


can_go_fwd = dfs(1, fwd)
can_go_rev = dfs(n, rev)

row = []
col = []
cost = []
for a, b, c in abc:
    if can_go_fwd[a] and can_go_rev[b]:
        row.append(a)
        col.append(b)
        cost.append(p - c)

g = csr_matrix((cost, (row, col)), shape=(n + 1, n + 1))
try:
    dist = bellman_ford(g, indices=[1]).astype(int)
    ans = max(0, -dist[0][n])
    print(ans)
except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse import csr_matrix

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

fwd = [[] for _ in range(n + 1)]
rev = [[] for _ in range(n + 1)]

for a, b, c in abc:
    fwd[a].append(b)
    rev[b].append(a)


def dfs(s, adj):
    stack = [s]
    arrived = [False] * (n + 1)
    arrived[s] = True
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if not arrived[v]:
                arrived[v] = True
                stack.append(v)

    return arrived


can_go_fwd = dfs(1, fwd)
can_go_rev = dfs(n, rev)

row = []
col = []
cost = []
for a, b, c in abc:
    if can_go_fwd[a] and can_go_rev[b]:
        row.append(a)
        col.append(b)
        cost.append(p - c)

g = csr_matrix((cost, (row, col)), shape=(n + 1, n + 1))
try:
    dist = bellman_ford(g, indices=1).astype(int)
    ans = max(0, -dist[n])
    print(ans)
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
class Edge:
  def __init__(self, starting_point, arrival_point, cost):
    self.starting_point = starting_point
    self.arrival_point = arrival_point
    self.cost = cost

def solve():
  N, M, P = map(int, input().split())
  edges = []
  dist = [float('inf') for _ in range(N + 10)]
  dist[1] = 0
  ans = 0
  for i in range(M):
    a, b, c = map(int, input().split())
    e = Edge(a, b, -c + P)
    edges.append(e)
  for i in range(2 * N):
    for e in edges:
      if dist[e.arrival_point] > e.cost + dist[e.starting_point]:
        dist[e.arrival_point] = e.cost + dist[e.starting_point]
        if e.arrival_point == N and i == 2 * N - 1:
          return -1
  return max((-1) * dist[N], 0)
print(solve())

Submission status: Wrong Answer

Solution code:
def resolve():
    def BF(s, n, edge, inf=float("inf")):
        d = [inf for i in range(n)]
        d[s] = 0
        for i in range(n):
            for before, after, dist in edge:
                if before != inf:
                    d[after] = min(d[after], d[before] + dist)
            if i == n - 2:
                t = d[:]
            elif i == n - 1:
                for i, j in enumerate(d):
                    if j != t[i]:
                        d[i] = -inf
        return list(map(lambda x: -x, d))
    n, m, p = map(int, input().split())
    inf = float("inf")
    edge = [list(map(int, input().split())) for _ in range(m)]
    edge = [[x - 1, y - 1, p - z] for x, y, z in edge]
    ans = BF(0, n, edge, inf)[-1]
    print(max(0, ans) if ans < inf else -1)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e,p):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split()), p) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n-1):
	for u,v,w in edges: h[v] = min(h[v], h[u] + w)

s = h[n]
for _ in range(n-1):
	for u,v,w in edges: h[v] = min(h[v], h[u] + w)

fnc = h[n] < s
print max(0,-h[n]) if (not(fnc) and h[n] != +float('inf')) else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e,p):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split()), p) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n-1):
	for u,v,w in edges: 
		h[v] = min(h[v], h[u] + w)

s = h[n]
for u,v,w in edges:  
	h[v] = min(h[v], h[u] + w)

fnc = h[n] < s
print max(0,-h[n]) if (not(fnc) and h[n] != +float('inf')) else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e,p):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split()), p) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n):
	for u,v,w in edges: 
		h[v] = min(h[v], h[u] + w)

s = h[n]
for u,v,w in edges:  
	h[v] = min(h[v], h[u] + w)

fnc = h[n] < s
print max(0,-h[n]) if not(fnc) or h[n] == +float('inf') else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e,p):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split()), p) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n):
	for u,v,w in edges: 
		h[v] = min(h[v], h[u] + w)

s = h[v]
for u,v,w in edges:  
	h[v] = min(h[v], h[u] + w)

fnc = h[n] < s
print max(0,-h[n]) if not(fnc) or h[n] == +float('inf') else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split())) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n):
	for u,v,w in edges: h[v] = min(h[v], h[u] + w)

s = h[v]
for u,v,w in edges:  h[v] = min(h[v], h[u] + w)

fnc = h[v] < s
print max(0,-h[n]) if not(fnc) or h[n] == +float('inf') else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

n,m,p = map(int,raw_input().split(' '))

adj = collections.defaultdict(list)
def f(e):
	u,v,w = e
	return (u,v,p-w)
edges = [f(map(int, raw_input().split())) for _ in range(m) ]
h = {u: (+float('inf') if u > 1 else 0) for u in range(1, n + 1)}

for _ in range(n):
	for u,v,w in edges: h[v] = min(h[v], h[u] + w)

s = h[v]
for u,v,w in edges:  h[v] = min(h[v], h[u] + w)

fnc = h[v] < s
print -h[n] if not(fnc) or h[n] == +float('inf') else -1

Submission status: Wrong Answer

Solution code:
import collections
import heapq

s = raw_input()
h = {'R': lambda x:x-1, 'L': lambda x:x+1}
q = collections.deque([])
for i in range(len(s)-1):
	if s[i:i+2] == 'RL':
		q.append((i,i,i+1,i,'R'))
		q.append((i+1,i,i+1,i+1,'L'))
res = [0] * len(s)

while(q):
	u, a,b,w,d = q.popleft()
	res[w] += 1
	v = h[d](u)
	if 0 <= v  < len(s) and s[v] == d:
		nw = {a:b,b:a}[w] #if w == b else a
		q.append((v, a,b,nw,d))
print ' '.join(map(str,res))

Submission status: Wrong Answer

Solution code:
INF = 10**18

N, M, P = map(int, input().split())
G = []
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    G.append((a, b, c-P))
D = [0]*N
for i in range(N):
    D[i] = -INF
D[0] = 0
for i in range(N-1):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
tmpAns = D[N-1]
for _ in range(N):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
if tmpAns != D[N-1]:
    print(-1)
    exit()
if D[N-1] < 0:
    print(0)
else:
    print(D[N-1])

Submission status: Wrong Answer

Solution code:
INF = 10**18

N, M, P = map(int, input().split())
G = []
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    G.append((a, b, c-P))
D = [0]*N
for i in range(N):
    D[i] = -INF
D[0] = 0
for _ in range(N):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
tmpAns = D[N-1]
for _ in range(N):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
if tmpAns != D[N-1]:
    print(-1)
    exit()
if D[N-1] < 0:
    print(0)
else:
    print(D[N-1])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s, N):
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(N):
        for u in range(N+1):
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    dist[v] = dist[u] + g[u][v]
    for i in range(N):
        for u in range(N+1):
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if dist[v] != INF:
                        dist[v] = -INF
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    d = BellmanFord(g, 1, N)
    # print(d)
    if -d[N] >= INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s, N):
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(N):
        for u in g:
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    dist[v] = dist[u] + g[u][v]
    for i in range(N):
        for u in g:
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if dist[v] != INF:
                        dist[v] = -INF
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    d = BellmanFord(g, 1, N)
    # print(d)
    if -d[N] >= INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s, N):
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(N+N):
        for u in g:
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i > N and dist[v] != INF:
                        dist[v] = -INF
                    else:
                        dist[v] = dist[u] + g[u][v]
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    d = BellmanFord(g, 1, N)
    # print(d)
    if -d[N] >= INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: INF)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+N):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i > N and dist[v] != INF:
                        dist[v] = -INF
                    else:
                        if dist[u] == INF:
                            continue
                        dist[v] = dist[u] + g[u][v]
                        pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    d = BellmanFord(g, 1)
    if -d[N] >= INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: INF)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+N):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i > N:
                        dist[v] = -INF
                    else:
                        dist[v] = dist[u] + g[u][v]
                        pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    r = set()
    r.add(1)
    s = [1]
    while s:
        u = s.pop()
        for v in g[u]:
            if v in r:
                continue
            r.add(v)
            s.append(v)
    g2 = {}
    for k in g:
        if k in r:
            g2[k] = g[k]
    g = g2
    d = BellmanFord(g, 1)
    if -d[N] >= INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: INF)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+N):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        dist[v] = -INF
                    else:
                        dist[v] = dist[u] + g[u][v]
                        pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    r = set()
    r.add(1)
    s = [1]
    while s:
        u = s.pop()
        for v in g[u]:
            if v in r:
                continue
            r.add(v)
            s.append(v)
    g2 = {}
    for k in g:
        if k in r:
            g2[k] = g[k]
    g = g2
    d = BellmanFord(g, 1)
    if -d[N] > INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


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


def read_float():
    return float(buff_readline())


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


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


def read_str_n():
    return readline().strip().split()


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


def mt(f):
    import time

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

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

    return wrap


from collections import defaultdict

def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+1):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        dist[v] = -INF
                    else:
                        dist[v] = dist[u] + g[u][v]
                        pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)
    d = BellmanFord(g, 1)
    # print(d)
    if -d[N] == INF:
        return -1
    return max(0, -d[N])





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


if __name__ == '__main__':
    main()