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:
INF = 10 ** 15
MOD = 10 ** 9 + 7

def beruman(n,edges,start = 0,negative_loop = False):
    ans = False #startを含む負の閉路が存在するか
    dist = [INF] * n
    dist[start] = 0

    for i in range(n):
        update = False
        for a,b,c in edges:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c
                update = True

        if not update:
            break
    
    if n != 1 and i == n - 1:
        ans = True
    
    if negative_loop:
        return dist,ans
    else:
        return dist

def dfs(G,can_reach,start):
    stack = [start]
    can_reach[start] = True
    while stack:
        v = stack.pop()
        for e in G[v]:
            if can_reach[e]:
                continue
            stack.append(e)
            can_reach[e] = True
    return can_reach

def main():
    N,M,P = map(int,input().split())
    edges = []
    G = [[] for _ in range(N)]
    G_inv = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = map(int,input().split())
        a -= 1
        b -= 1
        edges.append((a,b,P - c))
        G[a].append(b)
        G_inv[b].append(a)
    
    can_reach_from_start = [False] * N
    can_reach_from_goal = [False] * N
    dfs(G,can_reach_from_start,0)
    dfs(G_inv,can_reach_from_goal,N - 1)
    edge = []
    for a,b,c in edges:
        if (can_reach_from_goal[a] and can_reach_from_start[a]
            and can_reach_from_start[b] and can_reach_from_start[b]):
            edge.append((a,b,c))
    
    dist,flag = beruman(N,edge,0,True)
    if flag:
        print(-1)
    else:
        print(max(-dist[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
graph=[[] for i in range(N+1)]
for _ in range(M):
    a,b,weight=map(int,input().split())
    graph[a].append((b,P-weight))
    
class Node():
    def __init__(self,name):
        self.name=name
        self.par=None
        self.d=float("inf")
        
    def relax(self,other,weight):
        if self.d>other.d+weight:
            self.d=other.d+weight
            self.par=other.name
    def relax_(self,other,weight):
         if self.d>other.d+weight:
            self.d=other.d+weight
            return True
         return False
def bellman_ford(graph,s_node):
    N=len(graph)-1
    d_list=[Node(i) for i in range(N+1)]
    #初期化
    d_list[s_node].d=0
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)
    negative=[False for i in range(N+1)]
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                if d_list[point].relax_(d_list[node],distance):
                    if negative[point]==False:
                        negative[point]=True
                    else:
                        for que in graph[point]:
                            negative[que[0]]=True
    if negative[N]:
        return False

    return d_list[N].d

K=bellman_ford(graph,1)
if K!=False:
    print(max(-K,0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

    n,m,p = map(int, input().split())
    edge = [[] for _ in range(m)]
    for i in range(m):
        a,b,c = map(int, input().split())
        edge[i] = [a-1,b-1,c-p]
    
    def bellmanford(n, s, edge):
        inf = 10**17
        d = [-inf] * n
        d[s] = 0
        for i in range(n*2):
            for a,b,c in edge:
                if d[a] != -inf and d[b] < d[a]+c:
                    d[b] = d[a] + c
                    if i >= n-1 and b == n-1:
                        return -inf
        return d[-1]

    res = bellmanford(n,0,edge)
    if res == -inf:
        print(-1)
    elif res < 0:
        print(0)
    else:
        print(res)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

    n,m,p = map(int, input().split())
    edge = [[] for _ in range(m)]
    for i in range(m):
        a,b,c = map(int, input().split())
        edge[i] = [a-1,b-1,c-p]
    
    def bellmanford(n, s, edge):
        inf = 10**17
        d = [-inf] * n
        d[s] = 0
        for i in range(n):
            for a,b,c in edge:
                if d[a] != -inf and d[b] < d[a]+c:
                    d[b] = d[a] + c
                    if i == n-1 and b == n-1:
                        return -inf
        return d[-1]

    res = bellmanford(n,0,edge)
    if res == -inf:
        print(-1)
    elif res < 0:
        print(0)
    else:
        print(res)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
graph=[[] for i in range(N+1)]
for _ in range(M):
    a,b,weight=map(int,input().split())
    graph[a].append((b,P-weight))
    
class Node():
    def __init__(self,name):
        self.name=name
        self.par=None
        self.d=float("inf")
        
    def relax(self,other,weight):
        if self.d>other.d+weight:
            self.d=other.d+weight
            self.par=other.name

def bellman_ford(graph,s_node):
    N=len(graph)-1
    d_list=[Node(i) for i in range(N+1)]
    #初期化
    d_list[s_node].d=0
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)         
    now_L=d_list[N].d
    for _ in range(N-1):
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance) 
        if d_list[N].d<now_L:
                    return False
    return -d_list[N].d

K=bellman_ford(graph,1)
if K!=False:
    print(max(0,K))  
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
graph=[[] for i in range(N+1)]
for _ in range(M):
    a,b,weight=map(int,input().split())
    graph[a].append((b,P-weight))
    
class Node():
    def __init__(self,name):
        self.name=name
        self.par=None
        self.d=float("inf")
        
    def relax(self,other,weight):
        if self.d>other.d+weight:
            self.d=other.d+weight
            self.par=other.name

def bellman_ford(graph,s_node):
    N=len(graph)-1
    d_list=[Node(i) for i in range(N+1)]
    #初期化
    d_list[s_node].d=0
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)         
    
    for _ in range(N-1):
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)   
        for tuple_ in graph[N]:
                point,distance=tuple_     
                if d_list[N].d<d_list[point].d+distance:
                    return False
    return -d_list[N].d

K=bellman_ford(graph,1)
if K!=False:
    print(max(0,K))  
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
graph=[[] for i in range(N+1)]
for _ in range(M):
    a,b,weight=map(int,input().split())
    graph[a].append((b,P-weight))
    
class Node():
    def __init__(self,name):
        self.name=name
        self.par=None
        self.d=float("inf")
        
    def relax(self,other,weight):
        if self.d>other.d+weight:
            self.d=other.d+weight
            self.par=other.name

def bellman_ford(graph,s_node):
    N=len(graph)-1
    d_list=[Node(i) for i in range(N+1)]
    #初期化
    d_list[s_node].d=0
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)         
    
    for _ in range(N-1):
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)   
        for tuple_ in graph[N]:
                point,distance=tuple_     
                if d_list[N].d<d_list[point].d+weight:
                    return False
    return -d_list[N].d

K=bellman_ford(graph,1)
if K!=False:
    print(max(0,K))  
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
graph=[[] for i in range(N+1)]
for _ in range(M):
    a,b,weight=map(int,input().split())
    graph[a].append((b,P-weight))
    
class Node():
    def __init__(self,name):
        self.name=name
        self.par=None
        self.d=float("inf")
        
    def relax(self,other,weight):
        if self.d>other.d+weight:
            self.d=other.d+weight
            self.par=other.name
            
def bellman_ford(graph,s_node):
    N=len(graph)-1
    d_list=[Node(i) for i in range(N+1)]
    #初期化
    d_list[s_node].d=0
    for _ in range(N-1):
        #N回同じループを繰り返す
        for node in range(1,N+1):
            for tuple_ in graph[node]:
                point,distance=tuple_
                d_list[point].relax(d_list[node],distance)           
    for  node in range(1,N+1):
        for tuple_ in graph[node]:
            point,distance=tuple_
            if d_list[point].d>d_list[node].d+distance:
                return False
    return d_list  

K=bellman_ford(graph,1)
if K!=False:
    print(max(0,-K[N].d))  
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int,input().split())
edge =[[] for _ in range(n+1)]
for i in range(m):
    a,b,c = map(int,input().split())
    edge[a].append((b,-c+p))
 
from heapq import *
INF = float("inf")
d = [INF] *(n+1)
d[1] = 0
h=[]
renew = set()
heappush(h,(d[1],1))
count = 0
while len(h)>0:
    dist,u = heappop(h)
    for (v,cost) in  edge[u]:
        if dist + cost >= d[v]:
            continue
        d[v] = dist + cost
        heappush(h,(d[v],v))
        if (u,v) in renew:
            d[v] = -INF
            renew.append((u,v))
if d[n] == -INF :
  d[n] = 1 
print(-d[n])

Submission status: Wrong Answer

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

from heapq import *
INF = float("inf")
d = [INF] *(n+1)
d[1] = 0
h=[]
renew = set()
heappush(h,(d[1],1))
count = 0
while len(h)>0:
    dist,u = heappop(h)
    for (v,cost) in  edge[u]:
        if dist + cost >= d[v]:
            continue
        d[v] = dist + cost
        heappush(h,(d[v],v))
        if (u,v) in renew:
            d[v] = -INF
            renew.append((u,v))
print(-d[n])

Submission status: Wrong Answer

Solution code:
import sys

INF = 10 ** 9
N, M, P = map(int,input().split())

edges = []

for _ in range(M):
    A, B, C = map(int,input().split())
    edges.append([A-1, B-1, P-C])

flag = [0] * N
flag[N-1] = 1

for i in range(N-1):
    for j in range(M):
        edge = edges[j]
        if flag[edge[1]]:
            flag[edge[0]] = 1

d = [INF] * N
d[0] = 0
k = None

for i in range(N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N - 1 and flag[edge[1]]:
                print(-1)
                sys.exit()

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

Submission status: Wrong Answer

Solution code:
import sys

INF = 10 ** 9
N, M, P = map(int,input().split())

edges = []

for _ in range(M):
    A, B, C = map(int,input().split())
    edges.append([A-1, B-1, P-C])

d = [INF] * N
d[0] = 0
k = None

for i in range(2 * N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N - 1:
                k = d[N-1]
            if i == 2 * N - 1:
                if k > d[N-1]:
                    print(-1)
                    sys.exit()

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

Submission status: Wrong Answer

Solution code:
import sys

INF = 10 ** 9
N, M, P = map(int,input().split())

edges = []

for _ in range(M):
    A, B, C = map(int,input().split())
    edges.append([A-1, B-1, P-C])

d = [INF] * N
d[0] = 0

for i in range(N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N-1 and edge[1] == N-1:
                print(-1)
                sys.exit()

# print(max(-1 * d[N-1], 0))
print(-1)

Submission status: Wrong Answer

Solution code:
import sys

INF = float('inf')
N, M, P = map(int,input().split())

edges = []

for _ in range(M):
    A, B, C = map(int,input().split())
    edges.append([A-1, B-1, P-C])

d = [INF] * N
d[0] = 0

for i in range(N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N-1 and edge[1] == N-1:
                print(-1)
                sys.exit()

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

Submission status: Wrong Answer

Solution code:
import sys

INF = 10 ** 9
N, M, P = map(int,input().split())

edges = []

for _ in range(M):
    A, B, C = map(int,input().split())
    edges.append([A-1, B-1, P-C])

d = [INF] * N
d[0] = 0

for i in range(N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N-1 and edge[1] == N-1:
                print(-1)
                sys.exit()

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

Submission status: Wrong Answer

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,m,p = mi()
A = [[] for _ in range(n)]
B = [[] for _ in range(n)]

for _ in range(m):
    a,b,c = mi()
    a -= 1
    b -= 1
    c -= p
    A[a].append((b,c))
    B[b].append(a)

# Is num able to reach n
flag = [0]*n
ima = [(n-1,n-1)]
while ima:
    now ,prev = ima.pop()
    flag[now] = 1
    for i in B[now]:
        if flag[i] == 0:
            ima.append((i,now))
#print(flag)

ima = [(0,0)]
count = 0
inf = -10**9
dp = [inf]*n
dp[0] = 0
mm = 2*m
while ima:
    now,score = ima.pop()

    for b,c in A[now]:
        #print(b,c)
        if not flag[b]:
            continue
        ten = score + c
        if dp[b] < ten:
            dp[b] = ten
            ima.append((b,ten))
            count += 1
            if count == mm:
                print(-1)
                exit()
print(max(0,dp[-1]))

Submission status: Wrong Answer

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,m,p = mi()
A = [[] for _ in range(n)]
B = [[] for _ in range(n)]

for _ in range(m):
    a,b,c = mi()
    a -= 1
    b -= 1
    c -= p
    A[a].append((b,c))
    B[b].append(a)

# Is num able to reach n
flag = [0]*n
ima = [(n-1,n-1)]
while ima:
    now ,prev = ima.pop()
    flag[now] = 1
    for i in B[now]:
        if i != prev:
            ima.append((i,now))
#print(flag)

ima = [(0,0,0)]
count = 0
dp = [-1]*n
dp[0] = 0
mm = 2*m
while ima:
    now,prev,score = ima.pop()

    for b,c in A[now]:
        #print(b,c)
        if not flag[b]:
            continue
        ten = max(0,score + c)
        if dp[b] < ten:
            dp[b] = ten
            ima.append((b,now,ten))
            count += 1
            if count == mm:
                print(-1)
                exit()
print(dp[-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
N,M,P=map(int,input().split())

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

graph=[[] for _ in range(N+1)]
elist=[]
for _ in range(M):
  A,B,C=map(int,input().split())
  elist.append((A,B,P-C))
  graph[A].append(B)
#print(elist)

visited=[None]*(N+1)
def check_reachable(u):
  if u==N:
    #print(ls+[u])
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    ret=None
    if reachable[v]!=None:
      ret=reachable[v]
    elif not visited[v]:
      ret=check_reachable(v)
    if ret:        
      cnt+=1
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    reachable[u]=False
    return False
  
reachable=[None]*(N+1)
for i in range(1,N+1):
#for i in range(23,24):
  if reachable[i]==None:
    visited=[False]*(N+1)
    check_reachable(i)
#print(reachable)
#print(reachable[23])
#sys.exit(0)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
N,M,P=map(int,input().split())

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

graph=[[] for _ in range(N+1)]
elist=[]
for _ in range(M):
  A,B,C=map(int,input().split())
  elist.append((A,B,P-C))
  graph[A].append(B)
#print(elist)

visited=[None]*(N+1)
def check_reachable(u):
  if u==N:
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    if not visited[v]:
      ret=check_reachable(v)
      if ret:        
        reachable[v]=True
        cnt+=1
      else:
        reachable[v]=False
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    reachable[u]=False
    return False
  
reachable=[None]*(N+1)
for i in range(1,N+1):
  if reachable[i]==None:
    visited=[False]*(N+1)
    check_reachable(i)
#print(reachable)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
N,M,P=map(int,input().split())

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

graph=[[] for _ in range(N+1)]
elist=[]
for _ in range(M):
  A,B,C=map(int,input().split())
  elist.append((A,B,P-C))
  graph[A].append(B)
#print(elist)

visited=[None]*(N+1)
def check_reachable(u):
  if u==N:
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    if not visited[v]:
      ret=check_reachable(v)
      if ret:        
        cnt+=1
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    reachable[u]=False #入れるとエラー
    return False
  
reachable=[False]*(N+1)
for i in range(1,N+1):
  if not reachable[i]:
    visited=[False]*(N+1)
    check_reachable(i)
#print(reachable)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Wrong Answer

Solution code:
import sys


sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def bellman_ford(edges, n_nodes, start, goal):
    dist = [float("inf") for _ in range(n_nodes)]
    dist[start] = 0
    negative = [False for _ in range(n_nodes)]

    for i in range(n_nodes):
        for fro, to, cost in edges:
            if dist[to] > dist[fro] + cost:
                dist[to] = dist[fro] + cost
                if i == n_nodes - 1:
                    negative[to] = True

    if negative[goal]:
        return float("inf")
    else:
        return -dist[goal]


def main():
    N, M, P = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a - 1, b - 1, -c + P))

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import heapq
import sys
sys.setrecursionlimit(10**9)

# 全頂点からのゴールへの到達可能性を確認
# 頂点1からDFSしてNまできたら、それまでのパス全てについて到達可能に更新
# その後、到達可能な部分のみを新たな辺にして、ベルマンフォード
# 辺の重みは（C - P）
# 負閉路を検出したなら-1
# そうでなければNまでの距離


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

Edge = [[] for _ in range(N)]
for a,b,c in ABC:
    Edge[b-1].append(a-1)


reachable = [False]*N
reachable[0] = True
reachable[N-1] = True

def dfs(v):
    for nv in Edge[v]:
        if reachable[nv]:
            continue
        else:
            reachable[nv] = True
            dfs(nv)
    return 

def BellmanFord(s, N, Edge):
    INF = 10**20
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        isUpdated = False
        for t in range(N):
            if dist[t] == INF:
                continue
            for v,c in Edge[t]:
                if dist[t]+c < dist[v]:
                    dist[v] = dist[t]+c
                    isUpdated = True
        if not isUpdated:
            break
        elif i==N-1:
            return -1
    return dist

                
dfs(N-1)
newEdge = [[] for _ in range(N)]
for a,b,c in ABC:
    if reachable[a-1]:
        newEdge[a-1].append([b-1, P-c])

dist = BellmanFord(0, N, newEdge)
if dist==-1:
    print(-1)
else:
    print(max(0, -dist[N-1]))

Submission status: Wrong Answer

Solution code:
INF=10**30
def Belman_Ford(s,N,Edge):
    dist=[INF]*N
    neg=[0]*N
    dist[s]=0
    for i in range(N-1):
        for f,t,c in Edge:
            if dist[t]>dist[f]+c and dist[f]!=INF:
                dist[t]=min(dist[t],dist[f]+c)
    for i in range(N):
        for f,t,c in Edge:
            if dist[t]>dist[f]+c and dist[f]!=INF:
                dist[t]=dist[f]+c
                neg[t]=True
    return dist,neg
                
N,M,P=map(int,input().split())
Edge=[]
for i in range(M):
    a,b,c=map(int,input().split())
    Edge.append((a-1,b-1,-(c-P)))
dist,neg=Belman_Ford(0,N,Edge)

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

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, M, P = (int(i) for i in input().split())
    adj_list = [[] for _ in range(N)]
    radj_list = [[] for _ in range(N)]
    ok = [False]*N
    edge = []
    for i in range(M):
        a, b, c = (int(i) for i in input().split())
        c -= P
        if a == b:
            continue
        adj_list[a-1].append(b-1)
        radj_list[b-1].append(a-1)
        edge.append((a-1, b-1, -c))

    def dfs(G, v):
        seen = [False]*N
        todo = [v]
        seen[v] = True
        while todo:
            u = todo.pop()
            for next_v in G[u]:
                if seen[next_v]:
                    continue
                seen[next_v] = True
                todo.append(next_v)
        return seen

    i = 0
    for s, rs in zip(dfs(adj_list, 0), dfs(radj_list, N-1)):
        ok[i] = s and rs
        i += 1
    print(ok)
    # Bellman_ford
    d = [10**12]*N
    d[0] = 0
    update = True
    step = 0
    while update:
        update = False
        for a, b, c in edge:
            if not(ok[a]) or not(ok[b]):
                continue
            newD = d[a] + c
            if newD < d[b]:
                update = True
                d[b] = newD
        step += 1
        if step > N:
            return print(-1)
    print(max(0, d[N-1]*-1))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

INF = 10 ** 9
#入力

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

check = [False] * N
d = [INF] * N #距離を記録

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    i = 0
    while i < N - 1:
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
        i += 1
    
    j = 0
    while j < N:
        for i in range(M):
            e = G[i]
            if d[e[0]] == INF:
                continue
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                check[e[1]] = True
            if check[e[0]]:
                check[e[1]] = True
        j += 1

shortest_path(1)
if check[N - 1]:
    print (-1)
else:
    ans = d[N - 1]
    print (max(0, -ans))
# print (d)

Submission status: Wrong Answer

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

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

INF = 10 ** 9
#入力

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

check = [False] * N
d = [INF] * N #距離を記録

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    i = 0
    while i < N - 1:
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
        i += 1
    
    j = 0
    while j < N:
        for i in range(M):
            if d[e[0]] == INF:
                continue
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                check[e[1]] = True
            if check[e[0]]:
                check[e[1]] = True
        j += 1

shortest_path(1)
if check[N - 1]:
    print (-1)
else:
    ans = d[N - 1]
    print (max(0, -ans))
# print (d)