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

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict

    n, m, p = map(int, readline().split())
    edge = defaultdict(list)

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

    dist = [INF] * n
    dist[0] = 0

    for _ in range(n - 1):
        for u in range(n):
            for v, w in edge[u]:
                dist[v] = min(dist[v], dist[u] + w)

    for _ in range(n):
        for u in range(n):
            for v, w in edge[u]:
                if dist[v] > dist[u] + w:
                    dist[v] = -INF

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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

import sys
sys.setrecursionlimit(1000000)

import collections

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

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

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

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

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

Submission status: Accepted

Solution code:
from collections import deque
import sys


class mEdge():

    def __init__(self, _from, _to, _cost):
        self.From = _from
        self.to = _to
        self.cost = _cost


class bellman_ford():
    def __init__(self, V):
        self.G = []
        self._V = N
        self._E = 0

    def add(self, _from, _to, _cost):
        self.G.append(mEdge(_from, _to, _cost))
        self._E += 1

    def shortest_path(self, s):
        d = [10**20]*(self._V+1)
        d[s] = 0
        for _ in range(self._V):
            flag = False
            for edge in self.G:
                newlen = d[edge.From]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
        return d

    def have_negative_circle(self):
        d = [10**20]*(self._V+1)
        d[1] = 0
        for i in range(1, self._V+1):
            flag = False
            for edge in self.G:
                newlen = d[edge.From]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
            if i == self._V:
                return True
        return False


# Coins Respawn
sys.setrecursionlimit(10**7)
N, M, P = map(int, input().split())
graph = []
d = deque()


from_1 = [[] for i in range(N+1)]
from_N = [[] for i in range(N+1)]

for _ in range(M):
    a, b, c = map(int, input().split())
    from_1[a].append(b)
    from_N[b].append(a)
    d.append((a, b, P-c))


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True
G = bellman_ford(N)

while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        G.add(p, q, weight)

if G.have_negative_circle():
    print(-1)
else:

    print(max(0, -G.shortest_path(1)[N]))

Submission status: Accepted

Solution code:
from collections import deque
import sys


class mEdge():

    def __init__(self, _from, _to, _cost):
        self.From = _from
        self.to = _to
        self.cost = _cost


class bellman_ford():
    def __init__(self, V):
        self.G = []
        self._V = N
        self._E = 0

    def add(self, _from, _to, _cost):
        self.G.append(mEdge(_from, _to, _cost))
        self._E += 1

    def shortest_path(self, s):
        d = [10**20]*(self._V+1)
        d[s] = 0
        for _ in range(self._V):
            flag = False
            for edge in self.G:
                newlen = d[edge.From]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
        return d

    def have_negative_circle(self):
        d = [10**20]*(self._V+1)
        d[1] = 0
        for i in range(1, self._V+1):
            flag = False
            for edge in self.G:
                newlen = d[edge.From]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
            if i == self._V:
                return True
        return False


# Coins Respawn
sys.setrecursionlimit(10**7)
N, M, P = map(int, input().split())
graph = []
d = deque()


from_1 = [[] for i in range(N+1)]
from_N = [[] for i in range(N+1)]

for _ in range(M):
    a, b, c = map(int, input().split())
    from_1[a].append(b)
    from_N[b].append(a)
    d.append((a, b, P-c))


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True
G = bellman_ford(N)

while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        G.add(p, q, weight)

if G.have_negative_circle():
    print(-1)
else:

    print(max(0, -G.shortest_path(1)[N]))

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

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

to = [[] for _ in range(N + 1)]
ot = [[] for _ in range(N + 1)]
edges = [[] for _ in range(N + 1)]

for a, b, c in X:
    edges[a].append((b, c - P))
    to[a].append(b)
    ot[b].append(a)

ok_1 = [False] * (N + 1)
ok_n = [False] * (N + 1)
ok_1[1] = True
ok_n[N] = True

q = deque()
q.append(1)
while q:
    u = q.popleft()
    for v in to[u]:
        if not ok_1[v]:
            ok_1[v] = True
            q.append(v)
            
q = deque()
q.append(N)
while q:
    u = q.popleft()
    for v in ot[u]:
        if not ok_n[v]:
            ok_n[v] = True
            q.append(v)

INF = 10 ** 9 + 7
d = [INF] * (N + 1)
d[1] = 0
updated = True
cnt = 0
while updated and cnt <= N:
    updated = False
    cnt += 1
    for u in range(1, N + 1):
        if not ok_1[u] or not ok_n[u]:
            continue
            
        for v, c in edges[u]:
            if not ok_1[v] or not ok_n[v]:
                continue
                
            if d[v] > d[u] - c:
                d[v] = d[u] - c
                updated = True

if cnt > N:
    print(-1)
else:
    print(max(0, -d[-1]))

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

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

to = [[] for _ in range(N + 1)]
ot = [[] for _ in range(N + 1)]
edges = [[] for _ in range(N + 1)]

for a, b, c in X:
    edges[a].append((b, c - P))
    to[a].append(b)
    ot[b].append(a)

ok_1 = [False] * (N + 1)
ok_n = [False] * (N + 1)

def dfs_1(u):
    if ok_1[u]:
        return
    
    ok_1[u] = True
    for v in to[u]:
        dfs_1(v)
        
def dfs_n(u):
    if ok_n[u]:
        return
    
    ok_n[u] = True
    for v in ot[u]:
        dfs_n(v)

dfs_1(1)
dfs_n(N)

INF = 10 ** 9 + 7
d = [INF] * (N + 1)
d[1] = 0
updated = True
cnt = 0
while updated and cnt <= N:
    updated = False
    cnt += 1
    for u in range(1, N + 1):
        if not ok_1[u] or not ok_n[u]:
            continue
            
        for v, c in edges[u]:
            if not ok_1[v] or not ok_n[v]:
                continue
                
            if d[v] > d[u] - c:
                d[v] = d[u] - c
                updated = True

if cnt > N:
    print(-1)
else:
    print(max(0, -d[-1]))

Submission status: Accepted

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

def main():
  n, m, p = map(int, input().split())
  edge = []
  for _ in range(m):
    a, b, c = map(int, input().split())
    edge.append((a, b, c-p))
  dist = [-float("inf")]*(n+1)
  dist[1] = 0
  for i in range(n):
    for a, b, c in edge:
      if dist[b] < dist[a] + c:
        dist[b] = dist[a] + c
  ans = max(dist[n], 0)
  for i in range(n):
    for a, b, c in edge:
      if dist[b] != float("inf") and dist[b] < dist[a] + c:
        dist[b] = float("inf")
  if dist[n] == float("inf"):
    ans = -1
  print(ans)
if __name__ == "__main__":
  main()

Submission status: Accepted

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

n, m, p = map(int, input().split())
edge = []
for _ in range(m):
  a, b, c = map(int, input().split())
  edge.append((a, b, c-p))
dist = [-float("inf")]*(n+1)
dist[1] = 0
for i in range(n):
  for a, b, c in edge:
    if dist[b] < dist[a] + c:
      dist[b] = dist[a] + c
ans = max(dist[n], 0)
for i in range(n):
  for a, b, c in edge:
    if dist[b] != float("inf") and dist[b] < dist[a] + c:
      dist[b] = float("inf")
if dist[n] == float("inf"):
  ans = -1
print(ans)

Submission status: Accepted

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

input = sys.stdin.buffer.readline
epsilon = 2 ** -26 # > 10 ** -8, which is the smallest cost scipy's bellman_ford can deal with. 

N, M, P = map(int, input().split())
graph = np.zeros((N, N), np.float64)
for _ in range(M):
    a, b, c = map(int, input().split())
    if graph[a-1][b-1] == 0:
        if -c+P == 0:
            graph[a-1][b-1] = epsilon
        else:
            graph[a-1][b-1] = -c+P
    elif graph[a-1][b-1] > -c+P:
        if -c+P == 0:
            graph[a-1][b-1] = epsilon
        else:
            graph[a-1][b-1] = -c+P

tmp = graph[-1, 0]
#connect N to 1
graph[-1, 0] = epsilon
_, labels = connected_components(graph, connection = "strong")
mask = (labels == labels[0])

#recover original N to 1 path.
graph[-1, 0] = tmp
graph = graph[mask, :][:, mask]

try:
    ans = bellman_ford(graph, directed = True, indices = 0)[-1]
    ans = max(0, int(round(-ans)))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque #,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,m,p = inm()
dst = [{} for i in range(n+1)]
src = [{} for i in range(n+1)]
es = []
for i in range(m):
    a,b,c = inm()
    dst[a][b] = src[b][a] = p-c
    es.append((a,b,p-c))

rf1 = [False]*(n+1)
rf1[1] = True
q = deque([1])
while len(q)>0:
    x = q.popleft()
    for y in dst[x]:
        if not rf1[y]:
            rf1[y] = True
            q.append(y)

rtn = [False]*(n+1)
rtn[n] = True
q = deque([n])
while len(q)>0:
    x = q.popleft()
    for y in src[x]:
        if not rtn[y]:
            rtn[y] = True
            q.append(y)

ddprint(rf1)
ddprint(rtn)

use = [rf1[i] and rtn[i] for i in range(n+1)]

es = [z for z in es if use[z[0]] and use[z[1]]]
ddprint(es)

dp = [BIG]*(n+1)
dp[1] = 0
for i in range(n):
    ddprint(dp)
    for a,b,c in es:
        if dp[b] > dp[a]+c:
            dp[b] = dp[a]+c
            if i==n-1:
                print(-1)
                exit()

print(max(0,-dp[n]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, m, p = LI()
abc = [LI() for _ in range(m)]
edges = [[] for _ in range(n)]
inv_edges = [[] for _ in range(n)]
for a, b, c in abc:
    edges[a-1].append((b-1, c))
    inv_edges[b-1].append(a-1)

visited = [False] * n
stack = [n-1]
while stack:
    v = stack.pop()
    visited[v] = True
    for u in inv_edges[v]:
        if visited[u]:
            continue
        stack.append(u)

dp = [-float('inf')] * n
dp[0] = 0
tmp = -1
for _ in range(n+1):
    flag = False
    for v in range(n):
        score = dp[v]
        for u, c in edges[v]:
            if dp[u] < score + c - p and visited[u]:
                dp[u] = score + c - p
                flag = True
if flag:
    print(-1)
else:
    print(max(0, dp[n-1]))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)



    inf=10**14
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[set() for _ in range(N)]
        d[s]=0
        count=0
        for _ in range(N):
            update=False
            for e in range(N):
                if d[e]==inf:
                    continue
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if x<d[ne]:
                        d[ne]=x
                        update=True
            if update==False: break

        for _ in range(N):
            update=False
            for e in range(N):
                if d[e]==inf:
                    continue
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if x<d[ne]:
                        d[ne]=-inf
                        update=True
            if update==False: break

        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]==-inf:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n):
    res = [None] * n
    for i in range(n):
        res[i] = II()
    return res
def LIR(n):
    res = [None] * n
    for i in range(n):
        res[i] = LI()
    return res
def FR(n):
    res = [None] * n
    for i in range(n):
        res[i] = IF()
    return res
def LIR(n):
    res = [None] * n
    for i in range(n):
        res[i] = IF()
    return res
def LIR_(n):
    res = [None] * n
    for i in range(n):
        res[i] = LI_()
    return res
def SR(n):
    res = [None] * n
    for i in range(n):
        res[i] = S()
    return res
def LSR(n):
    res = [None] * n
    for i in range(n):
        res[i] = LS()
    return res
mod = 1000000007
inf = float('INF')

#solve
def solve():
    n, m, p = LI()
    edg = [[] for i in range(n)]
    for _ in range(m):
        a, b, c = LI_()
        c += 1
        edg[a].append((b, c))
    dp = [-inf] * n
    dp[0] = 0
    for j in range(n):
        for i in range(n):
            score = dp[i]
            for e, s in edg[i]:
                if dp[e] < score + s - p:
                    dp[e] = score + s - p
    ans = dp[:]
    for j in range(n):
        for i in range(n):
            score = dp[i]
            for e, s in edg[i]:
                if dp[e] < score + s - p:
                    dp[e] = inf
    if ans[-1] != dp[-1]:
        print(-1)
    else:
        print(abs(max(ans[-1],0)))
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
from heapq import heappop, heappush
import sys
input = sys.stdin.readline

N, M, P = map(int, input().split())
d = defaultdict(list)
e = defaultdict(list)
cd = defaultdict(list)
l = []

for _ in range(M):
    a, b, c = map(int, input().split())
    cd[a].append((b, P-c))
    d[a].append(b)
    e[b].append(a)

def check_visited(d, start):
    visited = [False]*(N+1)
    visited[start] = True
    q = deque([start])
    while q:
        s = q.popleft()
        for t in d[s]:
            if visited[t]:continue
            visited[t] = True
            q.append(t)
    
    s = set()
    for i in range(1, N+1):
        if visited[i]:
            s.add(i)
    return s

def shortest_path(s):
    INF = 10**18
    dist = [float("inf")]*(N+1)
    dist[s] = 0

    for i in range(N):
        for a, b, c in l:
            if dist[b]>dist[a]+c:
                dist[b] = dist[a]+c
                if i==N-1:
                    return dist, True
    return dist, False

add_l = check_visited(d, 1)&check_visited(e, N)
for a in add_l:
    for b, c in cd[a]:
        l.append((a, b, c))
d1, neg = shortest_path(1)
print(-1 if neg else max(0, -d1[N]))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
from heapq import heappop, heappush
import sys
input = sys.stdin.readline

N, M, P = map(int, input().split())
d = defaultdict(list)
e = defaultdict(list)
cd = defaultdict(list)
l = []

for _ in range(M):
    a, b, c = map(int, input().split())
    cd[a].append((b, P-c))
    d[a].append(b)
    e[b].append(a)

def check_visited(d, start):
    visited = [False]*(N+1)
    visited[start] = True
    q = deque([start])
    while q:
        s = q.popleft()
        for t in d[s]:
            if visited[t]:continue
            visited[t] = True
            q.append(t)
    
    s = set()
    for i in range(1, N+1):
        if visited[i]:
            s.add(i)
    return s

def shortest_path(s):
    INF = 10**18
    dist = [float("inf")]*(N+1)
    dist[s] = 0

    for i in range(N):
        for a, b, c in l:
            if dist[b]>dist[a]+c:
                dist[b] = dist[a]+c
                if i==N-1:
                    return dist, True
    return dist, False

add_l = check_visited(d, 1)&check_visited(e, N)
for a in add_l:
    for b, c in cd[a]:
        l.append((a, b, c))
d1, neg = shortest_path(1)
if neg:
    print(-1)
elif d1[N]<0:
    print(-d1[N])
else:
    print(0)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N,M,P = map(int,readline().split())
ABC = np.array(read().split(),np.int64)

A = ABC[::3]
B = ABC[1::3]
C = ABC[2::3]

C = P-C

# bellman fordでAからBへの最短距離を求める

INF = 10**18
dist = np.full(N+1,INF,np.int64)
dist[1] = 0
for T in range(N+N+10):
    x = dist[A] + C
    update = (dist[B] > x) & (x < INF//2)
    b = B[update]; x = x[update]
    if T > N:
        dist[b] = -INF
    else:
        ind = x.argsort(); x = x[ind][::-1]; b=b[ind][::-1]
        dist[b] = x

answer = -dist[N]
if answer < 0:
    answer = 0
elif answer == INF:
    answer = -1
print(answer)

Submission status: Accepted

Solution code:
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import sys
input = sys.stdin.readline


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

    edges = []
    routes = [[] for _ in range(n)]
    rev_routes = [[] for _ in range(n)]

    def get_reachable_nodes(start, routes):
        seen = {start}
        todo = []
        for to in routes[start]:
            todo.append(to)
            seen.add(to)

        while todo:
            node = todo.pop()
            for to in routes[node]:
                if to in seen:
                    continue
                todo.append(to)
                seen.add(to)
        return seen

    for _ in range(m):
        node1, node2, value = map(int, input().split())
        node1, node2, value = node1 - 1, node2 - 1, value - p
        edges.append([node1, node2, value])
        routes[node1].append(node2)
        rev_routes[node2].append(node1)

    from_start = get_reachable_nodes(0, routes)
    if n-1 not in from_start:
        print(-1)
        return

    to_goal = get_reachable_nodes(n-1, rev_routes)

    from_start_to_goal = from_start & to_goal

    temp_dict = dict()

    for row, col, value in edges:
        if {row, col} <= from_start_to_goal:
            if not (row, col) in temp_dict:
                temp_dict[(row, col)] = -value
            else:
                temp_dict[(row, col)] = min(-value, temp_dict[(row, col)])

    values = []
    rows = []
    cols = []

    for (row, col), minus_value in temp_dict.items():
        values.append(minus_value)
        rows.append(row)
        cols.append(col)

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import csr_matrix
from collections import defaultdict

n, m, p = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]
INF = 10 ** 9

fwd = [[] for _ in range(n + 1)]
rev = [[] for _ in range(n + 1)]

for a, b, c in abc:
    fwd[a].append(b)
    rev[b].append(a)


def dfs(s, adj):
    stack = [s]
    arrived = [False] * (n + 1)
    arrived[s] = True
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if not arrived[v]:
                arrived[v] = True
                stack.append(v)

    return arrived


can_go_fwd = dfs(1, fwd)
can_go_rev = dfs(n, rev)

data = defaultdict(lambda: INF)
for a, b, c in abc:
    if can_go_fwd[a] and can_go_rev[b]:
        data[(a, b)] = min(data[(a, b)], p - c)

row = []
col = []
cost = []
for (a, b), c in data.items():
    row.append(a)
    col.append(b)
    cost.append(c)

g = csr_matrix((cost, (row, col)), shape=(n + 1, n + 1))

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

Submission status: Accepted

Solution code:
class Edge:
  def __init__(self, starting_point, arrival_point, cost):
    self.starting_point = starting_point
    self.arrival_point = arrival_point
    self.cost = cost

def solve():
  N, M, P = map(int, input().split())
  edges = []
  INF = float('inf')
  dist = [INF for _ in range(N + 10)]
  dist[1] = 0
  for i in range(M):
    a, b, c = map(int, input().split())
    e = Edge(a, b, -c + P)
    edges.append(e)
  for i in range(2 * N):
    for e in edges:
      if dist[e.arrival_point] > e.cost + dist[e.starting_point]:
        dist[e.arrival_point] = e.cost + dist[e.starting_point]
        if i == N - 1:
          dist[e.arrival_point] = -INF
  if dist[N] != -INF:
    return max(-dist[N], 0)
  else:
    return -1
print(solve())

Submission status: Accepted

Solution code:
def resolve():
    def BF(s, n, edge, inf=float("inf")):
        d = [inf for i in range(n)]
        d[s] = 0
        for i in range(n * 2):
            for before, after, dist in edge:
                if before != inf and d[before] + dist < d[after]:
                    if i < n:
                        d[after] = d[before] + dist
                    else:
                        d[after] = -inf
        return d
    n, m, p = map(int, input().split())
    inf = float("inf")
    edge = [list(map(int, input().split())) for _ in range(m)]
    edge = [[x - 1, y - 1, p - z] for x, y, z in edge]
    ans = -BF(0, n, edge, inf)[-1]
    print(max(0, ans) if ans < inf else -1)


if __name__ == "__main__":
    resolve()