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:
import sys
from queue import Queue
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

A = [-1]*M
B = [-1]*M
C = [-1]*M
nodes_edges = [[] for _ in range(N)]
rev_nodes_edges = [[] for _ in range(N)]
coin = [-float('inf')]*N
coin[0] = 0
availables = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    A[edge] = a-1
    B[edge] = b-1
    C[edge] = c-P
    nodes_edges[a-1].append(edge)
    rev_nodes_edges[b-1].append(edge)

def cut_graph(node):
    edges = rev_nodes_edges[node]
    availables.add(node)
    for edge in edges:
        prev = A[edge]
        if prev not in availables:
            continue
        cut_graph(prev)

cut_graph(N-1)
q = Queue()
q.put(0)
count = 0
while not q.empty():
    if count == len(availables)+1:
        print(-1)
        break
    node = q.get()
    edges = nodes_edges[node]
    for edge in edges:
        nxt = B[edge]
        if nxt not in availables:
            continue
        coin[nxt] = max(C[edge]+coin[node], coin[nxt])
        q.put(nxt)
    count += 1
else:
    ans = coin[N-1]
    ans = 0 if ans < 0 else ans
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from queue import Queue
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

A = [-1]*M
B = [-1]*M
C = [-1]*M
nodes_edges = [[] for _ in range(N)]
rev_nodes_edges = [[] for _ in range(N)]
coin = [-float('inf')]*N
coin[0] = 0
availables = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    A[edge] = a-1
    B[edge] = b-1
    C[edge] = c-P
    nodes_edges[a-1].append(edge)
    rev_nodes_edges[b-1].append(edge)

def cut_graph(node):
    edges = rev_nodes_edges[node]
    availables.add(node)
    for edge in edges:
        prev = A[edge]
        if prev not in availables:
            continue
        cut_graph(prev)

cut_graph(N-1)
q = Queue()
q.put(0)
count = 0
while not q.empty():
    if count == len(availables)+1:
        print(-1, coin)
        break
    node = q.get()
    edges = nodes_edges[node]
    for edge in edges:
        nxt = B[edge]
        if nxt not in availables:
            continue
        coin[nxt] = max(C[edge]+coin[node], coin[nxt])
        q.put(nxt)
    count += 1
else:
    ans = coin[N-1]
    ans = 0 if ans < 0 else ans
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from queue import Queue
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

A = [-1]*M
B = [-1]*M
C = [-1]*M
nodes_edges = [[] for _ in range(N)]
rev_nodes_edges = [[] for _ in range(N)]
coin = [-float('inf')]*N
coin[0] = 0
availables = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    A[edge] = a-1
    B[edge] = b-1
    C[edge] = c-P
    nodes_edges[a-1].append(edge)
    rev_nodes_edges[b-1].append(edge)

def cut_graph(node):
    edges = rev_nodes_edges[node]
    availables.add(node)
    for edge in edges:
        prev = A[edge]
        if prev not in availables:
            continue
        cut_graph(prev)

cut_graph(N-1)
q = Queue()
q.put(0)
count = 0
while not q.empty():
    if count == len(availables)+1:
        print(-1, coin)
        break
    node = q.get()
    edges = nodes_edges[node]
    for edge in edges:
        nxt = B[edge]
        if nxt not in availables:
            continue
        coin[nxt] = max(C[edge]+coin[node], coin[nxt])
        q.put(nxt)
    count += 1
else:
    ans = coin[N-1]
    ans = 0 if ans < 0 else ans
    print(coin)
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from queue import Queue
input = sys.stdin.readline

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

B = [-1]*M
C = [-1]*M
nodes_edges = [[] for _ in range(N)]
coin = [-float('inf')]*N
coin[0] = 0

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    C[edge] = c-P
    nodes_edges[a-1].append(edge)

q = Queue()
q.put(0)
count = 0
while not q.empty():
    if count == N+1:
        print(-1)
        break
    node = q.get()
    edges = nodes_edges[node]
    for edge in edges:
        nxt = B[edge]
        coin[nxt] = max(C[edge]+coin[node], coin[nxt])
        q.put(nxt)
    count += 1
else:
    ans = coin[N-1]
    ans = 0 if ans < 0 else ans
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

B = [-1]*M
nodes_edges = [[] for _ in range(N)]
C = [-1]*M
coin_memo = [None]*N
past = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    nodes_edges[a-1].append(edge)
    C[edge] = c-P

def rec(node, coin):
    edges = nodes_edges[node]
    if node in past:
        if coin_memo[node] < coin and (N-1) in past:
            print(-1)
            sys.exit()
        return
    if coin_memo[node] is not None:
        if coin_memo[node] >= coin:
            return
    coin_memo[node] = coin
    past.add(node)
    for edge in edges:
        coin += C[edge]
        rec(B[edge], coin)
        coin -= C[edge]
    past.discard(node)

rec(0, 0)

ans = coin_memo[N-1]
ans = ans if ans > 0 else 0
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

B = [-1]*M
nodes_edges = [[] for _ in range(N)]
C = [-1]*M
coin_memo = [None]*N
past = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    nodes_edges[a-1].append(edge)
    C[edge] = c-P

def rec(node, coin):
    edges = nodes_edges[node]
    if node in past:
        if coin_memo[node] < coin and (N-1) in past:
            print(-1)
            sys.exit()
        return
    coin_memo[node] = coin
    past.add(node)
    for edge in edges:
        coin += C[edge]
        rec(B[edge], coin)
        coin -= C[edge]
    past.discard(node)

rec(0, 0)

ans = coin_memo[N-1]
ans = ans if ans > 0 else 0
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

B = [-1]*M
nodes_edges = [[] for _ in range(N)]
C = [-1]*M
coin_memo = [-1]*N
past = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    nodes_edges[a-1].append(edge)
    C[edge] = c-P

def rec(node, via, coin):
    edges = nodes_edges[node]
    if via is not None:
        coin += C[via]
    if node in past:
        if coin_memo[node] < coin:
            print(-1)
            sys.exit()
        return
    coin_memo[node] = coin
    past.add(node)
    for edge in edges:
        rec(B[edge], edge, coin)
    past.discard(node)

rec(0, None, 0)

ans = coin_memo[N-1]
ans = ans if ans > 0 else 0
print(coin_memo[N-1])

Submission status: Wrong Answer

Solution code:
N, M, P = list(map(int, input().split()))
ABC = [list(map(int, input().split())) for _ in range(M)]

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c
  
cnt = M + 1
while True:
  flag = True
  Nflag = False
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if e.t == N - 1:
        Nflag = True
  if flag:
    break
  cnt -= 1
  if cnt <= 0:
    if Nflag:
      print(-1)
      exit()
    if cnt < -M:
      break

print(max(0, -D[-1]))

Submission status: Wrong Answer

Solution code:
N, M, P = list(map(int, input().split()))
ABC = [list(map(int, input().split())) for _ in range(M)]

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c
  
cnt = N + 1
while True:
  flag = True
  Nflag = False
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if e.t == N - 1:
        Nflag = True
  if flag:
    break
  cnt -= 1
  if cnt <= 0:
    if Nflag:
      print(-1)
      exit()
    if cnt < -N:
      break

print(max(0, -D[-1]))

Submission status: Wrong Answer

Solution code:
print(-1)
exit()

Submission status: Wrong Answer

Solution code:
N, M, P = list(map(int, input().split()))
ABC = [list(map(int, input().split())) for _ in range(M)]

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c

cnt = M + M + 1
while True:
  flag = True
  Nflag = False
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if e.t == N - 1:
        Nflag = True
  if flag:
    break
  cnt -= 1
  if cnt == 0:
    if Nflag:
      print(-1)
      exit()
    else:
      break

print(max(0, -D[-1]))

Submission status: Wrong Answer

Solution code:
N, M, P = list(map(int, input().split()))
ABC = [list(map(int, input().split())) for _ in range(M)]

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c

cnt = M + 1
while True:
  flag = True
  Nflag = False
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if e.t == N - 1:
        Nflag = True
  if flag:
    break
  cnt -= 1
  if cnt == 0:
    if Nflag:
      print(-1)
      exit()
    else:
      break

print(max(0, -D[-1]))

Submission status: Wrong Answer

Solution code:
N, M, P = 2500, 5000, 5
ABC = [[i, i+1, 10] for i in range(1, 2500)] + [[N, 1, 10]] + [[i, i, 10] for i in range(1, 2501)]

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c

cnt = M + 1
while True:
  flag = True
  Nflag = False
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if e.t == N - 1:
        Nflag = True
  if flag:
    break
  cnt -= 1
  if cnt == 0:
    if Nflag:
      print(-1)
      exit()
    else:
      break

print(max(0, -D[-1]))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

B = [-1]*M
nodes_edges = [[] for _ in range(N)]
C = [-1]*M
coin_memo = [-1]*N
past = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    nodes_edges[a-1].append(edge)
    C[edge] = c-P

def rec(node, via, coin):
    edges = nodes_edges[node]
    if via is not None:
        coin += C[via]
    if node in past:
        if coin_memo[node] < coin:
            print(-1)
            sys.exit()
    if coin_memo[node] >= coin:
        return 
    coin_memo[node] = coin
    past.add(node)
    for edge in edges:
        rec(B[edge], edge, coin)
    past.discard(node)

rec(0, None, 0)

ans = coin_memo[N-1]
ans = ans if ans > 0 else 0
print(coin_memo[N-1])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

B = [-1]*M
nodes_edges = [[] for _ in range(N)]
C = [-1]*M
coin_memo = [0]*N

for edge in range(M):
    a, b, c = map(int, input().split())
    B[edge] = b-1
    nodes_edges[a-1].append(edge)
    C[edge] = c-P

def rec(node, via, past, coin):
    edges = nodes_edges[node]
    if via is not None:
        coin += C[via]
    if node in past:
        if coin_memo[node] < coin:
            print(-1)
            sys.exit()
        else:
            return
    if coin_memo[node] > coin:
        return 
    coin_memo[node] = coin
    past.add(node)
    for edge in edges:
        rec(B[edge], edge, past, coin)
    past.discard(node)

rec(0, None, set(), 0)

ans = coin_memo[N-1]
ans = ans if ans > 0 else 0
print(coin_memo[N-1])

Submission status: Wrong Answer

Solution code:
import collections
from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import bellman_ford

N, M, P = [int(_) for _ in input().split()]
#for multiple edges
ABC = sorted([[int(_) for _ in input().split()] for _ in range(M)], key=lambda xs:xs[2])
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
G = lil_matrix((N + 1, N + 1))
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G[a, b] = P - c
try:
    dist_matrix = bellman_ford(G, directed=True, indices=[1])
    print(max(-int(dist_matrix[0][-1]), 0))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
import collections
from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import bellman_ford

N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
G = lil_matrix((N + 1, N + 1))
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G[a, b] = P - c
try:
    dist_matrix = bellman_ford(G, directed=True, indices=[1])
    print(max(-int(dist_matrix[0][-1]), 0))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
# from collections import deque
# import numpy as np
import sys
sys.setrecursionlimit(10**4)

def _li(): return list(map(int, stdin.readline().split()))
def _li_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def _lf(): return list(map(float, stdin.readline().split()))
def _ls(): return stdin.readline().split()
def _i(): return int(stdin.readline())
def _f(): return float(stdin.readline())
def _s(): return stdin.readline()[:-1]


N, M, P = _li()

edge_cost = []
edge_from = [[] for _ in range(N)]
edge_to = [[] for _ in range(N)]

for _ in range(M):
    a, b, c = _li()
    a -= 1
    b -= 1
    edge_cost.append((a, b, -(c-P)))
    edge_to[a].append(b)
    edge_from[b].append(a)


ok_from_start = [False] * N
ok_from_end = [False] * N


def reachable_start(node):
    if not ok_from_start[node]:
        ok_from_start[node] = True
        for n in edge_to[node]:
            reachable_start(n)


def reachable_end(node):
    if not ok_from_end[node]:
        ok_from_end[node] = True
        for n in edge_from[node]:
            reachable_end(n)


reachable_start(0)
reachable_end(N-1)

ok = [a and b for a, b in zip(ok_from_start, ok_from_end)]

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

# Bellman-Ford
contain_negative_loop = False
for i in range(N):
    update_flag = False
    for ec in edge_cost:
        if ok[ec[0]] and ok[ec[1]]:
            if shortest_path[ec[1]] > shortest_path[ec[0]] + ec[2]:
                shortest_path[ec[1]] = shortest_path[ec[0]] + ec[2]
                update_flag = True
    if not update_flag:
        break
if i == N - 1:
    contain_negative_loop = True

if contain_negative_loop:
    print(-1)
else:
    print(max(0, -shortest_path[-1]))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
# from collections import deque
# import numpy as np
import sys
sys.setrecursionlimit(10**4)

def _li(): return list(map(int, stdin.readline().split()))
def _li_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def _lf(): return list(map(float, stdin.readline().split()))
def _ls(): return stdin.readline().split()
def _i(): return int(stdin.readline())
def _f(): return float(stdin.readline())
def _s(): return stdin.readline()[:-1]


N, M, P = _li()

edge_cost = []
edge_from = [[] for _ in range(N)]
edge_to = [[] for _ in range(N)]

for _ in range(M):
    a, b, c = _li()
    a -= 1
    b -= 1
    edge_cost.append((a, b, -(c-P)))
    edge_to[a].append(b)
    edge_from[b].append(a)


ok_from_start = [False] * N
ok_from_end = [False] * N


def reachable_start(node):
    if not ok_from_start[node]:
        ok_from_start[node] = True
        for n in edge_to[node]:
            reachable_start(n)


def reachable_end(node):
    if not ok_from_end[node]:
        ok_from_end[node] = True
        for n in edge_from[node]:
            reachable_end(n)


reachable_start(0)
reachable_end(N-1)


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

# Bellman-Ford
contain_negative_loop = False
for i in range(N):
    update_flag = False
    for ec in edge_cost:
        if ok_from_start[ec[1]] and ok_from_end[ec[1]]:
            if shortest_path[ec[1]] > shortest_path[ec[0]] + ec[2]:
                shortest_path[ec[1]] = shortest_path[ec[0]] + ec[2]
                update_flag = True
    if not update_flag:
        break
if i == N - 1:
    contain_negative_loop = True

if contain_negative_loop:
    print(-1)
else:
    print(max(0, -shortest_path[-1]))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    # def dfs(node):
    #     if reachable_from_start[node]:
    #         return
    #     reachable_from_start[node] = True
    #     for next_node in graph[node]:
    #         dfs(next_node)

    reachable_to_end = [False] * n

    # def rdfs(node):
    #     if reachable_to_end[node]:
    #         return
    #     reachable_to_end[node] = True
    #     for next_node in rev_graph[node]:
    #         rdfs(next_node)
    #
    # dfs(0)
    # rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

    print(max(0, -scores[-1]))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections
from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import bellman_ford

N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
G = lil_matrix((N + 1, N + 1))
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G[a, b] = P - c


def bellman_ford2(V, G, i):
    INF = float('inf')
    D = [INF] * V
    D[i] = 0
    for _ in range(V):
        update = False
        for s, t, d in G:
            if D[s] != INF and D[t] > D[s] + d:
                D[t] = D[s] + d
                update = True
        if not update:
            return D
        if _ == V:
            return False


try:
    dist_matrix = bellman_ford(G, directed=True)
    print(max(-int(dist_matrix[1, N]), 0))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
import collections
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
G = cd(lambda: cd(int))
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G[a][b] = P - c


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [INF] * V
    D[i] = 0
    for _ in range(V):
        update = False
        for s in G:
            for t in G[s]:
                if D[s] != INF and D[t] > D[s] + G[s][t]:
                    D[t] = D[s] + G[s][t]
                    update = True
        if not update:
            return D
        if _ == V:
            return False


a = bellman_ford(N + 1, G, 1)
try:
    print(max(-a[-1], 0))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
import collections
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
G = cd(lambda: cd(int))
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
    G[a][b] = P - c
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [INF] * V
    D[i] = 0
    for _ in range(V):
        update = False
        for s in G:
            for t in G[s]:
                if D[s] != INF and D[t] > D[s] + G[s][t] and ok[t] == 2:
                    D[t] = D[s] + G[s][t]
                    update = True
        if not update:
            return D
        if _ == V:
            return False


a = bellman_ford(N + 1, G, 1)
if a is None:
    print(-1)
else:
    print(-a[-1])

Submission status: Wrong Answer

Solution code:
import collections
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
G = cd(lambda: cd(int))
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
    G[a][b] = P - c
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [INF] * V
    D[i] = 0
    for _ in range(V):
        update = False
        for s in G:
            for t in G[s]:
                if D[s] != INF and D[t] > D[s] + G[s][t] and ok[t] == 2:
                    D[t] = D[s] + G[s][t]
                    update = True
        if not update:
            return D
        if _ == V:
            return False


try:
    print(max([-bellman_ford(N + 1, G, 1)[-1], 0]))
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
from collections import deque
import numpy as np
# import sys
# sys.setrecursionlimit(10**4)

def _li(): return list(map(int, stdin.readline().split()))
def _li_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def _lf(): return list(map(float, stdin.readline().split()))
def _ls(): return stdin.readline().split()
def _i(): return int(stdin.readline())
def _f(): return float(stdin.readline())
def _s(): return stdin.readline()[:-1]


N, M, P = _li()

come_in = [[] for _ in range(N)]  # [[], [[1, 20]], [[1, 45], [2, 30]]]

for _ in range(M):
    a, b, c = _li_()
    c += 1
    come_in[b].append([a, c])

search_list = deque([])  # [[visited], gain]
for search in come_in[-1]:  # add search_list
    search.extend([[N-1], []])
    search_list.append(search)

ans = 0
has_loop = np.zeros(N, dtype=int)
ans_cand = []
while len(search_list) > 0:
    target = search_list.pop()  # [from, coin, visited, gain]
    target[3].append(target[1])  # update gain list

    if target[0] in target[2]:
        # already searched, loop appear
        idx = target[2].index(target[0])
        loop = len(target[2]) - idx
        if sum(target[3][idx:]) > loop * P:
            has_loop[target[0]] = 1

    else:
        # not searched
        target[2].append(target[0])  # update visited list
        for search in come_in[target[0]]:  # add search_list
            search.extend([target[2].copy(), target[3].copy()])
            search_list.append(search)
        if target[0] == 0:
            if has_loop[target[2]].sum() > 0:
                ans = -1
                break
            else:
                ans_cand.append(target[3])

if ans == -1:
    print(ans)
else:
    for c in ans_cand:
        ans = max(ans, sum(c) - len(c) * P)
    print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
from collections import deque
import numpy as np
# import sys
# sys.setrecursionlimit(10**4)

def _li(): return list(map(int, stdin.readline().split()))
def _li_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def _lf(): return list(map(float, stdin.readline().split()))
def _ls(): return stdin.readline().split()
def _i(): return int(stdin.readline())
def _f(): return float(stdin.readline())
def _s(): return stdin.readline()[:-1]


N, M, P = _li()

come_in = [[] for _ in range(N)]  # [[], [[1, 20]], [[1, 45], [2, 30]]]

for _ in range(M):
    a, b, c = _li_()
    c += 1
    come_in[b].append([a, c])

search_list = deque([])  # [[visited], gain]
for search in come_in[-1]:  # add search_list
    search.extend([[N-1], []])
    search_list.append(search)

ans = 0
has_loop = np.zeros(N, dtype=int)
while len(search_list) > 0:
    target = search_list.pop()  # [from, coin, visited, gain]
    target[3].append(target[1])  # update gain list

    if target[0] in target[2]:
        # already searched, loop appear
        idx = target[2].index(target[0])
        loop = len(target[2]) - idx
        if sum(target[3][idx:]) > loop * P:
            has_loop[target[0]] = 1

    else:
        # not searched
        target[2].append(target[0])  # update visited list
        for search in come_in[target[0]]:  # add search_list
            search.extend([target[2].copy(), target[3].copy()])
            search_list.append(search)
        if target[0] == 0:
            if has_loop[target[2]].sum() > 0:
                ans = -1
                break
            else:
                ans = max(ans, sum(target[3]) - len(target[3]) * P)

print(ans)