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:
impoty sys
sys.setrecursionlimit(10**9)

N,M,P = map(int,input().split())
edges = []
to = [[] for i in range(N)]
rto = [[] for i in range(N)]
for i in range(M) :
    u,v,cost = map(int,input().split())
    u -= 1
    v -= 1
    cost -= P
    cost *= -1
    edges.append([u,v,cost])
    to[u].append(v)
    rto[v].append(u)

canVisitFromS = [False]*N
canVisitFromG = [False]*N

def dfs(u) :
    if canVisitFromS[u] : return
    canVisitFromS[u] = True
    for v in to[u] :
        dfs(v)

def rdfs(v) :
    if canVisitFromG[v] : return
    canVisitFromG[v] = True
    for u in rto[v] :
        rdfs(u)

dfs(0)
rdfs(N-1)

OK = [canVisitFromS[i]*canVisitFromG[i] for i in range(N)]

dist = [float("inf")]*N
dist[0] = 0

ans = 0
step = 0
update = True
while update :
    update = False
    for i in range(M) :
        u,v,cost = edges[i]
        if OK[u]*OK[v] == 0 : continue
        if dist[v] > dist[u] + cost :
            dist[v] = dist[u] + cost
            update = True
    step += 1
    if step > N :
        ans = -1
        break

if ans != -1 :
    ans = max(0, dist[N-1]*(-1))

print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(4100000)

from collections import defaultdict

def bellman_ford(graph, m, n, source):
    # Step 1. Prepare distance and predecessor for each node
    distance, predecessor = dict(), dict()
    for node in graph:
        distance[node], predecessor[node] = float('inf'), None
    distance[source] = 0

    # Step 2. Relax the edges
    for _ in range(len(graph) - 1):
        for node in graph:
            for neighbor in graph[node]:
                # If the distance between the node and the neighbor is lower than the current, store it
                if distance[neighbor] > distance[node] + graph[node][neighbor]:
                    distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor], node
    temp = distance[n]
    for node in graph:
        for neighbor in graph[node]:
            # If the distance between the node and the neighbor is lower than the current, store it
            if distance[neighbor] > distance[node] + graph[node][neighbor] + m:
                distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor] + m, node
    if temp != distance[n]:
        return "Loop"

    else:
        return -distance[n]
    # Step 3. Check for negative weight cycles
    # for node in graph:
    #     for neighbor in graph[node]:
    #         assert distance[neighbor] <= distance[node] + graph[node][neighbor], "Negative weight cycle."

    # return distance, predecessor

n,m,p = [int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for _ in range(n)]
graph = {}
for i in range(1,n+1):
    graph[i] = {}
for start, end, weight in a:
    graph[start][end] = p-weight

# print(graph)
distance = bellman_ford(graph, p, n, source=1)
if distance == "Loop":
    print(-1)
else:
    print(max(0,distance))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(4100000)

from collections import defaultdict

def bellman_ford(graph, m, n, source):
    # Step 1. Prepare distance and predecessor for each node
    distance, predecessor = dict(), dict()
    for node in graph:
        distance[node], predecessor[node] = float('inf'), None
    distance[source] = 0

    # Step 2. Relax the edges
    for _ in range(len(graph) - 1):
        for node in graph:
            for neighbor in graph[node]:
                # If the distance between the node and the neighbor is lower than the current, store it
                if distance[neighbor] > distance[node] + graph[node][neighbor] + m:
                    distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor] + m, node
    temp = distance[n]
    for node in graph:
        for neighbor in graph[node]:
            # If the distance between the node and the neighbor is lower than the current, store it
            if distance[neighbor] > distance[node] + graph[node][neighbor] + m:
                distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor] + m, node
    if temp != distance[n]:
        return -1
    elif temp > 0:
        return 0
    else:
        return -distance[n]
    # Step 3. Check for negative weight cycles
    # for node in graph:
    #     for neighbor in graph[node]:
    #         assert distance[neighbor] <= distance[node] + graph[node][neighbor], "Negative weight cycle."

    # return distance, predecessor

n,m,p = [int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for _ in range(n)]
graph = {}
for i in range(1,n+1):
    graph[i] = {}
for start, end, weight in a:
    graph[start][end] = -weight

# print(graph)
distance = bellman_ford(graph, p, n, source=1)
print(distance)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(4100000)

from collections import defaultdict

def bellman_ford(graph, m, n, source):
    # Step 1. Prepare distance and predecessor for each node
    distance, predecessor = dict(), dict()
    for node in graph:
        distance[node], predecessor[node] = float('inf'), None
    distance[source] = 0

    # Step 2. Relax the edges
    for _ in range(len(graph) - 1):
        for node in graph:
            for neighbor in graph[node]:
                # If the distance between the node and the neighbor is lower than the current, store it
                if distance[neighbor] > distance[node] + graph[node][neighbor] + m:
                    distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor] + m, node
    temp = distance[n]
    for node in graph:
        for neighbor in graph[node]:
            # If the distance between the node and the neighbor is lower than the current, store it
            if distance[neighbor] > distance[node] + graph[node][neighbor] + m:
                distance[neighbor], predecessor[neighbor] = distance[node] + graph[node][neighbor] + m, node
    if temp != distance[n]:
        return -1
    elif temp > 0:
        return 0
    else:
        return -distance[n]
    # Step 3. Check for negative weight cycles
    # for node in graph:
    #     for neighbor in graph[node]:
    #         assert distance[neighbor] <= distance[node] + graph[node][neighbor], "Negative weight cycle."

    # return distance, predecessor

n,m,p = [int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for _ in range(n)]
graph = {}
for i in range(1,n+1):
    graph[i] = {}
for start, end, weight in a:
    graph[start][end] = -weight

# print(graph)
distance = bellman_ford(graph, p, n, source=1)
print(distance)

Submission status: Runtime Error

Solution code:
# -*- coding:utf-8 -*-
# /usr/bin/python3

import json
from collections import defaultdict
INF = float('inf')

def f(s, graph, path=[]):
  path = path + [s]
  cost = sum([graph[path[i]][path[i+1]]['cost'] for i in range(len(path)-1)])
  for t in graph[s]:
    if t == 'score':
      continue
    if t in path:
      if cost + graph[s][t]['cost'] < 0:
        return True
      continue
    if f(t, graph, path):
      return True
  return False



def g(s, graph, path, necessary_nodes):
  path = path + [s]
  for t in graph[s]:
    if t in path:
      continue
    if t in necessary_nodes:
      necessary_nodes |= set(path)
      continue
    g(t, graph, path, necessary_nodes)




def main():
  n, m, p = map(int, input().strip().split(' '))
  graph = defaultdict(dict) 
  for _ in range(m):
    a, b, c =  map(int, input().strip().split(' '))
    graph[b][a] = {'cost':-(c-p)}
    graph[b]['score'] = INF
    graph[a]['score'] = INF

  necessary_nodes = {1}
  g(n, graph, [], necessary_nodes)
  for s in set(graph.keys()) - necessary_nodes:
    if s != 'score':
      del graph[s]

  for s in graph.keys():
    for t in set(graph[s].keys()) - necessary_nodes:
      if s != 'score' and t != 'score':
        del graph[s][t]


  if f(n, graph):
    print(-1)
    return

  starts = [n]
  graph[n]['score'] = 0
  for s in starts:
    for t in graph[s]:
      if t == 'score':
        continue
      if graph[t]['score'] == INF:
        starts += [t]
      if graph[t]['score'] > graph[s]['score'] + graph[s][t]['cost']:
        graph[t]['score'] = graph[s]['score'] + graph[s][t]['cost']

  print(max(-graph[1]['score'], 0))

if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
# -*- coding:utf-8 -*-
# /usr/bin/python3

import json
from collections import defaultdict
INF = float('inf')

def f(s, graph, path=[]):
  path = path + [s]
  cost = sum([graph[path[i]][path[i+1]]['cost'] for i in range(len(path)-1)])
  for t in graph[s]:
    if t == 'score':
      continue
    if t in path:
      if cost + graph[s][t]['cost'] < 0:
        return True
    if f(t, graph, path):
      return True
  return False



def g(s, graph, path, necessary_nodes):
  path = path + [s]
  for t in graph[s]:
    if t in path:
      continue
    if t in necessary_nodes:
      necessary_nodes |= set(path)
    g(t, graph, path, necessary_nodes)




def main():
  n, m, p = map(int, input().strip().split(' '))
  graph = defaultdict(dict) 
  for _ in range(m):
    a, b, c =  map(int, input().strip().split(' '))
    graph[b][a] = {'cost':-(c-p)}
    graph[b]['score'] = INF
    graph[a]['score'] = INF

  necessary_nodes = {1}
  g(n, graph, [], necessary_nodes)
  for s in set(graph.keys()) - necessary_nodes:
    if s != 'score':
      del graph[s]

  for s in graph.keys():
    for t in set(graph[s].keys()) - necessary_nodes:
      if s != 'score' and t != 'score':
        del graph[s][t]


  if f(n, graph):
    print(-1)
    return

  starts = [n]
  graph[n]['score'] = 0
  for s in starts:
    for t in graph[s]:
      if t == 'score':
        continue
      if graph[t]['score'] == INF:
        starts += [t]
      if graph[t]['score'] > graph[s]['score'] + graph[s][t]['cost']:
        graph[t]['score'] = graph[s]['score'] + graph[s][t]['cost']

  print(max(-graph[1]['score'], 0))

if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
# -*- coding:utf-8 -*-
# /usr/bin/python3

import json
from collections import defaultdict
INF = float('inf')

def f(s, graph, path=[]):
  path = path + [s]
  cost = sum([graph[path[i]][path[i+1]]['cost'] for i in range(len(path)-1)])
  for t in graph[s]:
    if t == 'score':
      continue
    if t in path:
      if cost + graph[s][t]['cost'] < 0:
        return True
    if f(t, graph, path):
      return True
  return False



def g(s, graph, path, necessary_nodes):
  path = path + [s]
  for t in graph[s]:
    if t in path:
      continue
    if t == 1:
      necessary_nodes += (path + [t])
    g(t, graph, path, necessary_nodes)




def main():
  n, m, p = map(int, input().strip().split(' '))
  graph = defaultdict(dict) 
  for _ in range(m):
    a, b, c =  map(int, input().strip().split(' '))
    graph[b][a] = {'cost':-(c-p)}
    graph[b]['score'] = INF
    graph[a]['score'] = INF

  necessary_nodes = []
  g(n, graph, [], necessary_nodes)
  for s in set(graph.keys()) - set(necessary_nodes):
    if s != 'score':
      del graph[s]

  for s in graph.keys():
    for t in set(graph[s].keys()) - set(necessary_nodes):
      if s != 'score' and t != 'score':
        del graph[s][t]


  if f(n, graph):
    print(-1)
    return

  starts = [n]
  graph[n]['score'] = 0
  for s in starts:
    for t in graph[s]:
      if t == 'score':
        continue
      if graph[t]['score'] == INF:
        starts += [t]
      if graph[t]['score'] > graph[s]['score'] + graph[s][t]['cost']:
        graph[t]['score'] = graph[s]['score'] + graph[s][t]['cost']

  print(max(-graph[1]['score'], 0))

if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
inputs = [int(x) for x in input().split()]
n, m, p = inputs[0], inputs[1], inputs[2]
inputs = [[int(x) for x in input().split()] for _ in range(m)]
graphs, scores = {}, {}
for x, y, c in inputs:
  if y in graphs.keys():
    graphs[y].append([x, c - p])
  else:
    graphs[y] = [[x, c - p]]
    scores[y] = [None, False]
for k, v in graphs.items():
  graphs[k] = sorted(v, key=lambda x: x[0])

has_loop_in_the_path = False
scores[1] = [0, has_loop_in_the_path]

for goal in range(2, n+1):
  for start, score in graphs[goal]:
    # 1につながっていない
    if scores[start][0] is None:
      continue
    has_loop_in_the_path = (goal == start) or scores[start][1]
    total = scores[start][0] + score
    if (scores[goal][0] is None) or (total > scores[goal][0]):
      scores[goal] = [total, has_loop_in_the_path]

# print(scores)
if scores[n][0] < 0:
  print(0)
elif scores[n][1] == True:
  print(-1)
else:
  print(scores[n][0])

Submission status: Runtime Error

Solution code:
inputs = [int(x) for x in input().split()]
n, m, p = inputs[0], inputs[1], inputs[2]
inputs = [[int(x) for x in input().split()] for _ in range(m)]
graphs, scores = {}, {}
for x, y, c in inputs:
  if y in graphs.keys():
    graphs[y].append([x, c - p])
  else:
    graphs[y] = [[x, c - p]]
    scores[y] = None
for k, v in graphs.items():
  graphs[k] = sorted(v, key=lambda x: x[0])

scores[1] = 0

for goal in range(2, n+1):
  for start, score in graphs[goal]:
    if scores[start] is None:
      continue
    total = scores[start] + score
    if (scores[goal] is None) or (total > scores[goal]):
      scores[goal] = total

print(scores[n] if scores[n] > 0 else 0)

Submission status: Runtime Error

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([ r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Runtime Error

Solution code:
"""
AtCoder
    :author: vierbein
"""
from __future__ import absolute_import, division, print_function

# import itertools as it
from collections import *
import sys
from heapq import *

INFTY = 10000000000


def bellman_ford(vertices, edge_weight, source):
    """
    Bellman-Ford algorithm for shortest path
    O(V E)
    """
    d = {vertex: (0 if vertex == source else INFTY) for vertex in vertices}
    prev = {v: None for v in vertices}

    num_vertices = len(vertices)
    for _ in range(num_vertices):
        for (u, v), weight in edge_weight.items():
            alt = d[u] + weight
            if d[v] > alt:
                d[v] = alt
                prev[v] = u

    for (u, v), weight in edge_weight.items():
        if u in prev and v in prev and d[u] + weight < d[v]:
            raise ValueError("Graph contains a negative-weight cycle")

    return d, prev


def pp(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


def dfs_reachables(adj_list, source):

    def _dfs(u, seen):
        seen.add(u)
        for v in adj_list[u]:
            if v not in seen:
               seen = _dfs(v, seen)
        return seen

    reachable_vertices = set()
    reachable_vertices = _dfs(source, reachable_vertices)
    return reachable_vertices


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

    adj_list = [[] for _ in range(N)]
    back_adj_list = [[] for _ in range(N)]
    edge_weight = dict()
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1   # 0-based index
        b -= 1   # 0-based index

        adj_list[a].append(b)
        back_adj_list[b].append(a)
        edge_weight[(a, b)] = -(c - P)

    forward_reachables = dfs_reachables(adj_list, 0)
    backward_reachables = dfs_reachables(back_adj_list, N-1)
    vertices = forward_reachables & backward_reachables
    edge_weight = {(u,v): w for (u, v), w in edge_weight.items() if u in vertices and v in vertices}

    try:
        d, _ = bellman_ford(vertices, edge_weight, 0)
        print(max(0, -d[N - 1]))
    except ValueError:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
"""
AtCoder
    :author: vierbein
"""
from __future__ import absolute_import, division, print_function

# import itertools as it
from collections import *
import sys
from heapq import *

INFTY = 10000000000


def bellman_ford(vertices, adj_list, edge_weight, source):
    """
    Bellman-Ford algorithm for shortest path
    O(V E)
    """
    d = {vertex: (0 if vertex == source else INFTY) for vertex in vertices}
    prev = {v: None for v in vertices}

    num_vertices = len(vertices)
    for _ in range(num_vertices):
        for (u, v), weight in edge_weight.items():
            if (u not in prev) or (v not in prev):
                continue
            alt = d[u] + weight
            if d[v] > alt:
                d[v] = alt
                prev[v] = u

    for (u, v), weight in edge_weight.items():
        if u in prev and v in prev and d[u] + weight < d[v]:
            raise ValueError("Graph contains a negative-weight cycle")

    return d, prev


def pp(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


def dfs_reachables(vertices, adj_list, source):

    def _dfs(u, seen):
        seen.add(u)
        for v in adj_list[u]:
            if v not in seen:
               seen = _dfs(v, seen)
        return seen

    reachable_vertices = set()
    reachable_vertices = _dfs(source, reachable_vertices)
    return reachable_vertices


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

    adj_list = [[] for _ in range(N)]
    back_adj_list = [[] for _ in range(N)]
    edge_weight = dict()
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1   # 0-based index
        b -= 1   # 0-based index

        adj_list[a].append(b)
        back_adj_list[b].append(a)
        edge_weight[(a, b)] = -(c - P)

    forward_reachables = dfs_reachables(range(N), adj_list, 0)
    backward_reachables = dfs_reachables(range(N), back_adj_list, N-1)
    vertices = forward_reachables & backward_reachables

    try:
        d, _ = bellman_ford(vertices, adj_list, edge_weight, 0)
        print(max(0, -d[N - 1]))
    except ValueError:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c - p


def bellman_ford(vst, graph, node_num):
    costs = [-float('inf')] * n
    costs[0] = 0
    update_points = []
    ans = 0
    v_nows = set([vst])
    for _ in range(n):
        v_changeds = set()
        for v_from in v_nows:
            for v_to, cost in enumerate(graph[v_from]):
                if cost == -float('inf'):
                    continue
                if costs[v_from] + cost > costs[v_to]:
                    costs[v_to] = costs[v_from] + cost
                    v_changeds.add(v_to)



    if not v_changeds:
        return costs


    que = deque()
    que.append(start)
    while que:
        edges = que.popleft()
        for to, costs in enumerate(graph[edges]):
            if costs != -float('inf'):
                graph[edges] = -float('inf')
                que.append(to)
    return costs



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

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
edges = []
L = [[] for i in range(N)]
utov = [[] for i in range(N)]
vtou = [[] for i in range(N)]

for i in range(M) :
    u,v,cost = map(int,input().split())
    u -= 1
    v -= 1
    cost -= P
    cost *= -1
    edges.append([u,v,cost])
    utov[u].append(v)
    vtou[v].append(u)

reachableFromS = [False]*N
reachableFromG = [False]*N

def dfs(u) :
    if reachableFromS[u] :
        return
    reachableFromS[u] = True
    for v in utov[u] :
        dfs(v)

def dfs2(v) :
    if reachableFromG[v] :
        return
    reachableFromG[v] = True
    for u in vtou[v] :
        dfs2(u)

dfs(0)
dfs2(N-1)

OK = [reachableFromS[i] * reachableFromG[i] for i in range(N)]

dist = [float("inf")]*N
dist[0] = 0

ans = 0
step = 0
update = True

while update :
    update = False
    for i in range(M) :
        u,v,cost = edges[i]
        if OK[u] * OK[v] == 0 :
            continue
        if dist[v] > dist[u] + cost :
            dist[v] = dist[u] + cost
            update = True
    
    step += 1
    if step > N :
        ans = -1
        break

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

Submission status: Runtime Error

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]
    for e in d:
        s, t = e
        if V[s] == None:
            continue
        if V[t] == None:
            V[t] = V[s] + d[e]
            continue
        if V[s] + d[e] < V[t]:
            V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None or W[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = "a"
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == "a" or V[t] == a:
                V[t] == "a"
                continue
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] == "a":
        print(-1)
    else:
        print(max(-W[-1],0))
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c



def dfs(graph, start, goal):
    que = deque()
    que.append(start)
    reached = set()
    while que:
        edges = que.popleft()
        for to, cost in enumerate(graph[edges]):
            if cost != -float('inf') and to not in reached:
                que.append(to)
                reached.add(to)
    if goal in reached:
        return True
    else:
        return False


dist = [-float('inf')] * n
dist[0] = 0
ans = -float('inf')
flag = True
for time in range(1, n+1):
    if not flag:
        break
    new_dist = [-float('inf')] * n
    flag = False
    for before, edges in enumerate(graph):
        for to, cost in enumerate(edges):
            if dist[before] + cost > new_dist[to]:
                new_dist[to] = dist[before] + cost
                flag = True
                if time == n:
                    update_points = []
                    update_points.append(to)
    dist = new_dist
    ans = max(0, new_dist[n-1] - time * p, ans)



flag = False
for i in update_points:
    if dfs(graph, i, n-1):
        print(-1)
        break
else:
    print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
edgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  edgedict[f-1][t-1] = 1

# Nに到達できない頂点を削除
visited = [False] * N
unreach = set()
def dfs(f):
  visited[f] = True
  for t in edgedict[f].keys():
    if t == N-1:
      return True
    ret = False
    if not visited[t]:
      ret = ret or dfs(t)
  if not ret:
    unreach.add(f)
  return ret
dfs(0)

# ベルマンフォード
INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(M):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and t not in unreach and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Submission status: Runtime Error

Solution code:
# 頂点sから到達する頂点の集合
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use

# ベルマンフォード法
def bellman_ford(v, s, t, e):
    INF = 10**18
    # コストをINFで初期化
    d = [INF] * v
    # 開始頂点は0
    d[s] = 0
    # 負の閉路が無ければ更新はV-1回までで終わる
    for _ in range(v):
        f = False
        for a, b, c in e:
            if d[a]=INF:continue
            # aまでのコスト+辺abのコストがbまでのコストより小さければ更新
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        # 更新が無ければbreak
        if not f:break
    else:
        # V回目まで更新があったら負の閉路がある
        return -1
    return max(-d[t], 0)

def main():
    import sys
    input = sys.stdin.readline
    n, m, p = map(int, input().split())
    edge = [[] for _ in range(n)]
    edge_rev = [[] for _ in range(n)]
    e = []
    for _ in range(m):
        a, b, c = map(int, input().split())
        edge[a-1].append(b-1)
        # 頂点Nからdfsするため辺の向きを逆にする
        edge_rev[b-1].append(a-1)
        e.append((a-1, b-1, p-c))
    """
    # 頂点1と頂点Nのどちらからも到達できる頂点の集合
    use = dfs(edge, 0) & dfs(edge_rev, n-1)
    # fromとtoがどちらもuseに含まれる辺のみ使う
    # そうすることで負の閉路を検出した場合答えは必ず-1になる
    """
    # ↑って思ってたけど頂点Nから到達できるか見るだけでいいらしいよ(えー)
    use = dfs(edge_rev, n-1)
    e = [(a, b, c) for a, b, c in e if a in use and b in use]
    print(bellman_ford(n, 0, n-1, e))   
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
INF = 10**10
 
def dfs(edge, visited, n):
    if visited[n]:
        return
    visited[n] = True
    for to, _ in edge[n]:
        dfs(edge, visited, to)

def bellman_ford(edge, mask):
    dist = [INF] * n
    dist[0] = 0

    for _ in range(n):
        update = False
        for i, es in enumerate(edge):
            if not mask[i]:
                continue
            for to, cost in es:
                if not mask[to]:
                    continue
                if dist[i] != INF and dist[i] + cost < dist[to]:
                    dist[to] = dist[i] + cost
                    update = True
        if not update:
            return dist
    else:
        # Found minus loops
        return -INF

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    redge = [[] for _ in range(n)]
    for i in range(m):
        a, b, c = [int(item) for item in input().split()]
        a -= 1; b -= 1; c -= p
        c *= -1
        edge[a].append((b, c))
        redge[b].append((a, c)) 
    
    visited = [False] * n
    dfs(edge, visited, 0)
    rvisited = [False] * n
    dfs(redge, rvisited, n-1)
    mask = [forward and backward for forward, backward in zip(visited, rvisited)]
    dist = bellman_ford(edge, mask)
    if dist == -INF:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Runtime Error

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for r, c in zip(row, col)])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
    
    1/0 #REチェック
except csgraph._shortest_path.NegativeCycleError:
    print(-1)