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: Runtime Error

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, P, *ABC = map(int, read().split())
    edge = [0] * M
    for i, (a, b, c) in enumerate(zip(*[iter(ABC)] * 3)):
        edge[i] = (a - 1, b - 1, -(c - P))

    dist = [INF] * N
    dist[0] = 0

    for _ in range(N - 1):
        for a, b, c in edge:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c

    updated = [False] * N
    for _ in range(N):
        for a, b, c in edge:
            if dist[b] != INF and dist[b] > dist[a] + c:
                updated[b] = True
            if updated[a]:
                updated[b] = True

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

    return


if __name__ == '__main__':import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, P, *ABC = map(int, read().split())

    G = [[] for _ in range(N)]
    G_rev = [[] for _ in range(N)]
    edge = []
    for a, b, c in zip(*[iter(ABC)] * 3):
        a -= 1
        b -= 1
        c = P - c
        G[a].append(b)
        G_rev[b].append(a)
        edge.append((a, b, c))

    reachable_1 = [False] * N
    reachable_N = [False] * N

    reachable_1[0] = True
    reachable_N[N - 1] = True

    queue = deque([0])
    while queue:
        v = queue.popleft()
        for nv in G[v]:
            if not reachable_1[nv]:
                reachable_1[nv] = True
                queue.append(nv)

    queue = deque([N - 1])
    while queue:
        v = queue.popleft()
        for nv in G_rev[v]:
            if not reachable_N[nv]:
                reachable_N[nv] = True
                queue.append(nv)

    ok = [reachable_1[i] and reachable_N[i] for i in range(N)]

    dist = [INF] * N
    dist[0] = 0

    for i in range(N):
        for a, b, c in edge:
            if not ok[a] or not ok[b]:
                continue
            if dist[b] > dist[a] + c:
                if i < N - 1:
                    dist[b] = dist[a] + c
                else:
                    print(-1)
                    return

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


if __name__ == '__main__':
    main()

    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
N,M,P = map(int, input().split())
ABC = []
Adake = [[] for _ in range(M)]
Bdake = [[] for _ in range(M)]
for _ in range(M):
    A,B,C = map(int, input().split())
    ABC.append((A-1,B-1,C-P))
    Adake[A-1].append(B-1)
    Bdake[B-1].append(A-1)
    
def dfs(x,s):
    used = {s}
    search = deque([s])
    while search:
        ss = search.pop()
        for sss in x[ss]:
            if sss in used:
                continue
            used.add(sss)
            search.append(sss)
    return used

U = dfs(Adake,0) & dfs(Bdake,N-1)
ABC = [(a,b,c) for (a,b,c) in ABC if a in U and b in U]

dist = [-float("inf")]*N
dist[0]=0
    
for i in range(N):
    ju = True
    for a,b,c in ABC:
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            ju = False
if ju:
    print(max(0,dist[-1]))
    sys.exit()
print(-1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
N,M,P = map(int, input().split())
ABC = []
Adake = [[] for _ in range(M)]
Bdake = [[] for _ in range(M)]
for _ in range(M):
    A,B,C = map(int, input().split())
    ABC.append((A-1,B-1,C-P))
    Adake[A-1].append(B-1)
    Bdake[B-1].append(A-1)
    
def dfs(x,s):
    used = {s}
    search = deque([s])
    while search:
        ss = search.pop()
        for sss in x[ss]:
            if sss in used:
                continue
            used.add(sss)
            search.append(sss)
    return used

U = dfs(Adake,0) & dfs(Bdake,N-1)
ABC = [(a,b,c) for (a,b,c) in ABC if a in U and b in U]

dist = [-float("inf")]*N
dist[0]=0
    
for i in range(N):
    for a,b,c in ABC:
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            if i == N-1 and b == N-1:
                print(-1)
                sys.exit()
if dist[-1] == -float("inf"):
    print(-1)
elif dist[-1]<0:
    print(0)
else:
    print(dist[-1])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
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

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,M,P = IL()

graph = [[] for i in range(N)]
for _ in range(M):
  a,b,c = IL()
  graph[a-1].append((b-1,-c+P))

s = 0
d = [INF] * N
d[s] = 0
update = True
for _ in range(N):
  update = False
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        d[t] = d[v] + cost
        update = True
  if not update:
    break
else:
  check = [False] * N
  for _ in range(N):
    update = False
    for v, e in enumerate(graph):
      for t, cost in e:
        if d[v] != INF and d[v] + cost < d[t]:
          check[t] = True
        if check[v]:
          check[t] = True

  for _ in range(N):
    for v, e in enumerate(graph):
      for t, cost in e:
        if d[v] != INF and d[v] + cost < d[t]:
          if t==N-1:
            print(-1)
            exit()
          d[t] = d[v] + cost
          check[t] = True
        if check[v]:
          check[t] = True
        
if check[-1]:
    print(-1)
    exit()          

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

Submission status: Runtime Error

Solution code:
# 両方から到達出来ないものに関する辺を無視してベルマンフォード
n, m, p = map(int, input().split())
edges = []
to = [[] for _ in range(n)]
ot = [[] for _ in range(n)]
reachable_from_1 = [False] * n
reachable_to_n = [False] * n
ok = [False] * n
INF = float('inf')


def dfs(v):
    if reachable_from_1[v]:
        return
    reachable_from_1[v] = True
    for nv in to[v]:
        dfs(nv)


def rdfs(v):
    if reachable_to_n[v]:
        return
    reachable_to_n[v] = True
    for nv in ot[v]:
        rdfs(nv)


for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c -= p
    c = -c
    edges.append((a, b, c))
    to[a].append(b)
    ot[b].append(a)
dfs(0)
rdfs(n - 1)
for i in range(n):
    ok[i] = reachable_from_1[i] and reachable_to_n[i]
d = [INF] * n
d[0] = 0
upd = True
step = 0
while upd:
    upd = False
    for e in edges:
        frm, to, cost = e
        if not ok[frm]:
            continue
        if not ok[to]:
            continue
        nd = d[frm] + cost
        if nd < d[to]:
            d[to] = nd
            upd = True
    step += 1
    if step > n:
        print(-1)
        exit()
ans = -d[n - 1]
ans = max(0, ans)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse import csr_matrix
from collections import deque
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    inf = 10**9
    l = np.zeros((n, n))
    tree_forth = [[] for _ in range(n)]
    tree_back = [[] for _ in range(n)]
    for i in range(m):
        a, b, c =map(int, input().split())
        tree_forth[a-1].append(b-1)
        tree_back[b-1].append(a-1)
        c = p-c
        if c == 0:
            c = 10**(-8)
        if l[a-1][b-1] == 0:
            l[a-1][b-1] = c
        else:
            l[a-1][b-1] = min(l[a-1][b-1], c)
    
    already1, already2 = [True]*n, [True]*n
    for already, tree, start in zip([already1, already2], [tree_forth, tree_back], [0, n-1]):
        not_yet = deque([start])
        already[start] = False
        while not_yet:
            key = not_yet.pop()
            for v in tree[key]:
                if already[v] == False:
                    continue
                already[v] = False
                not_yet.append(v)
    
    
    for i in range(n):
        if already1[i] or already2[i]:
            for j in range(n):
                l[i][j] = 0
                l[j][i] = 0

    print(2/0)
    
    try:
        print(max(0, int(bellman_ford(csr_matrix(l))[0][-1])*(-1)))
    except:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
from collections import deque
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    tree = [[] for _ in range(n)]
    tree_back = [[] for _ in range(n)]
    
    for i in range(m):
        a, b, c = map(int, input().split())
        tree[a-1].append((b-1, c))
        tree_back[b-1].append(a-1)
    
    not_yet = deque([n-1])
    already = [False]*n
    already[n-1] = True
    while not_yet:
        key = not_yet.pop()
        for v in tree_back[key]:
            if already[v]:
                continue
            already[v] = True
            not_yet.append(v)
    
    not_yet = deque([0])
    already2 = [False]*n
    already2[0] = True
    while not_yet:
        key = not_yet.pop()
        for (v, c) in tree[key]:
            if already2[v]:
                continue
            already2[v] = True
            not_yet.append(v)
    
    
    inf = 10**9
    adjoining_list = [[inf]*n for _ in range(n)]
    for i in range(n):
        if already[i] and already2[i]:
            for (v, c) in tree[i]:
                adjoining_list[i][v] = p-c
    
    adjoining_list = np.array(adjoining_list)
    try:
        ans = bellman_ford(csr_matrix(adjoining_list))
    except:
        print(-1)
    else:
        print(max(0, int(-ans[0][n-1])))


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

for i in range(M):
  A,B,C=map(int,input().split())
  ways[A-1].append([B-1,C-P])
  Rways[B-1].append(A-1)
  
  
visited=[-float("inf")]*N
visited[0]=0

blacklist=[True]*N
blacklist[-1]=False
"""
for c in range(M):
  for i in range(N):
    if blacklist[i]==True:
      continue
    for to in Rways[i]:
      blacklist[to]=False
"""
def b_update(nord):
  global blacklist
  for to in Rways[nord]:
    if blacklist[to]==True:
      blacklist[to]=False
      b_update(to)
      
b_update(N-1)

for c in range(M+1):
  flag=False
  for i in range(N):
    debit=visited[i]
    if debit==-float("inf"):
      continue
    for to,cost in ways[i]:
      if visited[to]<debit+cost and not blacklist[to]:
        visited[to]=debit+cost
        flag=True
        
  if not flag:
    break
  if c==M:
    print(-1)
    exit()
      
ans=visited[-1]
if ans==-float("inf"):
  print(-1)
else:
  print(max(ans,0))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

'''
lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
'''
n,m,p = input().split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(1,n+1):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))


'''
inf = 0

maxx = 0
dst = [10**9 for _ in range(n+1)]
dst[1] = 0
for i in range(n-1):
    for x,y,c in edge:
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))
'''

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

'''
lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
'''
n,m,p = input().split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(1,n+1):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))



inf = 0

maxx = 0
vst = [0 for _ in range(n+1)]
vst[1] = 1
dst = [10**9 for _ in range(n+1)]
dst[1] = 0
for i in range(n-1):
    for x,y,c in edge:
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
n,m,p = lines[0].split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(n):
    x,y,c = lines[i+1].split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))


'''
inf = 0

maxx = 0
vst = [0 for _ in range(n+1)]
vst[1] = 1
dst = [10**9 for _ in range(n+1)]
dst[1] = 0
for i in range(n-1):
    for x,y,c in edge:
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))
'''

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
n,m,p = lines[0].split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(n):
    x,y,c = lines[i+1].split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))


inf = 0

maxx = 0
vst = [0 for _ in range(n+1)]
vst[1] = 1
dst = [10**9 for _ in range(n+1)]
dst[1] = 0
'''
cnt = [0 for _ in range(n+1)]
d = deque()
d.append(1)
while(d):
    x = d.popleft()
    cnt[x]+=1
    if(cnt[x]==n):
        e[x] = []
        if(x==n):
            print("-1")
            inf = 1
    for y,c in e[x]:
        if not vst[y]:
                dst[y] = dst[x]+c
                d.append(y)
        elif dst[y]<dst[x]+c:
                dst[y] = dst[x]+c
                d.append(y)
        vst[y] = 1
'''
for i in range(n-1):
    for x,y,c in edge:
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
n,m,p = lines[0].split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(n):
    x,y,c = lines[i+1].split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,c-p))
    e[x].append((y,c-p))

inf = 0

maxx = 0
vst = [0 for _ in range(n+1)]
vst[1] = 1
dst = [0 for _ in range(n+1)]

cnt = [0 for _ in range(n+1)]
d = deque()
d.append(1)
while(d):
    x = d.popleft()
    cnt[x]+=1
    if(cnt[x]==n):
        e[x] = []
        if(x==n):
            print("-1")
            inf = 1
    for y,c in e[x]:
        if not vst[y]:
                dst[y] = dst[x]+c
                d.append(y)
        elif dst[y]<dst[x]+c:
                dst[y] = dst[x]+c
                d.append(y)
        vst[y] = 1
'''
for i in range(n-1):
    for x,y,c in edge:
        if vst[x]:
            if not vst[y]:
                dst[y] = dst[x]+c
            elif dst[y]<dst[x]+c:
                dst[y] = dst[x]+c
            vst[y] = 1
for x,y,c in edge:
        if y==n and dst[y]<dst[x]+c:
            print("-1")
            inf = 1
'''
if not inf:
    print((dst[n]>0)*dst[n])

Submission status: Runtime Error

Solution code:
import sys
from heapq import heappush,heappop

lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
n,m,p = lines[0].split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(n):
    x,y,c = lines[i+1].split()
    x = int(x)
    y = int(y)
    c = int(c)
    e[x].append((y,c))
    edge.append((x,y,c))

inf = 0

maxx = 0
vst = [0 for _ in range(n+1)]
vst[1] = 1
dst = [0 for _ in range(n+1)]
for i in range(n-1):
    for x,y,c in edge:
        if vst[x]:
            if not vst[y]:
                dst[y] = dst[x]+c-p
            elif dst[y]<dst[x]+c-p:
                dst[y] = dst[x]+c-p
            vst[y] = 1
for x,y,c in edge:
        if y==n and dst[y]<dst[x]+c-p:
            print("-1")
            inf = 1
if not inf:
    print((dst[n]>0)*dst[n])

Submission status: Runtime Error

Solution code:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

import collections

N, M, P = rl()
E = []
edges = collections.defaultdict(list)
redges = collections.defaultdict(list)
for i in range(M):
	a, b, c = rl()
	E.append((a-1, b-1, P-c))
	edges[a-1].append(b-1)
	redges[b-1].append(a-1)

visited = {}
def dfs(n):
	if n in visited: return
	visited[n] = 1
	for e in edges[n]:
		dfs(e)
rvisited = {}
def rdfs(n):
	if n in rvisited: return
	rvisited[n] = 1
	for e in redges[n]:
		rdfs(e)

dfs(0)
rdfs(N-1)
ok = [False] * N
for n in range(N):
	if n in visited and n in rvisited:
		ok[n] = True
V = list(range(N))

def belmanford(V, E, s=0):
	D = [float('inf')] * len(V)
	D[s] = 0
	P = [None] * len(V)
	update = True
	step = 0
	while update:
		update = False
		for u, v, c in E:
			if not ok[u]: continue
			if not ok[v]: continue
			if D[v] > D[u] + c:
				D[v] = D[u] + c
				P[v] = (u, c)
				update = True
		step += 1
		if step > N:
			return None, None
	return D, P

D, P = belmanford(V, E)
if D == None:
	print(-1)
else:
	print(max(-D[N-1], 0))

Submission status: Runtime Error

Solution code:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

import collections

N, M, P = rl()
E = []
edges = collections.defaultdict(list)
redges = collections.defaultdict(list)
for i in range(M):
	a, b, c = rl()
	E.append((a-1, b-1, P-c))
	edges[a-1].append(b-1)
	redges[b-1].append(a-1)

visited = {}
def dfs(n):
	if n in visited: return
	visited[n] = 1
	for e in edges[n]:
		dfs(e)
rvisited = {}
def rdfs(n):
	if n in rvisited: return
	rvisited[n] = 1
	for e in redges[n]:
		rdfs(e)

dfs(0)
rdfs(N-1)

V = list(range(N))

def belmanford(V, E, s=0):
	D = [float('inf')] * len(V)
	D[s] = 0
	P = [None] * len(V)
	update = True
	step = 0
	while update:
		update = False
		for u, v, c in E:
			if u not in V: continue
			if v not in V: continue
			if D[v] > D[u] + c:
				D[v] = D[u] + c
				P[v] = (u, c)
				update = True
		step += 1
		if step > N:
			return None, None
	return D, P

D, P = belmanford(V, E)
if D == None:
	print(-1)
else:
	print(max(-D[N-1], 0))

Submission status: Runtime Error

Solution code:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

import collections

N, M, P = rl()
E = []
edges = collections.defaultdict(list)
redges = collections.defaultdict(list)
for i in range(M):
	a, b, c = rl()
	E.append((a-1, b-1, P-c))
	edges[a-1].append(b-1)
	redges[b-1].append(a-1)

visited = {}
def dfs(n):
	if n in visited: return
	visited[n] = 1
	for e in edges[n]:
		dfs(e)
rvisited = {}
def rdfs(n):
	if n in rvisited: return
	rvisited[n] = 1
	for e in redges[n]:
		rdfs(e)

dfs(0)
rdfs(N-1)

V = list(range(N))

def belmanford(V, E, s=0):
	D = [float('inf')] * len(V)
	D[s] = 0
	P = [None] * len(V)

	for i in range(len(V)-1):
		m = i+1
		for u, v, c in E:
			if u not in V: continue
			if v not in V: continue
			if D[v] > D[u] + c:
				D[v] = D[u] + c
				P[v] = (u, c)
	n = N-1
	while n != 0:
		prev, c = P[n]
		if D[prev] + c < D[n]:
			return None, None
		n = prev
	return D, P

D, P = belmanford(V, E)
if D == None:
	print(-1)
else:
	print(max(-D[N-1], 0))

Submission status: Runtime Error

Solution code:
import sys
S=sys.stdin.readlines()
N,M,P=map(int,S[0].split())
G=[]
a,b,c=0,0,0
for i in range(M):
  a,b,c=map(int,S[i+1].split())
  G.append((a-1,b-1,P-c))
INF=10**15
D=[INF]*N
D[0]=0
e=0
for i in range(2*max(N,M)):
  for j in range(M):
    e=G[j]
    if D[e[0]]!=INF and D[e[1]]>D[e[0]]+e[2]:
      D[e[1]]=D[e[0]]+e[2]
X=D[N-1]
for i in range(2*max(N,M))
  for j in range(M):
    e=G[j]
    if D[e[0]]!=INF and D[e[1]]>D[e[0]]+e[2]:
      D[e[1]]=D[e[0]]+e[2]
if X==D[N-1]:
  print(max(0,-X))
else:
  print(-1)

Submission status: Runtime Error

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 dN[1]!=INF and d1[N]+dN[1]<0:
        print(-1)
    elif d1[N]<0:
        print(-d1[N])
    else:
        print(0)
else:
    print(-1)

Submission status: Runtime Error

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

    matrix = [[10**6] * n for _ in range(n)]

    for row, col, value in edges:
        if {row, col} <= from_start_to_goal:
            if -value < matrix[row][col]:
                matrix[row][col] = -value

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


if __name__ == "__main__":
    main()