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
input=sys.stdin.readline  #危険！基本オフにしろ！

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

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

#print(d)


def BELLMANFORD(point,d,p):
    cost       = [-float("inf")]*(n+1)  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.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.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: Accepted

Solution code:
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！


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

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

#print(d)


def BELLMANFORD(point,d,p):
    cost       = [-float("inf") for node in range(n+1)]  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.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.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: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)

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

edges = []
routes  = [[] for i in range(n)]
rev_routes = [[] for i in range(n)]
from_start = set()
to_goal = set()

def dfs(node, routes, seen):
    if node in seen:
        return
    seen.add(node)
    candidates = routes[node]
    for to in candidates:
        dfs(to, routes, 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)

dfs(0, routes, from_start)
dfs(n-1, rev_routes, to_goal)

from_start_to_goal = from_start & to_goal

graph = [-float('INF')] * n
graph[0] = 0

for i in range(n):
    is_updated = False
    for node, to, value in edges:
        if node not in from_start_to_goal or to not in from_start_to_goal:
            continue
        current_point = graph[node]
        next_point = graph[node] + value
        if graph[to] < next_point:
            graph[to] = next_point
            is_updated = True
        else:
            continue
    if not is_updated:
        score = max(0, graph[n-1])
        break
else:
    score = -1
      
print(score)

Submission status: Accepted

Solution code:
import time

t1 = time.time()

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

to_w = [set() for _ in range(N)]
for a, b, c in ABC:
    to_w[a - 1].add((b - 1, P - c))
reachable_from_start = {0}
q = {0}
while q:
    u = q.pop()
    for v, _ in to_w[u]:
        if v not in reachable_from_start:
            reachable_from_start.add(v)
            q.add(v)


from_w = [set() for _ in range(N)]
for a, b, c in ABC:
    from_w[b - 1].add((a - 1, P - c))
reachable_to_goal = {N - 1}
q = {N - 1}
while q:
    u = q.pop()
    for v, _ in from_w[u]:
        if v not in reachable_to_goal:
            reachable_to_goal.add(v)
            q.add(v)


reachable = reachable_from_start & reachable_to_goal


to_w = [set() for _ in range(N)]
for a, b, c in ABC:
    if a - 1 in reachable and b - 1 in reachable:
        to_w[a - 1].add((b - 1, P - c))
d = [float("inf")] * N
d[0] = 0
q = {0}
while q:
    u = q.pop()

    for v, w in to_w[u]:
        tmp = d[u] + w
        if tmp < d[v]:
            d[v] = tmp
            if v not in q:
                q.add(v)

        if time.time() > 1.9 + t1:
            d[-1] = -float("inf")
            break
    else:
        continue
    break

if d[-1] == -float("inf"):
    print(-1)
else:
    print(max(0, -d[-1]))

Submission status: Accepted

Solution code:
def reachable(es, source):
	ret = {source}
	Q = [source]
	while Q:
		cur = Q.pop()
		for nxt in es[cur]:
			if nxt not in ret:
				Q.append(nxt)
				ret.add(nxt)
	return ret

def BellmanFord(V:int, es:list, source=0):
	INF = float("inf")
	D = [INF]*V
	D[source] = 0
	for _ in range(V):
		upd = False
		for f, t, c in es:
			tmp = D[f] + c
			if D[t] > tmp:
				D[t] = tmp
				upd = True
		if not upd:
			return D[-1]
	else:
		return None
	
def main():
	N,M,P,*L=map(int,open(0).read().split())
	fwd = [[] for _ in range(N)]
	bwd = [[] for _ in range(N)]
	tmp = []
	for a,b,c in zip(*[iter(L)]*3):
		fwd[a-1].append(b-1)
		bwd[b-1].append(a-1)
		tmp+=[(a-1,b-1,P-c)]
	judge = reachable(fwd,0) & reachable(bwd,N-1)
	ans = BellmanFord(N,[(a,b,c) for a,b,c in tmp if a in judge and b in judge])
	if ans==None:
		print(-1)
	else:
		print(max(0,-ans))

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
def reachable(es, source):
	ret = {source}
	Q = [source]
	while Q:
		cur = Q.pop()
		for nxt in es[cur]:
			if nxt not in ret:
				Q.append(nxt)
				ret.add(nxt)
	return ret

def BellmanFord(V:int, es:list, source=0):
	INF = float("inf")
	D = [INF]*V
	D[source] = 0
	for _ in range(V):
		upd = False
		for f, t, c in es:
			tmp = D[f] + c
			if D[t] > tmp:
				D[t] = tmp
				upd = True
		if not upd:
			return D[-1]
	else:
		return None
	
def main():
	N,M,P,*L=map(int,open(0).read().split())
	fwd = [[] for _ in range(N)]
	bwd = [[] for _ in range(N)]
	for a,b in zip(L[::3],L[1::3]):
		fwd[a-1].append(b-1)
		bwd[b-1].append(a-1)
	judge = reachable(fwd,0) & reachable(bwd,N-1)
	G = [(a-1,b-1,P-c) for a,b,c in zip(*[iter(L)]*3) if a-1 in judge and b-1 in judge]
	ans = BellmanFord(N,G)
	if ans==None:
		print(-1)
	else:
		print(max(0,-ans))

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
from collections import deque

def reachable(es, source):
	ret = {source}
	Q = [source]
	while Q:
		cur = Q.pop()
		for nxt in es[cur]:
			if nxt not in ret:
				Q.append(nxt)
				ret.add(nxt)
	return ret

def SPFA(G:list, source=0):
	V = len(G)
	d = [float("inf")]*V
	inQ = [False]*V
	cnt = [0]*V
	d[source] = 0
	cnt[source] = 1
	Q = deque([source])
	while Q:
		f = Q.popleft()
		inQ[f] = False
		for t,c in G[f]:
			dist = d[f] + c
			if dist < d[t]:
				d[t] = dist
				if not inQ[t]:
					Q.append(t)
					inQ[t] = True
					cnt[t] += 1
					front = Q.popleft()
					if d[front] > dist:
						Q.append(front)
					else:
						Q.appendleft(front)
				if cnt[t] > V:
					#negative cycle
					return None
	return d[-1]
	
def main():
	N,M,P,*L=map(int,open(0).read().split())
	fwd = [[] for _ in range(N)]
	bwd = [[] for _ in range(N)]
	G = [[] for _ in range(N)]
	for a,b in zip(L[::3],L[1::3]):
		fwd[a-1].append(b-1)
		bwd[b-1].append(a-1)
	judge = reachable(fwd,0) & reachable(bwd,N-1)
	for a,b,c in zip(*[iter(L)]*3):
		if a-1 in judge and b-1 in judge:
			G[a-1].append((b-1,P-c))
	ans = SPFA(G)
	if ans==None:
		print(-1)
	else:
		print(max(0,-ans))

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
from collections import deque

def reachable(es, source):
	ret = {source}
	Q = [source]
	while Q:
		cur = Q.pop()
		for nxt in es[cur]:
			if nxt not in ret:
				Q.append(nxt)
				ret.add(nxt)
	return ret

def SPFA(G:list, source=0):
	from collections import deque
	V = len(G)
	d = [float("inf")]*V
	inQ = [False]*V
	cnt = [0]*V
	d[source] = 0
	cnt[source] = 1
	Q = deque([source])
	_sum = 0
	_len = 1
	while Q:
		f = Q.popleft()
		inQ[f] = False
		_sum -= d[f]
		_len -= 1
		for t,c in G[f]:
			dist = d[f] + c
			if dist < d[t]:
				d[t] = dist
				if not inQ[t]:
					inQ[t] = True
					cnt[t] += 1
					if dist*_len < _sum:
						Q.appendleft(t)
					else:
						Q.append(t)
					_sum += dist
					_len += 1
				if cnt[t] > V:
					#negative cycle
					return None
	return d[-1]
	
def main():
	N,M,P,*L=map(int,open(0).read().split())
	fwd = [[] for _ in range(N)]
	bwd = [[] for _ in range(N)]
	G = [[] for _ in range(N)]
	for a,b in zip(L[::3],L[1::3]):
		fwd[a-1].append(b-1)
		bwd[b-1].append(a-1)
	judge = reachable(fwd,0) & reachable(bwd,N-1)
	for a,b,c in zip(*[iter(L)]*3):
		if a-1 in judge and b-1 in judge:
			G[a-1].append((b-1,P-c))
	ans = SPFA(G)
	if ans==None:
		print(-1)
	else:
		print(max(0,-ans))

if __name__=="__main__":
	main()

Submission status: Accepted

Solution code:
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, p-c])

d = [float('inf')] * n
d[0] = 0

for i in range(n):
    for a, b, c in abc:
        d[b] = min(d[b], d[a] + c)

for a, b, c in abc:
    if d[b] > d[a] + c:
        d[b] = - float('inf')

for i in range(n):
    for a, b, c in abc:
        d[b] = min(d[b], d[a] + c)

if d[n-1] == - float('inf'):
    print(-1)
else:
    print(max(0, - d[n-1]))

Submission status: Accepted

Solution code:
def main():
    INF = float("inf")

    N, M, P, *ABC = map(int, open(0).read().split())

    F = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    E = [(a - 1, b - 1, P - c) for a, b, c in zip(*[iter(ABC)] * 3)]

    for a, b, c in E:
        F[a].append(b)
        B[b].append(a)

    def reachable(E, a):
        S = {a}
        stack = [a]
        while stack:
            s = stack.pop()
            for v in E[s]:
                if v not in S:
                    stack.append(v)
                    S.add(v)
        return S

    ok = reachable(F, 0) & reachable(B, N - 1)

    E = [(a, b, c) for a, b, c in E if a in ok and b in ok]

    D = [INF] * N
    D[0] = 0

    def bellman_ford(N):
        for _ in range(N):
            update = False
            for a, b, c in E:
                if D[b] > D[a] + c:
                    D[b] = D[a] + c
                    update = True
            if not update:
                return False
        return True

    print(-1 if bellman_ford(N + 1) else max(-D[-1], 0))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    INF = float("inf")

    N, M, P, *ABC = map(int, open(0).read().split())

    F = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    E = [(a - 1, b - 1, P - c) for a, b, c in zip(*[iter(ABC)] * 3)]

    for a, b, c in E:
        F[a].append(b)
        B[b].append(a)

    S = {0}
    stack = [0]
    while stack:
        s = stack.pop()
        for v in F[s]:
            if v not in S:
                stack.append(v)
                S.add(v)

    T = {N - 1}
    stack = [N - 1]
    while stack:
        s = stack.pop()
        for v in B[s]:
            if v not in T:
                stack.append(v)
                T.add(v)

    ok = S & T

    E = [(a, b, c) for a, b, c in E if a in ok and b in ok]

    D = [INF] * N
    D[0] = 0

    def bellman_ford(N):
        for _ in range(N):
            update = False
            for a, b, c in E:
                if D[b] > D[a] + c:
                    D[b] = D[a] + c
                    update = True
            if not update:
                return False
        return True

    print(-1 if bellman_ford(N + 1) else max(-D[-1], 0))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    INF = float("inf")

    N, M, P, *ABC = map(int, open(0).read().split())

    F = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    E = [(a - 1, b - 1, P - c) for a, b, c in zip(*[iter(ABC)] * 3)]

    for a, b, c in E:
        F[a].append(b)
        B[b].append(a)

    S = {0}
    stack = [0]
    while stack:
        s = stack.pop()
        for v in F[s]:
            if v not in S:
                stack.append(v)
                S.add(v)

    T = {N - 1}
    stack = [N - 1]
    while stack:
        s = stack.pop()
        for v in B[s]:
            if v not in T:
                stack.append(v)
                T.add(v)

    ok = S & T

    E = [(a, b, c) for a, b, c in E if a in ok and b in ok]

    D = [INF] * N
    D[0] = 0

    def bellman_ford(N):
        for _ in range(N):
            update = False
            for a, b, c in E:
                if D[b] > D[a] + c:
                    D[b] = D[a] + c
                    update = True
            if not update:
                return False
        return True

    bellman_ford(N)

    print(-1 if bellman_ford(1) else max(-D[-1], 0))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, m, p = map(int, input().split())
lst = [list(map(int, input().split())) for _ in range(m)]
 
for i in range(m):
    lst[i][2] = - (lst[i][2] - p)

d = [10**100] * (n+1)
d[1] = 0
rep = 0
 
while True:
    update = False
    for edge in lst:
        a,b,c = edge
        if d[a] != 10**100 and d[b] > d[a]+ c:
            if rep >= n:
                d[b] = -10**100
            else:
                d[b] = d[a] + c
            update = True
    if not update:
        break
    rep += 1
    if rep > 2*n:
        break

if d[n] <= - 10**100:
    print(-1)
elif -d[n] < 0:
    print(0)
else:
    print(-d[n])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from itertools import *
INF = float('inf')

def bellmanford(edges, s, t, se):
    N = len(edges)
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        update = False
        for v in range(N):
            if v not in se or dist[v] == INF:
                continue
            for u, c in edges[v]:
                if u not in se:
                    continue
                d = dist[v] + c
                if d < dist[u]:
                    dist[u] = d
                    update = True
        if update == False:
            return max(0, -dist[t])
    else:
        return -1

N, M, P = map(int, input().split())
es = [[] for i in range(N)]
es_r = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    es[a-1].append((b-1, P-c))
    es_r[b-1].append(a-1)
reachable1 = [False] * N
def dfs(v):
    if reachable1[v]: return
    reachable1[v] = True
    for u, c in es[v]:
        dfs(u)
reachable2 = [False] * N
def rdfs(v):
    if reachable2[v]: return
    reachable2[v] = True
    for u in es_r[v]:
        rdfs(u)
dfs(0)
rdfs(N-1)
se = set()
for i in range(N):
    if reachable1[i] and reachable2[i]:
        se.add(i)
print(bellmanford(es, 0, N-1, se))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from itertools import *
INF = float('inf')

def bellmanford(edges, s, t, se):
    N = len(edges)
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        update = False
        for v in range(N):
            if v in se and dist[v] == INF:
                continue
            for u, c in edges[v]:
                if u not in se:
                    continue
                d = dist[v] + c
                if d < dist[u]:
                    dist[u] = d
                    update = True
        if update == False:
            return max(0, -dist[t])
    else:
        return -1

N, M, P = map(int, input().split())
es = [[] for i in range(N)]
es_r = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    es[a-1].append((b-1, P-c))
    es_r[b-1].append(a-1)
reachable1 = [False] * N
def dfs(v):
    if reachable1[v]: return
    reachable1[v] = True
    for u, c in es[v]:
        dfs(u)
reachable2 = [False] * N
def rdfs(v):
    if reachable2[v]: return
    reachable2[v] = True
    for u in es_r[v]:
        rdfs(u)
dfs(0)
rdfs(N-1)
se = set()
for i in range(N):
    if reachable1[i] and reachable2[i]:
        se.add(i)
print(bellmanford(es, 0, N-1, se))

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

def belman(egdes, N, start, end):
    INF = int(1e10)
    cost = [INF] * N
    cost[start] = 0
    fin = False
    count = 0
    while True:
        no_change = True
        for edge in egdes:
            from_, to_, d = edge
            tmp = cost[from_] + d
            if cost[to_] > tmp:
                no_change = False
                cost[to_] = tmp
        count += 1
        if no_change:
            fin = True
            break
        elif count > N+1:
            break
    
    if fin:
        return max(0, -cost[end])
    else:
        return -1

def bfs(link, N, start):
    q = deque()
    check = [False] * N
    q.append(start)
    check[start] = True
    used = {start}
    while len(q) > 0:
        node = q.popleft()
        for next_ in link[node]:
            if not check[next_]:
                check[next_] = True
                q.append(next_)
                used.add(next_)
    return used
        

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

    link = [[] for i in range(N)]
    rlink = [[] for i in range(N)]
    edges = []

    for i in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        link[a].append(b)
        rlink[b].append(a)
        edges.append((a, b, -(c-P)))
    
    use_nodes = bfs(link, N, 0) & bfs(rlink, N, N-1)
    use_edges = [(a, b, c) for a, b, c in edges if a in use_nodes and b in use_nodes]
    print(belman(use_edges, N, 0, N-1))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

def main():
    N, M, P = mis()
    
    to = [[] for _ in range(N)]
    ot = [[] for _ in range(N)]
    edges = []

    for i in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        c = -(c-P)
        #
        to[a].append(b)
        ot[b].append(a)
        edges.append((a,b,c))

    reachableFrom0 = set()
    reachableToN = set()

    # dfs
    reachableFrom0.add(0)
    nodes = [0]
    while nodes:
        node = nodes.pop()
        for i in to[node]:
            if i not in reachableFrom0:
                nodes.append(i)
                reachableFrom0.add(i)

    #rdfs
    reachableToN.add(N-1)
    nodes = [N-1]
    while nodes:
        node = nodes.pop()
        for i in ot[node]:
            if i not in reachableToN:
                nodes.append(i)
                reachableToN.add(i)


    ok = reachableFrom0 & reachableToN

    edges = tuple((a, b, c) for a, b, c in edges if a in ok and b in ok)

    V = [float('inf')] * N
    V[0] = 0

    def bf(n):
        for _ in range(n):
            upd = False
            for a, b, c in edges:
                if V[b] > V[a] + c:
                    V[b] = V[a] + c
                    upd = True
            if not upd:
                return False
        return True

    bf(N)

    if not bf(1):
        print(max(-V[-1], 0))
    else:
        print(-1)

main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
INF = float('inf')


def BFord(n,es):
    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n*2):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
        if v == n-1:
            prev = v_cost[:]
    v_cost = [-INF if prev[idx]!=v_cost[idx] else v_cost[idx] for idx in range(n)]
    return v_cost
    

def main():
    n, m, p = map(int, input().split())
    es = []
    for _ in range(m):
        e = list(map(int, input().split()))
        es.append([e[0]-1, e[1]-1, - e[2] + p])

    v_cost = BFord(n,es)

    if v_cost[-1] == -INF:
        return -1

    return max(0, -v_cost[-1])


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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)

n, m, p = map(int, input().split())
routes =[]
bt = [[] for _ in range(n+1)]

for i in range(m):
    a, b, c = map(int, sys.stdin.readline().split())
    routes.append([a, b, -1 * (c - p)])
    bt[b].append(a)

enable = set()
enable.add(n)
for i in range(n):
    for j in range(1, n+1):
        if j in enable:
            for k in bt[j]:
                if not k in enable:
                    enable.add(k)

inf = float('inf')
costs = [inf for _ in range(n+1)]
costs[1] = 0
error = False
for i in range(n):
    for route in routes:
        if route[1] in enable and costs[route[0]] + route[2] < costs[route[1]]:
            costs[route[1]] = costs[route[0]] + route[2]
            if i == n-1:
                error = True
                break
if error == True:
    print(-1)
else:
    print(max(0, -1 * costs[n]))

Submission status: Accepted

Solution code:
from collections import deque
import math

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  # rev_edge
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)   

def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  #負辺があるケースでの、スタートからゴールへの最短路を求めるアルゴ。
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): #頂点の個数の分だけ回る
        updated = False
        for u,v,c in dist: #辺の個数の分だけ回る
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    #収束しない場合は負閉路があるため無限に小さくできる。
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)     
    
use = bfs(edge1, 0) & bfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

Submission status: Accepted

Solution code:
from collections import deque
import math
    
def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  #負辺があるケースでの、スタートからゴールへの最短路を求めるアルゴ。
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): #頂点の個数の分だけ回る
        updated = False
        for u,v,c in dist: #辺の個数の分だけ回る
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    #収束しない場合は負閉路があるため無限に小さくできる。
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)    
        

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  # rev_edge
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)    
    
use = bfs(edge1, 0) & bfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

Submission status: Accepted

Solution code:
from collections import deque
import math
    
def dfs(edges, s):
    stack = deque([s])
    used  = {s}
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y not in used:
                used.add(y)
                stack.append(y)
    return used


def bfs(edges, s):
    queue = deque([s])
    used  = {s}
    while queue:
        x = queue.popleft()
        for y in edges[x]:
            if y in used:
                continue
            used.add(y)
            queue.append(y)
    return used
    

def bellman(dist):  #負辺があるケースでの、スタートからゴールへの最短路を求めるアルゴ。
    cost = [float("inf")] * n
    cost[0] = 0
    for _ in range(n): #頂点の個数の分だけ回る
        updated = False
        for u,v,c in dist: #辺の個数の分だけ回る
            if cost[u] + c < cost[v]:
                cost[v] = cost[u] + c
                updated = True                
    #収束しない場合は負閉路があるため無限に小さくできる。
    if updated==True:
        return -1
    else:
        return max(0, cost[n-1]*-1)    
        

n,m,p = map(int, input().split())
dist  = []
edge1 = [[] for _ in range(n)]
edge2 = [[] for _ in range(n)]  # rev_edge
for _ in range(m):
    u,v,c = map(int, input().split())
    u -= 1
    v -= 1
    dist.append((u,v,(c-p)*-1))
    edge1[u].append(v)
    edge2[v].append(u)    
    
use = dfs(edge1, 0) & dfs(edge2, n-1)
dist2 = [(a,b,c) for a,b,c in dist if a in use and b in use]
print(bellman(dist2))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

ok = [False for i in range(2505)]
def Bellmanford(edges, n, s):
    d = [float("inf") for i in range(n)]
    d[s] = 0


    for i in range(n):
        for x, y, z in edges:
            if not ok[x] or not ok[y]:#0からn-1へ到達できない点は無視
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if i == n - 1:
                    print(-1)
                    exit()
    print(max(0, -d[n - 1]))


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

    to = [[] for i in range(n + 1)]
    rto = [[] for i in range(n + 1)]
    e = []
    for i in range(m):
        a, b, c = map(int, input().split())
        to[a - 1].append(b - 1)
        rto[b - 1].append(a - 1)
        e.append((a - 1, b - 1, p - c))

    #0 から n-1にたどり着けるか調べる
    can_reach_to = [False for i in range(n+1)]
    can_reach_rto = [False for i in range(n+1)]
    def todfs(i):
        if can_reach_to[i]:
            return 0
        can_reach_to[i] = True
        for v in to[i]:
            todfs(v)
    def rtodfs(i):
        if can_reach_rto[i]:
            return 0
        can_reach_rto[i] = True
        for v in rto[i]:
            rtodfs(v)
    todfs(0)
    rtodfs(n-1)
    for i in range(n):
        ok[i] = (can_reach_to[i] & can_reach_rto[i])

    d = Bellmanford(e, n, 0)


if __name__ == '__main__':
    main()