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:
# -*- 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 = [0 for i in range(N)]
  for v, e in enumerate(graph):
    for t, cost in e:
      if d[v] != INF and d[v] + cost < d[t]:
        d[t] = min(d[v] + cost,0)
        update[t] = 1
  if not max(update):
    break
else:
  if update[-1]:
    print(-1)
    exit()

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

Submission status: Wrong Answer

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 = [0 for i in range(N)]
  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[t] = 1
  if not max(update):
    break
else:
  if update[-1]:
    print(-1)
    exit()

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

Submission status: Wrong Answer

Solution code:
from collections import deque

n,m,p=map(int,input().split())
INF=float('inf')
G=[]
V1=[[0 for i in range(n)]for j in range(n)]
Vn=[[0 for i in range(n)]for j in range(n)]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])
  V1[a-1][b-1]=1
  Vn[b-1][a-1]=1
  
R1=[False]*n
Rn=[False]*n

def dfs(R,V,s):
  Q=deque()
  Q.append(s)
  R[s]=True
  while Q:
    v=Q.pop()
    for i in range(n):
      if V[v][i]==1:
        if not R[i]:
          R[i]=True
          Q.append(i)
  return R
  
RR1=dfs(R1,V1,0)
RRn=dfs(Rn,Vn,n-1)
RR=[False]*n
c=0
for i in range(n):
  RR[i]=RR1[i] and RRn[i]
  if RR[i]:
    c+=1

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,c):
    for x,y,z in G:
      if not RR[x]:
        continue
      if not RR[y]:
        continue
      D[y]=min(D[y],D[x]+z)
  ans=-D[n-1]
  for x,y,z in G:
    if not RR[x]:
      continue
    if not RR[y]:
      continue
    D[y]=min(D[y],D[x]+z)
  if ans!=-D[n-1]:
    return -1
  else:
    return D

L=bellmanFord(G,0)
if L==-1:
  ans=-1
else:
  ans=max(0,-L[n-1])

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

n,m,p=map(int,input().split())
INF=float('inf')
G=[]
V1=[[0 for i in range(n)]for j in range(n)]
Vn=[[0 for i in range(n)]for j in range(n)]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])
  V1[a-1][b-1]=1
  Vn[b-1][a-1]=1
  
#TODO:1から到達できない頂点、Nに到達できない頂点を消す
R1=[False]*n
Rn=[False]*n

def dfs(R,V,s):
  Q=deque()
  Q.append(s)
  R[s]=True
  while Q:
    v=Q.pop()
    for i in range(n):
      if V[v][i]==1:
        Q.append(i)
        R[i]=True
    return R
  
RR1=dfs(R1,V1,0)
RRn=dfs(Rn,Vn,n-1)
RR=[0]*n
c=0
for i in range(n):
  if RR1[i] and RRn[i]:
    RR[i]=1
    c+=1

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,c):
    for x,y,z in G:
      if RR[x]==0 or RR[y]==0:
        continue
      D[y]=min(D[y],D[x]+z)
  ans=-D[n-1]
  for x,y,z in G:
    if RR[x]==0 or RR[y]==0:
      continue
    D[y]=min(D[y],D[x]+z)
  if ans!=-D[n-1]:
    return -1
  else:
    return -D[n-1]

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,n):
    for x,y,z in G:
      D[y]=min(D[y],D[x]+z)
  ans=-D[n-1]
  for x,y,z in G:
    D[y]=min(D[y],D[x]+z)
  if ans!=-D[n-1]:
    return -1
  else:
    return -D[n-1]

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,n):
    for x,y,z in G:
      D[y]=min(D[y],D[x]+z)
  ans=-D[n-1]
  for x,y,z in G:
    D[y]=min(D[y],D[x]+z)
  if ans!=-D[n-1]:
    return -1
  else:
    return ans

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,n+1):
    for x,y,z in G:
      if D[y]!=INF and D[y]>D[x]+z:
        if i<n:
          D[y]=D[x]+z
        else:
          D[y]=INF
    if i==n-1:
      ans=-D[n-1]
  if ans!=-D[n-1]:
    return -1
  else:
    return -D[n-1]

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(1,n+1):
    for x,y,z in G:
      if D[y]>D[x]+z:
        if i<n:
          D[y]=D[x]+z
        else:
          D[y]=-INF
    if i==n-1:
      ans=-D[n-1]
  if ans!=-D[n-1]:
    return -1
  else:
    return -D[n-1]

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])

def bellmanFord(G,s):
  D=[INF for i in range(n)]
  D[s]=0
  for i in range(n):
    for x,y,z in G:
      if D[y]>D[x]+z:
        if i<n:
          D[y]=D[x]+z
        else:
          D[y]=-INF
    if i==n-1:
      ans=-D[n-1]
  if ans!=-D[n-1]:
    return -1
  else:
    return -D[n-1]

D=bellmanFord(G,0)
if D==-1:
  ans=-1
else:
  ans=max(0,D)

print(ans)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
INF=float('inf')
G=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  G.append([a-1,b-1,-c+p])
D=[INF for i in range(n)]
D[0]=0

def main():
  for i in range(n-1):
    for x,y,z in G:
      if D[y]>D[x]+z:
        D[y]=D[x]+z
  ans=-D[n-1]
  for x,y,z in G:
    if D[y]>D[x]+z:
      D[y]=D[x]+z
  if -D[n-1]>ans:
    ans=-1 
  else:
    if ans<=0:
      ans=0
  return ans

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, Le):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for _ in range(N+10):
            for (u, v, c) in Le:
                if from1[u] and from1[v] and toN[u] and toN[v]:
                    if d[u] + c < d[v]:
                        d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in Le:
            if from1[u] and from1[v] and toN[u] and toN[v]:
                if d[u] + c < d[v]:
                    if v == N-1:
                        return None#負の閉路

                    d[v] = d[u] + c
        return d[-1]*-1
    ################################
    
    # 1からたどり着けて，かつNにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1

    
    ans=BellmanFord(N,M,edges)
    
    if ans==None:
        print(-1)
    else:
        if ans<=0:
            ans=0
        if ans>=10**10:
            ans=-1
        print(ans)
    
    


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    ans=0
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for i in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, Le):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in Le:
                if can[u] and can[v]:
                    if d[u] + c < d[v]:
                        d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in Le:
            if can[u] and can[v]:
                if d[u] + c < d[v]:
                    if v == N-1:
                        return None#負の閉路

                    d[v] = d[u] + c
        return d[N-1]*-1
    ################################
    
    # 1からたどり着けて，かつNにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1
                
    can=[0]*N
    for i in range(N):
        can[i]=from1[i] * toN[i]

    
    d=BellmanFord(N,M,edges)
    
    if d==None:
        print(-1)
    else:
        if d<=0:
            d=0
        if d>=10**10:
            d=-1
        print(d)
    
    


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    ans=0
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for i in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, Le):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in Le:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in Le:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路

                d[v] = d[u] + c
        return d[N-1]*-1
    ################################
    
    # 1からたどり着けて，かつNにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1
                
    can=[0]*N
    for i in range(N):
        can[i]=from1[i] * toN[i]
           
    #使う頂点からなる辺集合     
    newE=[]
    for (a,b,c) in edges:
        if can[a] and can[b]:
            newE.append((a,b,c))
    
    d=BellmanFord(N,M,newE)
    
    if d==None:
        print(-1)
    else:
        if d<=0:
            d=0
        if d>=10**10:
            d=-1
        print(d)
    
    
    


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    ans=0
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for i in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, Le):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in Le:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in Le:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路

                d[v] = d[u] + c
        return d[N-1]*-1
    ################################
    
    # 1からたどり着けて，かつNにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1
                
    can=[0]*N
    for i in range(N):
        can[i]=from1[i] * toN[i]
           
    #使う頂点からなる辺集合     
    newE=[]
    for (a,b,c) in edges:
        if can[a] and can[b]:
            newE.append((a,b,c))
    
    d=BellmanFord(N,M,newE)
    
    if d==None:
        print(-1)
    else:
        if d<=0:
            d=0
        print(d)
    
    
    


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    ans=0
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for i in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,P-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, edges):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路

                d[v] = d[u] + c
        return d[N-1]*-1
    ################################
    
    # 1からたどり着けて，Nにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1
                
    can=[0]*N
    for i in range(N):
        can[i]=from1[i] * toN[i]
           
    #使う頂点からなる辺集合     
    newE=[]
    for (a,b,c) in edges:
        if can[a] and can[b]:
            newE.append((a,b,c))
    
    
    d=BellmanFord(N,M,newE)
    
    if d==None:
        print(-1)
    else:
        if d<=0:
            d=0
        print(d)
    
    
    


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    最後のコイン回収をなくし，道の上のコインをCーPとする，
    コイン枚数を-1倍して，最短経路をみる，負のループがあるとダメ
    """

    
    N,M,P=MI()
    ans=0
    edges=[]
    adj=[[]for _ in range(N)]
    rev=[[]for _ in range(N)]
    
    
    for i in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        adj[a].append(b)
        rev[b].append(a)
        edges.append((a,b,P-c))
        
    ################################

    #0から他の頂点へ
    def BellmanFord(N, M, edges):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路

                d[v] = d[u] + c
        return d[N-1]*-1
    ################################
    
    # 1からたどり着けて，Nにたどり着ける部分にしか興味がない
    import queue
    q=queue.Queue()
    from1=[0]*N
    toN=[0]*N
    
    from1[0]=1
    toN[-1]=1
    
    q.put(0)
    while not q.empty():
        v=q.get()
        for nv in adj[v]:
            if from1[nv]==0:
                q.put(nv)
                from1[nv]=1
                
    q.put(N-1)
    while not q.empty():
        v=q.get()
        for nv in rev[v]:
            if toN[nv]==0:
                q.put(nv)
                toN[nv]=1
                
    can=[0]*N
    for i in range(N):
        can[i]=from1[i] & toN[i]
           
    #使う頂点からなる辺集合     
    newE=[]
    for (a,b,c) in edges:
        if can[a] and can[b]:
            newE.append((a,b,c))
    
    
    d=BellmanFord(N,M,newE)
    
    if d==None:
        print(-1)
    else:
        if d<=0:
            d=0
        print(d)
    
    
    


main()

Submission status: Wrong Answer

Solution code:
# 両方から到達出来ないものに関する辺を無視してベルマンフォード
import sys
sys.setrecursionlimit(10**6)
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: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import floyd_warshall, dijkstra, bellman_ford, NegativeCycleError
from scipy.sparse import csr_matrix

import sys
input = sys.stdin.readline

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

A,B,C = [0]*M, [0]*M, [0]*M
for i in range(M):
  a,b,c = map(int, input().split())
  a,b,c = a-1, b-1, (-1) * (c-P) # 最短炉問題にするため。
  #G[a].append((b,c))
  A[i], B[i], C[i] = a,b,c
CC = [1] * M
### https://atcoder.jp/contests/abc137/submissions/15987354
# とりあえず到達可能経路を探す、始点と終点から重み１にして辿っていき、双方登場した点が探すべき点。
# directedなので、A,Bを入れ替えているところもポイント
smat = bellman_ford(csr_matrix((CC, (A, B)), shape=(N, N)),
                    directed=True, unweighted=True, indices=0)
tmat = bellman_ford(csr_matrix((CC, (B, A)), shape=(N, N)),
                    directed=True, unweighted=True, indices=N-1)
r = set([i for i, v in enumerate(smat + tmat) if not np.isinf(v)])
A, B, C = zip(*[(a, b, c) for a, b, c in zip(A, B, C) if b in r])
try:
  csr_mat = csr_matrix((C, (A, B)), shape=(N, N))
  #csr_mat.data = P - csr_mat.data
  x = -int(bellman_ford(csr_mat, directed=True, indices=0)[N-1])
  if x < 0:
    x = 0
except NegativeCycleError:
  x = -1

print(x)