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: Runtime Error

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

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

def main():    
    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)]
    
    x,y=(BELLMANFORD(1,d,n,p))
    
    if y[n]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# ABC 137 E    E. Coins Respawn

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



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

def main():
    
    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)]
    
    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: Runtime Error

Solution code:
from collections import *
d=defaultdict(list)
n,m=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):
    cost       = {node:-1e18 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.items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c:
                    cost[nex]=cost[now]+c
                    preference[nex]=now
 
    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:
                    cost[nex]=cost[now]+c
                    preference[nex]=now
                    negative[now-1]=1
 
    return cost,negative

x,y=(BELLMANFORD(1,d))
#print(x,y)
if y[n-1]==1:
    print("inf")
else:
    print(x[n])

Submission status: Runtime Error

Solution code:
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: Runtime Error

Solution code:
N,M,P=map(int,input().split())
lst=[[0,0,0] for _ in range(M)]
for i in range(M):
  lst[i]=list(map(int,input().split()))
  lst[i][2]=-lst[i][2]+P
inf=float('inf')
dist=[inf]*N
start=1
dist[start-1]=0

def find_edge(v1,lst):
  tmp=[]
  for i in range(M):
    if lst[i][0]==v1:
      tmp.append(i)
  edges=[[] for _ in range(len(tmp))]
  for j in range(len(tmp)):
    edges[j]=lst[tmp[j]]      
  return edges

def BellmanFord(N,dist):
  for i in range(N):
    for edge in find_edge(i,lst):
      if len(edge)==0:
        pass
      else:
        if dist[edge[1]-1]>dist[i-1]+edge[2]:
          dist[edge[1]-1]=dist[i-1]+edge[2]
          if i==N-1:
            return -1
  return dist

if BellmanFord(N,dist)!=-1:
  ans=-1*BellmanFord(N,dist)[-1]
  if ans>0:
    print(ans)
  else:
    print(0)
else:
  print(-1)

Submission status: Runtime Error

Solution code:
class BellmanFord():
    class Edge():
        def __init__(self, _from, _to, _cost):
            self.from_ = _from
            self.to = _to
            self.cost = _cost

    def __init__(self):
        self.edges = []  # 辺
        self.v_set = set()  # 頂点の集合

    @property
    def E(self):
        return len(self.edges)

    @property
    def V(self):
        return len(self.v_set)

    def add(self, _from, _to, _cost):
        self.edges.append(self.Edge(_from, _to, _cost))
        self.v_set.add(_from)
        self.v_set.add(_to)

    def shortest_path(self, s):
        d = [float("inf")] * self.V
        d[s] = 0

        while True:
            do_update = False
            for i in range(self.E):
                e = self.edges[i]
                if d[e.from_] != float("inf") and d[e.to] > d[e.from_] + e.cost:
                    d[e.to] = d[e.from_] + e.cost
                    do_update = True

            if not do_update: break

        return d

    def exist_negative_loop(self):
        d = [0] * self.V
        for i in range(self.V):
            for j in range(self.E):
                e = self.edges[j]
                if d[e.to] > d[e.from_] + e.cost:
                    d[e.to] = d[e.from_] + e.cost
                    if i == self.V - 1: return True
        return False

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

v = [0] * n
v[0] = 1
def bfs(x, depth):
    #print(x, depth, e[x])
    if depth >= n:
        return 1
    if x == n-1:
        return 0
    temp = 1
    for y in e[x]:
        #print(y)
        if v[y] == 1 or x == y:
            continue
        #print(x, y)
        ret = bfs(y, depth + 1)
        if ret == 0:
            v[y] = 1
            temp = 0
    return temp

bfs(0, 0)
x = 1
for i in range(n):
    if v[i] == 1:
        v[i] = x
        x += 1

bf = BellmanFord()
for a, b, c in abc:
    if v[a]!= 0 and v[b] != 0:
        bf.add(v[a]-1, v[b]-1, c)

if bf.exist_negative_loop():
    print(-1)
    exit()
else:
    print(max(0, - bf.shortest_path(0)[-1]))

Submission status: Runtime Error

Solution code:
class BellmanFord():
    class Edge():
        def __init__(self, _from, _to, _cost):
            self.from_ = _from
            self.to = _to
            self.cost = _cost

    def __init__(self):
        self.edges = []  # 辺
        self.v_set = set()  # 頂点の集合

    @property
    def E(self):
        return len(self.edges)

    @property
    def V(self):
        return len(self.v_set)

    def add(self, _from, _to, _cost):
        self.edges.append(self.Edge(_from, _to, _cost))
        self.v_set.add(_from)
        self.v_set.add(_to)

    def shortest_path(self, s):
        d = [float("inf")] * self.V
        d[s] = 0

        while True:
            do_update = False
            for i in range(self.E):
                e = self.edges[i]
                if d[e.from_] != float("inf") and d[e.to] > d[e.from_] + e.cost:
                    d[e.to] = d[e.from_] + e.cost
                    do_update = True

            if not do_update: break

        return d

    def exist_negative_loop(self):
        d = [0] * self.V
        for i in range(self.V):
            for j in range(self.E):
                e = self.edges[j]
                if d[e.to] > d[e.from_] + e.cost:
                    d[e.to] = d[e.from_] + e.cost
                    if i == self.V - 1: return True
        return False

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

v = [0] * n
v[0] = 1
def bfs(x, depth):
    #print(x, depth, e[x])
    if depth >= n:
        return 1
    if x == n-1:
        return 0
    temp = 1
    for y in e[x]:
        #print(y)
        if v[y] == 1 or x == y:
            continue
        #print(x, y)
        ret = bfs(y, depth + 1)
        if ret == 0:
            v[y] = 1
            temp = 0
    return temp

bfs(0, 0)

bf = BellmanFord()
for a, b, c in abc:
    if v[a] * v[b] == 1:
        bf.add(a, b, c)
    else:
        bf.add(a, b, float('inf'))

if bf.exist_negative_loop():
    print(-1)
    exit()
else:
    print(max(0, - bf.shortest_path(0)[-1]))

Submission status: Runtime Error

Solution code:
from scipy.sparse.csgraph import dijkstra, bellman_ford, csgraph_from_dense, NegativeCycleError

INF = float("inf")

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

ABC = [(a - 1, b - 1, c)for a, b, c in zip(*[iter(ABC)] * 3)]

D = [[0] * N for _ in range(N)]
for a, b, c in ABC:
    D[a][b] = c

T = dijkstra(D)

E = [[0] * N for _ in range(N)]
for a, b, c in ABC:
    if T[0][a] < INF and T[b][N - 1] < INF:
        E[a][b] = P - c

try:
    G = bellman_ford(csgraph_from_dense(E))
    ans = max(0, -int(G[0][N - 1]))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Runtime Error

Solution code:
from scipy.sparse.csgraph import dijkstra, bellman_ford, csgraph_from_dense, NegativeCycleError
from itertools import permutations

INF = float("inf")

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

D = [INF] * (N + 1)
D[1] = 0

loop = False
for i in range(2 * N + 100):
    for a, b, c in zip(*[iter(ABC)] * 3):
        d = D[a] + P - c
        if D[b] > d:
            D[b] = d
            if b == N and i > N:
                loop = True

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

Submission status: Runtime Error

Solution code:
from scipy.sparse.csgraph import dijkstra, bellman_ford, csgraph_from_dense, NegativeCycleError
from itertools import permutations

INF = float("inf")

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

D = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    D[a - 1][b - 1] = c

T = dijkstra(D)

E = [[0] * N for _ in range(N)]
for a, b, c in zip(*[iter(ABC)] * 3):
    if T[b - 1][N - 1] < INF:
        E[a - 1][b - 1] = P - c

try:
    G = bellman_ford(csgraph_from_dense(E), indices=0)
    ans = max(0, -int(G[N - 1]))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Runtime Error

Solution code:
from scipy.sparse.csgraph import dijkstra, bellman_ford, csgraph_from_dense, NegativeCycleError
from itertools import permutations

INF = float("inf")

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

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

T = dijkstra(D)
for a, b in permutations(range(N), 2):
    if T[b][N - 1] == INF:
        E[a][b] = 0

try:
    G = bellman_ford(csgraph_from_dense(E), indices=0)
    ans = max(0, -int(G[N - 1]))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Runtime Error

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 loop:
        break
    if rep > 2*n:
        break


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

Submission status: Runtime Error

Solution code:
def dfs(i, V, E):
    if V[i]:
        return

    V[i] = True
    for e in E[i]:
        d = e[1]
        dfs(d, V, E)


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

E = [[] for i in range(N)]
RE = [[] for i in range(N)]

for i in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((a-1, b-1, P-c))
    RE[b-1].append((b-1, a-1, P-c))

V0 = [False for i in range(N)]
dfs(0, V0, E)

VN = [False for i in range(N)]
dfs(N-1, VN, RE)

ok = [V0[i] and VN[i] for i in range(N)]

V = [float("inf") for i in range(N)]
V[0] = 0

negative_loop = False
upd = True
step = 0
while upd:
    upd = False
    for el in E:
        for e in el:
            s = e[0]
            d = e[1]
            w = e[2]

            if not ok[s] or not ok[d]:
                continue

            newD = V[s] + w
            if newD < V[d]:
                upd = True
                V[d] = newD

    step = step + 1
    if step > N:
        negative_loop = True
        break

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

Submission status: Runtime Error

Solution code:
def dfs(i, V, E):
    if V[i]:
        return

    V[i] = True
    for e in E[i]:
        d = e[1]
        dfs(d, V, E)


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

E = [[] for i in range(N)]
RE = [[] for i in range(N)]

for i in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((a-1, b-1, P-c))
    RE[b-1].append((b-1, a-1, P-c))

V0 = [False for i in range(N)]
dfs(0, V0, E)

VN = [False for i in range(N)]
dfs(N-1, VN, RE)

E_refined = []
for el in E:
    for e in el:
        s = e[0]
        d = e[1]

        if V0[s] and VN[s] and V0[d] and VN[d]:
            E_refined.append(e)

V = [float("inf") for i in range(N)]
V[0] = 0

for i in range(N):
    for e in E_refined:
        s = e[0]
        d = e[1]
        w = e[2]

        if V[s] + w < V[d]:
            V[d] = V[s] + w

negative_loop = False

for e in E_refined:
    s = e[0]
    d = e[1]
    w = e[2]

    if V[s] + w < V[d]:
        negative_loop = True
        break

if negative_loop:
    print(-1)
elif V[N-1] > 0:
    print(0)
else:
    print(-V[N-1])

Submission status: Runtime Error

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

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 = [False] * N
reachableToN = [False] * N

def dfs(n):
    if reachableFrom0[n]:
        return
    reachableFrom0[n] = True
    for i in to[n]:
        dfs(i)

def rdfs(n):
    if reachableToN[n]:
        return
    reachableToN[n] = True
    for i in ot[n]:
        rdfs(i)

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]

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

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

def bf_step():
    for a, b, c in edges:
        V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Runtime Error

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

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 = [False] * N
reachableToN = [False] * N

def dfs(n):
    if reachableFrom0[n]:
        return
    reachableFrom0[n] = True
    for i in to[n]:
        dfs(i)

def rdfs(n):
    if reachableToN[n]:
        return
    reachableToN[n] = True
    for i in ot[n]:
        rdfs(i)

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]

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

V = [10**10] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        if ok[a] and ok[b]:
            V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Runtime Error

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

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 = [False] * N
reachableToN = [False] * N

def dfs(n):
    if reachableFrom0[n]:
        return
    reachableFrom0[n] = True
    for i in to[n]:
        dfs(i)

def rdfs(n):
    if reachableToN[n]:
        return
    reachableToN[n] = True
    for i in ot[n]:
        rdfs(i)

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]


V = [10**10] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        if ok[a] and ok[b]:
            V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Runtime Error

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

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 = [False] * N
reachableToN = [False] * N

def dfs(n):
    if reachableFrom0[n]:
        return
    reachableFrom0[n] = True
    for i in to[n]:
        dfs(i)

def rdfs(n):
    if reachableToN[n]:
        return
    reachableToN[n] = True
    for i in ot[n]:
        rdfs(i)

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]


V = [10**10] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        if ok[a] and ok[b]:
            V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Runtime Error

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 = [math.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: Runtime Error

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 = [math.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) & 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: Runtime Error

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)] 
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 = [math.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) & 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: Runtime Error

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 = [math.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) & 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: Runtime Error

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 = [math.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 = 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: Runtime Error

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 = [math.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) & 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))