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: Time Limit Exceeded

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

def main():
    N, M, P = map(int, input().split())
    g = [[] for _ in range(N+1)]
    g2 = [[] for _ in range(N+1)]
    data = [list(map(int, input().split())) for _ in range(M)]
    for a, b, _ in data:
        g[b].append(a)
        g2[a].append(b)

    visit = [False]*(N+1)
    visit2 = [False]*(N+1)

    queue = [N]
    while len(queue) > 0:
        nextqueue = []
        for now in queue:
            visit[now] = True
            for next in g[now]:
                if not visit[next]:
                    nextqueue.append(next)
        queue = nextqueue[:]

    queue = [1]
    while len(queue) > 0:
        nextqueue = []
        for now in queue:
            visit2[now] = True
            for next in g2[now]:
                if not visit2[next]:
                    nextqueue.append(next)
        queue = nextqueue[:]




    for i in range(1, N+1):
        visit[i] = visit[i] and visit2[i]


    INF = 1000000001
    d = [(-1)*INF for i in range(N+1)]
    d[1] = 0

    for i in range(N):
        d_N = [d[i] for i in range(1, N+1) if visit[i]]
        for j in range(M):
            a = data[j][0]
            b = data[j][1]
            c = data[j][2]
            d[b] = max(d[b], d[a]+c-P)
        if i == N-1:
            if d_N != [d[i] for i in range(1, N+1) if visit[i]]:
                ans = -1

            else:
                ans = d[N]

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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from collections import deque

def main():
    n, m, p = map(int, input().split())
    edge = defaultdict(list)

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

    score = [0, 0] + [float("-inf")] * (n - 1)

    q = deque()
    q.append((1, [1]))

    while q:
        curr, visited = q.popleft()
        for b, c in edge[curr]:
            if b in visited:
                if score[curr] + c > score[b]:
                    score[curr] = float("inf")
                    for bb, cc in edge[curr]:
                        score[bb] = float("inf")
            else:
                score[b] = max(score[b], score[curr] + c)
                q.append((b, visited + [b]))

    print(max(0, score[n]) if score[n] != float("inf") else -1)


main()

Submission status: Time Limit Exceeded

Solution code:
from collections import* #defaultdict Counter deque appendleft
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

d=defaultdict(list)
n,m,p=map(int,input().split())

for s in range(m):
    a,b,c=map(int,input().split())
    d[a].append([b,c])

def BELLMANFORD(point,d,p):
    cost       = {node:-float("inf") for node in range(1,n+1)}
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.copy().items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p

    negative=[0]*n                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for now,lis in d.copy().items():
            for nex,c in lis:
                if negative[now-1]==1:
                    negative[nex-1]=1
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    negative[now-1]=1
 
    return cost,negative

def main():
    x,y=(BELLMANFORD(1,d,p))
    if y[n-1]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
 
from collections import* #defaultdict Counter deque appendleft
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

d=defaultdict(list)
n,m,p=map(int,input().split())

for s in range(m):
    a,b,c=map(int,input().split())
    d[a].append([b,c])
#print(d)

def BELLMANFORD(point,d,p):
    cost       = {node:-float("inf") for node in range(1,n+1)}
    preference = {node:None         for node in range(1,n+1)}      #最適路のこと
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.copy().items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    preference[nex]=now
 
    negative=[0]*n                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for now,lis in d.copy().items():
            for nex,c in lis:
                if negative[now-1]==1:
                    negative[nex-1]=1
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    preference[nex]=now
                    negative[now-1]=1
 
    return cost,negative

def main():
    x,y=(BELLMANFORD(1,d,p))
#    print(x,y)
    if y[n-1]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
 
from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！

d=defaultdict(list)
n,m,p=map(int,input().split())

for s in range(m):
    a,b,c=map(int,input().split())
    d[a].append([b,c])
#print(d)

def BELLMANFORD(point,d,p):
    cost       = {node:-float("inf")for node in range(1,n+1)}
    preference = {node:None         for node in range(1,n+1)}      #最適路のこと
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.copy().items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    preference[nex]=now
 
    negative=[0]*n                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for now,lis in d.copy().items():
            for nex,c in lis:
                if negative[now-1]==1:
                    negative[nex-1]=1
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    preference[nex]=now
                    negative[now-1]=1
 
    return cost,negative








def main():
    x,y=(BELLMANFORD(1,d,p))
#    print(x,y)
    if y[n-1]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M,P=map(int,input().split())
A=[0 for i in range(M)]
B=[0 for i in range(M)]
C=[0 for i in range(M)]
G=[dict() for i in range(N)]
H=[dict() for i in range(N)]
for i in range(M):
    A[i],B[i],C[i]=map(int,input().split())
    G[B[i]-1][A[i]-1]=C[i]
    H[A[i]-1][B[i]-1]=C[i]
reached1=[0 for i in range(N)]
q=[N-1]
while(len(q)>0):
    r=q.pop()
    reached1[r]=1
    for p in G[r]:
        if reached1[p]==0:
            q.append(p)
reached2=[0 for i in range(N)]
q=[0]
while(len(q)>0):
    r=q.pop()
    reached2[r]=1
    for p in H[r]:
        if reached2[p]==0:
            q.append(p)
reached=[reached1[i]*reached2[i] for i in range(N)]
vertex_list=[]
vertex_num=[-1 for i in range(N)]
tmp=1
for i in range(N):
    if reached[i]==1:
        vertex_list.append(i+1)
        vertex_num[i]=tmp
        tmp+=1
num_v=len(vertex_list)
edges=[]
for i in range(M):
    if reached[A[i]-1]==1 and reached[B[i]-1]==1:
        edges.append((vertex_num[A[i]-1],vertex_num[B[i]-1],P-C[i]))
inf=10**10
dist=[inf for i in range(num_v)]
dist[0]=0
#print(reached)
#print(edges)
#print(vertex_list)
#print(vertex_num)
#辺の緩和
for i in range(num_v):
    for edge in edges:
        if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
            dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
            if i==num_v-1:
                print(-1)
                exit()
print(max(-dist[-1],0))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from collections import deque

n, m, p = map(int, input().split())

edge = defaultdict(list)

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

score = [0, 0] + [float("-inf")] * (n - 1)

q = deque()
q.append((1, [1]))

while q:
    curr, visited = q.popleft()
    for b, c in edge[curr]:
        if b in visited:
            if score[curr] + c > score[b]:
                score[curr] = float("inf")
                for bb, cc in edge[curr]:
                    score[bb] = float("inf")
        else:
            score[b] = max(score[b], score[curr] + c)
            q.append((b, visited + [b]))

print(max(0, score[n]) if score[n] != float("inf") else -1)

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
A, B, C = (
    zip(*(map(int, input().split()) for _ in range(M))) if M else
    ((), ())
)

INF = 10**20

dp = [INF for _ in range(N + 1)]
used = [False for _ in range(N + 1)]
dp[1] = 0
used[1] = True
for k in range(2 * N):
    for a, b, c in zip(A, B, C):
        w = P - c
        if used[a] and dp[b] > dp[a] + w:
            dp[b] = dp[a] + w
            used[b] = True
            if k >= N - 1:
                dp[b] = -INF
ans = max(0, -dp[N])
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M,P=map(int,input().split())
A=[0 for i in range(M)]
B=[0 for i in range(M)]
C=[0 for i in range(M)]
G=[dict() for i in range(N)]
H=[dict() for i in range(N)]
for i in range(M):
    A[i],B[i],C[i]=map(int,input().split())
    G[B[i]-1][A[i]-1]=C[i]
    H[A[i]-1][B[i]-1]=C[i]
reached1=[0 for i in range(N)]
q=deque([N-1])
while(len(q)>0):
    r=q.popleft()
    reached1[r]=1
    for p in G[r]:
        if reached1[p]==0:
            q.append(p)
reached2=[0 for i in range(N)]
q=deque([0])
while(len(q)>0):
    r=q.popleft()
    reached2[r]=1
    for p in H[r]:
        if reached2[p]==0:
            q.append(p)
reached=[reached1[i]*reached2[i] for i in range(N)]
vertex_list=[]
vertex_num=[-1 for i in range(N)]
tmp=1
for i in range(N):
    if reached[i]==1:
        vertex_list.append(i+1)
        vertex_num[i]=tmp
        tmp+=1
num_v=len(vertex_list)
edges=[]
for i in range(M):
    if reached[A[i]-1]==1 and reached[B[i]-1]==1:
        edges.append((vertex_num[A[i]-1],vertex_num[B[i]-1],P-C[i]))
inf=10**10
dist=[inf for i in range(num_v)]
dist[0]=0
#print(reached)
#print(edges)
#print(vertex_list)
#print(vertex_num)
#辺の緩和
for i in range(num_v):
    for edge in edges:
        if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
            dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
            if i==num_v-1:
                print(-1)
                exit()
print(max(-dist[-1],0))

Submission status: Accepted

Solution code:
n,m,p = map(int, input().split())
edge = []
inv_link = [[] for _ in range(n)]
link = [[] for _ in range(n)]

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

def bell(edges, start,num_v):
    cost = [float('inf')] * num_v
    cost[start] = 0
    for _ in range(num_v):
        updated = False
        for a, b, c in edges:
            if cost[b] > cost[a] + c:
                cost[b] = cost[a] + c
                updated = True
        if not updated: break
    else:
        return False,cost
    return True,cost

from collections import deque
Q = deque()
Q.append([n-1,0])
visited=[-1]*n
visited[n-1]=0
while Q:
    now,cnt = Q.popleft()
    for nxt in inv_link[now]:
        if visited[nxt]!=-1:
            continue
        visited[nxt]=cnt+1
        Q.append([nxt,cnt+1])

new_edge=[]
for a,b,c in edge:
    if visited[a]==-1 or visited[b]==-1:
        continue
    new_edge.append([a,b,c])
ret,cost = bell(new_edge,0,n)
if ret:
    print(max(0,-cost[-1]))
else:
    print(-1)

Submission status: Accepted

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:
            if res[t]>res[s]+d:
                res[t]=-INF
    if r0!=res[-1]:
        negative_flg=True
if negative_flg:
    print(-1)
else:
    print(max(-r,0))

Submission status: Accepted

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
    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 _ in range(n):
        for u in range(n):
            if dist[u]==INF:
                continue
            for v,c in graph[u]:
                if dist[v] >dist[u]+c:
                    dist[v]=-INF
    return dist
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=BF(G,0)
if abs(d[-1])==10**15:
    print(-1)
else:
    print(max(0,-d[-1]))

Submission status: Accepted

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)
  
  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: Accepted

Solution code:
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 bellman_ford():
    for i in range(n):
        upd=False
        for a,b,c in edges:
            if d[b]>d[a]+c:
                upd=True
                d[b]=d[a]+c     
        if not upd:
            break
        if i == n-1:
            print(-1)
            exit()


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        edges.append([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(m):
        a,b,c=edges[i]
        if toflag[a] and otflag[a] and toflag[b] and otflag[b]: continue;
        edges[i]=[0,0,0]

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



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

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
import sys
from collections import deque

read = sys.stdin.read
INF = 1 << 60


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

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

    # Only consider nodes that can be reached from 1 and can reach N.
    reachable_1 = [False] * N
    reachable_N = [False] * N

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

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

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

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

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

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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

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


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

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

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

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

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

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

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

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

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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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


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

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

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

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

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

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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


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

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

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

    for _ in range(N):
        for a, b, c in edge:
            if dist[b] != INF and 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: Accepted

Solution code:
import sys
from collections import deque

    
def dfs(x,s):
    used = {s}
    search = deque([s])
    while search:
        ss = search.pop()
        for sss in x[ss]:
            if sss in used:
                continue
            used.add(sss)
            search.append(sss)
    return used


def bellmanford(edges):
    coins = [-float("inf")] * N
    coins[0] = 0
    for _ in range(N):
        f = True
        for u,v,c in edges:
            if coins[u] + c > coins[v]:
                coins[v] = coins[u] + c
                f = False
        if f:
            return max(0, coins[-1])
    return -1

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

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

print(bellmanford(ABC))

Submission status: Accepted

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:
                print(-1)
                exit()
print(max(0,-dist[-1]))

Submission status: Accepted

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)]
rns = [[] 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))
    rns[v].append(u)
q = [n-1]
seen = [False]*n
seen[n-1] = True
while q:
    u = q.pop()
    for v in rns[u]:
        if seen[v]:
            continue
        seen[v] = True
        q.append(v)
def bf(start):
    dist = [float("inf")]*n
    dist[start] = 0
    for i in range(n):
        for u in range(n):
            if dist[u]==float("inf"):
                continue
            for c,v in ns[u]:
                if dist[v] > dist[u] + c:
                    dist[v] = dist[u] + c
                    if i>=n-1 and seen[v]:
                        return -1
    return dist

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

Submission status: Accepted

Solution code:
import math
from collections import deque

def BellmanFord(edges, N, M, start):
    dist = [math.inf]*N
    dist[start] = 0

    for i in range(N):
        for j in range(M):
            if is_valid(edges[j][0], edges[j][1]):
                if dist[edges[j][1]] > dist[edges[j][0]] + edges[j][2]:
                    dist[edges[j][1]] = dist[edges[j][0]] + edges[j][2]
                    if i == N - 1:
                        return False

    return dist

def dfs(graph, N, start):
    visited = [False]*N
    visited[start] = True
    q = deque([start])

    while q:
        v = q.pop()
        for n_v in graph[v]:
            if not visited[n_v]:
                visited[n_v] = True
                q.append(n_v)
    
    return visited

def is_valid(f, t):
    return can_from_start[f] and can_from_start[t] and can_to_goal[f] and can_to_goal[t]


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

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

can_from_start = dfs(graph, N, 0)
can_to_goal = dfs(graph_inv, N, N - 1)

dist = BellmanFord(edges, N, M, 0)

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

Submission status: Accepted

Solution code:
INF = 10**18
def bellman_ford(s, n, g): # s: start, n: |V|, g; glaph 
    d = [INF]*n
    d[s] = 0
    for i in range(n-1): # max n-1 loops. if update d[] in n-th loop -> negative cycle
        update = False
        for v_from, v_to, cost in g:
            if d[v_from] != INF and d[v_to] > d[v_from] + cost:
                d[v_to] = d[v_from] + cost
                update = True
        if not update:
            break

    for i in range(n-1): # max n-1 loops. if update d[] in n-th loop -> negative cycle
        update = False
        for v_from, v_to, cost in g:
            if d[v_from] != INF and d[v_to] > d[v_from] + cost:
                d[v_to] = -INF
                update = True
        if not update:
            break

    return d
    


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


d = bellman_ford(0,n,g)
if d[-1] == -INF: print(-1)
else:
    ans = -d[-1]
    ans = max(0,ans)
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque
N,M,P = map(int,input().split())
INF = 10**18
edge = []
rev_edge = [[] for _ in range(N+1)]
dis = [INF]*(N+1)
dis[1] = 0
for i in range(M):
    A,B,C = map(int,input().split())
    edge.append((A,B,P-C))
    rev_edge[B].append(A)
d = deque()
can_arrive = set()
d.append(N)
can_arrive.add(N)
while d:
    x = d.popleft()
    for y in rev_edge[x]:
        if not y in can_arrive:
            d.append(y)
            can_arrive.add(y)

for i in range(N):
    update = False
    for j in range(M):
        A,B,cost = edge[j]
        if dis[A] != INF and dis[B] > dis[A]+cost:
            dis[B] = dis[A]+cost
            if B in can_arrive:
                update = True
ans = dis[N]
if update:
    print(-1)
else:
    print(max(0,-ans))