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:
n,m,p = map(int, input().split())
link = [[] for _ in range(n)]
for i in range(m):
    a,b,cost = list(map(int,input().split()))
    link[a-1].append([b-1,cost-p])

from collections import deque
Q = deque()
Q.append([0,0])
cnt=0
costs=[-(10**15)]*n
while Q:
    if cnt>2*n:
        break
    now,now_cost = Q.popleft()
    for nxt,new_cost in link[now]:
        if costs[nxt] >= now_cost+new_cost or costs[nxt]==10**15:
            continue
        if cnt>n+1:
            costs[nxt]=10**15
        else:
            costs[nxt]=now_cost+new_cost
        Q.append([nxt,costs[nxt]])
        cnt+=1

if costs[-1]==10**15:
    print(-1)
else:
    print(max(0,costs[-1]))

Submission status: Wrong Answer

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

from collections import deque
Q = deque()
Q.append([0,0])
cnt=0
costs=[-10**10]*n
while Q:
    if cnt>10*n:
        break
    now,now_cost = Q.popleft()
    for nxt,new_cost in link[now]:
        if costs[nxt] >= now_cost+new_cost or costs[nxt]==10**10:
            continue
        if cnt>n+1:
            costs[nxt]=10**10
        else:
            costs[nxt]=now_cost+new_cost
        Q.append([nxt,costs[nxt]])
        cnt+=1

if costs[-1]==10**10:
    print(-1)
else:
    print(max(0,costs[-1]))

Submission status: Wrong Answer

Solution code:
f=lambda: map(int,input().split())
    
V,E,P=f()
G=[]
for _ in range(E):
    s,t,d=f()
    G.append((s,t,-(d-P)))

INF=float('inf')
res=[INF]*(V+1)
res[1]=0

def Bellman_Ford():
    for s,t,d in G:
        res[t]=min(res[t],res[s]+d)
        
negative_flg=False
r=INF
for _ in range(V):
    tmp=res[:]
    Bellman_Ford()
    r=min(res[-1],r)
    if tmp==res:
        break
else:
    r0=res[-1]
    for _ in range(V):
        tmp=res[:]
        for s,t,d in G:
            res[t]=-INF
    if r0!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-r,0))

Submission status: Wrong Answer

Solution code:
f=lambda: map(int,input().split())
    
V,E,P=f()
G=[]
for _ in range(E):
    s,t,d=f()
    G.append((s,t,-(d-P)))

INF=float('inf')
res=[INF]*(V+1)
res[1]=0

def Bellman_Ford():
    for s,t,d in G:
        res[t]=min(res[t],res[s]+d)
        
negative_flg=False
r=INF
for _ in range(V):
    tmp=res[:]
    Bellman_Ford()
    r=min(res[-1],r)
    if tmp==res:
        break
else:
    r0=res[-1]
    for _ in range(V):
        tmp=res[:]
        Bellman_Ford()
    if r0!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-r,0))

Submission status: Wrong Answer

Solution code:
f=lambda: map(int,input().split())
    
V,E,P=f()
G=[]
for _ in range(E):
    s,t,d=f()
    G.append((s,t,-(d-P)))

INF=float('inf')
res=[INF]*(V+1)
res[1]=0

def Bellman_Ford():
    for s,t,d in G:
        res[t]=min(res[t],res[s]+d)
        
negative_flg=False
for _ in range(V):
    tmp=res[:]
    Bellman_Ford()
    if tmp==res:
        break
else:
    r0=res[-1]
    for _ in range(V):
        tmp=res[:]
        Bellman_Ford()
    if r0!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-res[-1],0))

Submission status: Wrong Answer

Solution code:
f=lambda: map(int,input().split())
    
V,E,P=f()
G=[]
for _ in range(E):
    s,t,d=f()
    G.append((s,t,-(d-P)))

INF=float('inf')
res=[INF]*(V+1)
res[1]=0

def Bellman_Ford():
    for s,t,d in G:
        res[t]=min(res[t],res[s]+d)
        
negative_flg=False
for _ in range(V):
    tmp=res[:]
    Bellman_Ford()
    if tmp==res:
        break
else:
    tmp=res[:]
    Bellman_Ford()
    if tmp[-1]!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-res[-1],0))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s):##Bellman-Ford
    n=len(graph)
    INF=10**15
    dist = [INF]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for _ in range(n-1):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for u in range(n):
        for v,c in graph[u]:
            if dist[v] >dist[u]+c:
                is_m[v]=True
    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0)
if ism[-1]:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s,n):##Bellman-Ford
    n=len(graph)
    INF=10**15
    dist = [INF]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for _ in range(n-1):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for u in range(n):
        for v,c in graph[u]:
            if dist[v] >dist[u]+c:
                is_m[v]=True
    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0,m)
if ism[-1]:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s,n):##Bellman-Ford
    n=len(graph)
    INF=10**15
    dist = [INF]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for _ in range(n-1):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for u in range(n):
        if dist[u]==INF:
            is_m[u]=True##この場合は閉路ではなく到達不可能
            continue
        for v,c in graph[u]:
            if dist[v] >dist[u]+c:
                is_m[v]=True
    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0,m)
if ism[-1]:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s,n):##Bellman-Ford
    n=len(graph)
    dist = [float("inf")]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for loop in range(1,n):#n ::エッジの数
        for u in range(n):
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for u in range(n):
        for v,c in graph[u]:
            if dist[v] >dist[u]+c:
                is_m[v]=True
                is_m[u]=True

    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0,m)
if ism[-1]:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s,n):##Bellman-Ford
    n=len(graph)
    dist = [float("inf")]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for loop in range(1,n):#n ::エッジの数
        for u in range(n):
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
    for u in range(n):
        if dist[u]==float("inf"):
            is_m[u]=True##この場合は閉路ではなく到達不可能
        for v,c in graph[u]:
            if dist[v] >dist[u]+c:
                is_m[v]=True

    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0,m)
if ism[-1]:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def BF(graph,s,n):##Bellman-Ford
    n=len(graph)
    dist = [float("inf")]*n
    dist[s] = 0
    is_m=[False]*n #負の径路があるか
    for loop in range(1,n+1):#neg ::エッジの数
        for u in range(n):
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v] =dist[u]+c
                    if loop==n:
                        is_m[v]=True

    return dist,is_m
n,m,p  = ma()
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = ma()
    G[a-1].append((b-1,-c+p))##コストが高いほうがいいので反転させておく
d,ism=BF(G,0,m)
if ism[-1] or d[-1]==10**15:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(a)
  
  toflag[0]=True
  otflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  g=np.array([[10**9 for i in range(n)] for i in range(n)])
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      g[a][b]=min(g[a][b],c)
  g=np.where(g==10**9,0,g)
  try:
    d=bellman_ford(csr_matrix(g),indices=0).astype(int)
    print(max(0,-d[-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(a)
  
  toflag[0]=True
  otflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  g=np.array([[10**9 for i in range(n)] for i in range(n)])
  for a,b,c in edges:
    g[a][b]=min(g[a][b],c)
  
  try:
    d=bellman_ford(csr_matrix(g),indices=0).astype(int)
    print(max(0,-d[-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(a)
  
  toflag[0]=True
  otflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  g=np.array([[10**9 for i in range(n)] for i in range(n)]).astype(int)
  
  try:
    d=bellman_ford(csr_matrix(g),indices=0).astype(int)
    print(max(0,-d[-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(b)
  
  toflag[0]=True
  otflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  dic={}
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      if (a,b) in dic.keys():
        dic[(a,b)]=min(dic[(a,b)],c)
      else:
        dic[(a,b)]=c

  row=[]
  col=[]
  data=[]
  for (a,b),c in dic.items():
      row.append(a)
      col.append(b)
      data.append(c)
  g=csr_matrix((data,(row,col)), shape=(n,n))
  try:
    d=bellman_ford(g,indices=0).astype(int)
    print(max(0,-d[-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(b)
  
  toflag[0]=True
  toflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  dic={}
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      if (a,b) in dic.keys():
        dic[(a,b)]=min(dic[(a,b)],c)
      else:
        dic[(a,b)]=c

  row=[]
  col=[]
  data=[]
  for (a,b),c in dic.items():
      row.append(a)
      col.append(b)
      data.append(c)
  g=csr_matrix((data,(row,col)), shape=(n,n))
  
  try:
    d=bellman_ford(g,indices=[0]).astype(int)
    print(max(0,-d[0][-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(b)
  
  toflag[0]=True
  toflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  g=[[10**9]*n for i in range(n)]
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      g[a][b]=min(g[a][b],c)
  
  try:
    d=bellman_ford(csr_matrix(g),indices=[0]).astype(int)
    print(max(0,-d[0][-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(10**5)

def dfs(s):
  for u in to[s]:
    if not toflag[u]:
      toflag[u]=True
      dfs(u)

def rdfs(s):
  for u in ot[s]:
    if not otflag[u]:
      otflag[u]=True
      rdfs(u)

def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1, input().split())
    edges[i]=[a,b,-(c+1-p)]
    to[a].append(b)
    ot[b].append(b)
  
  toflag[0]=True
  toflag[-1]=True
  dfs(0)
  rdfs(n-1)
  
  g=np.array([[10**9]*n for i in range(n)])
  for a,b,c in edges:
    if toflag[a] and otflag[b]:
      g[a][b]=min(g[a][b],c)
  
  try:
    d=bellman_ford(csr_matrix(g)).astype(int)
    print(max(0,-d[0][-1]))
  except NegativeCycleError:
    print(-1)

    
if __name__=='__main__':
  n,m,p=map(int,input().split())
  edges=[[] for i in range(m)]
  to=[[] for i in range(n)]
  ot=[[] for i in range(n)]
  toflag=[False]*n
  otflag=[False]*n
  main()

Submission status: Wrong Answer

Solution code:
from numpy.core.numeric import indices
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import csr_matrix
import numpy as np
import sys
sys.setrecursionlimit(10**5)

def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        edges[i]=[a,b,-(c+1-p)]
        to[a].append(b)
        ot[b].append(a)

    
    toflag[0]=True
    otflag[n-1]=True
    dfs(0) # check for 0 to i path
    rdfs(n-1) # check for n-1 to i path
    
    for a,b,c in edges:
        if toflag[a] and otflag[a] and toflag[b] and otflag[b]: 
            g[a][b]=min(c,g[a][b]);


    try:
        d=bellman_ford(csr_matrix(g), indices=[0]).astype(int)
        print(max(-d[0][-1], 0))
    except NegativeCycleError:
        print(-1)



if __name__=='__main__':
    n,m,p=map(int,input().split())
    g=np.array([[10**9]*n for i in range(n)])
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    edges=[[] for i in range(m)]
    main()

Submission status: Wrong Answer

Solution code:
from numpy.core.numeric import indices
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import numpy as np
import sys
sys.setrecursionlimit(10**5)

def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        edges[i]=[a,b,-(c+1-p)]
        to[a].append(b)
        ot[b].append(a)

    
    toflag[0]=True
    otflag[n-1]=True
    dfs(0) # check for 0 to i path
    rdfs(n-1) # check for n-1 to i path
    
    for a,b,c in edges:
        if toflag[a] and otflag[a] and toflag[b] and otflag[b]: 
            g[a][b]=min(c,g[a][b]);


    try:
        d=bellman_ford(g, indices=[0]).astype(int)
        print(max(-d[0][-1], 0))
    except NegativeCycleError:
        print(-1)



if __name__=='__main__':
    n,m,p=map(int,input().split())
    g=np.array([[10**9]*n for i in range(n)])
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    edges=[[] for i in range(m)]
    main()

Submission status: Wrong Answer

Solution code:
from numpy.core.numeric import indices
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import numpy as np
import sys
sys.setrecursionlimit(10**5)

def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        g[a][b]=min(g[a][b], -(c+1-p))
        to[a].append(b)
        ot[b].append(a)

    toflag[0]=True
    otflag[n-1]=True
    dfs(0) # check for 0 to i path
    rdfs(n-1) # check for n-1 to i path
 
    for i in range(n):
        for j in range(n):
            if toflag[i] and otflag[i] and toflag[j] and otflag[j]: continue;
            g[i][j]=0

    try:
        d=bellman_ford(g, indices=[0]).astype(int)
        print(max(-d[0][-1], 0))
    except NegativeCycleError:
        print(-1)



if __name__=='__main__':
    n,m,p=map(int,input().split())
    g=np.array([[0]*n for i in range(n)])
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    main()

Submission status: Wrong Answer

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[b] > dist[a] + c:
                dist[b] = dist[a] + c

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

    score = -dist[N - 1]

    if score == INF:
        print(-1)
    else:
        print(max(0, score))

    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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[b] > dist[a] + c:
                dist[b] = dist[a] + c

    score1 = -dist[N - 1]

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

    score2 = -dist[N - 1]

    if score1 < score2:
        print(-1)
    else:
        print(max(0, score1))

    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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 a, b, c in edge:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c

    d1 = dist[N - 1]

    for a, b, c in edge:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c

    d2 = dist[N - 1]

    if d1 > d2:
        print(-1)
    else:
        print(max(0, -d1))

    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
N,M,P = map(int, input().split())
ABC = []
for _ in range(M):
    A,B,C = map(int, input().split())
    ABC.append((A-1,B-1,C-P))

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: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

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

stack = [0]
vis_go = set([0])
while stack:
    v = stack.pop()
    for to in es[v]:
        if to in vis_go: continue
        vis_go.add(to)
        stack.append(to)
stack = [N-1]
vis_bk = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in vis_bk: continue
        vis_bk.add(to)
        stack.append(to)
use = vis_go & vis_bk

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for i in range(len(use)):
    for a,b,c in ABC:
        a,b,c = a-1,b-1,P-c
        if a not in use or b not in use: continue
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c
            if i==len(use)-1 and b==N-1:
                print(-1)
                exit()
print(max(0,-dist[-1]))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

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

stack = [0]
vis_go = set([0])
while stack:
    v = stack.pop()
    for to in es[v]:
        if to in vis_go: continue
        vis_go.add(to)
        stack.append(to)
stack = [N-1]
vis_bk = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in vis_bk: continue
        vis_bk.add(to)
        stack.append(to)
use = vis_go & vis_bk

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for i in range(len(use)):
    for a,b,c in ABC:
        a,b,c = a-1,b-1,P-c
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c
            if i==len(use)-1 and b==N-1:
                print(-1)
                exit()
print(max(0,-dist[-1]))

Submission status: Wrong Answer

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0)]
D=[0]*2+[-9e9]*N
def f():
 for _ in D:
  for a,b,c in E:D[b]=max(D[b],D[a]+c-P)
f()
s=D[N]
f()
print([max(s,0),-1][s<D[N]])

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,m,p = map(int, input().split())
ns = [[] for _ in range(n)]
mc = -1
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    ns[u].append((p-c,v))
### ダイクストラ dijkstra
def dijkstra(start):
    import heapq
    vals = [None] * n
    h = [(0, start)] # (距離, ノード番号)
    vals[start] = 0
    while h:
        val, u = heapq.heappop(h)
        if val>vals[u]:
            continue
        for d, v in ns[u]:
            if vals[v] is None or vals[v]>val+d:
                vals[v] = val+d
                heapq.heappush(h, (vals[v], v))
    return vals
def bf(start):
    dist = [float("inf")]*n
    dist[start] = 0
    seen = [False] * n
    seen[start] = True
    for i in range(3*n):
        for u in range(n):
            if not seen[u]:
                continue
            for c,v in ns[u]:
                if dist[v] > dist[u] + c:
                    seen[v] = True
                    dist[v] = dist[u] + c
                    if i>=n-1 and v==n-1:
                        return -1
    return dist

dist = bf(0)
if dist==-1:
    ans = -1
else:
    ans = max(0, dist[n-1]*-1)
print(ans)