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: Wrong Answer

Solution code:
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
G = [{} for _ in range(N)]
for abc in ABC:
    a, b, c = abc
    a -= 1
    b -= 1
    G[a][b] = c


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [[-INF, 0]] * V
    D[i] = [0, 0]
    for _ in range(V + 1):
        update = update_goal = False
        for fr in range(V):
            for to in G[fr]:
                if D[fr][0] != -INF and D[to][0] - D[to][1] * P < D[fr][0] + G[
                        fr][to] - (D[fr][1] + 1) * P:
                    D[to] = [D[fr][0] + G[fr][to], D[fr][1] + 1]
                    update = True
                    if to == N - 1:
                        update_goal = True
        if not update:
            return D[N - 1]
    if not update_goal:
        return D[N - 1]
    return False


ans = bellman_ford(N, G, 0)
if ans is False:
    print(-1)
else:
    print(max(0, ans[0] - ans[1] * P))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] -= p

start = 0
goal = n - 1

# dist: cost from start
dist = [-float("inf")] * n
dist[start] = 0

# cut edges
reachable = [False] * n
reachable[goal] = True
d = deque()
d.append(goal)
reachable[goal] = True
while len(d) > 0:
    x = d.popleft()
    for edge in edges:
        if edge[1] == x and reachable[edge[0]] == False and x != start:
            d.append(edge[0])
            reachable[edge[0]] = True

cant_reach = []
for i in range(n):
    if reachable[i] == False:
        cant_reach.append(i)

for edge in edges:
    if edge[0] in cant_reach or edge[1] in cant_reach:
        edge[2] = -99999999

# bellman-ford

# relaxing
negative_cycle = False
for i in range(n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != -float("inf") and dist[edge[1]] < dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
            if i == n - 1:
                negative_cycle = True

print(-1 if negative_cycle else max(dist[n - 1], 0))

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


vertices = []
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    if v1 & v2:
        vertices.append(i)

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N * 2):
    for v in vertices:
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in vertices:
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for v in vertices:
    updated |= prev[v] != dist[v]

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

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


use = [False] * N
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    use[i] = v1 & v2

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N * 2):
    for v in range(N):
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in range(N):
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for p, d, u in zip(prev, dist, use):
    updated |= u and p != d

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

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        if ret[v]:
            continue
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


use = [False] * N
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    use[i] = v1 & v2

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for v in range(N):
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in range(N):
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for p, d, u in zip(prev, dist, use):
    updated |= u and p != d

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

Submission status: Wrong Answer

Solution code:
# https://takeg.hatenadiary.jp/entry/2019/05/31/005630
class BellmanFord():
    """ ベルマンフォード法
    重み付き有向グラフにおける単一始点最短路アルゴリズム
    
    * 使用条件
        - DAG（有向グラフで閉路を持たない）であること
        - 負のコストがあってもOK
    
    * 負の閉路がある場合、最短路は求まらないが、負の閉路の検出はできる
    
    * 計算量はO(V*E)
    """
    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()  # 頂点の集合
        self.V_max = 0
    
    @property
    def E(self):
        """ 辺数 """
        return len(self.edges)
    
    @property
    def V(self):
        """ 頂点数 """
        return self.V_max+1
    
    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.edges.append(self.Edge(_from, _to, _cost))
        self.v_set.add(_from)
        self.v_set.add(_to)
        self.V_max = max([self.V_max, _from, _to])
    
    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す 
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短路
        """
        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, get_array=False):
        """ 負の閉路が存在するか否か
        Returns:
            (bool): 負の閉路が存在する(True)/しない(False)

        get_arrayがTrueなら，負の平路候補を抜き出せる．
        有向グラフの場合，エッジの方向を逆にした場合の結果と要素ごとのandをとることで，
        負の平路を求められる．
        """
        if get_array:
            negloops = [False for i in range(self.V)]
        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
                    # n回目にも更新があるなら負の閉路が存在する
                    if i == self.V-1:
                        if get_array:
                            negloops[e.to] = True
                            negloops[e.from_] = True
                        else:
                            return True

        if get_array:
            return negloops
        else:
            return False


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

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

costs = {}

bf = BellmanFord()
bf2 = BellmanFord()
for i in range(M):
    a,b,c = map(int,input().split())
    c = -(c-P)
    bf.add(a,b,c)
    bf2.add(b,a,c)

lp = bf.exist_negative_loop(get_array=True)
# print(lp)
lp2 = bf2.exist_negative_loop(get_array=True)
# print(lp2)

bf3 = BellmanFord()
p = True
for e in bf.edges:
    a,b,c = e.from_,e.to,e.cost
    if (lp[a] and lp2[a]) or (lp[b] and lp2[b]):
        pass
    else:
        p = False
        bf3.add(a,b,c)

if p:
    print(-1)
    exit()

sp = bf3.shortest_path(1)

print(max(-min(sp),0))

Submission status: Wrong Answer

Solution code:
import sys
from pprint import pprint

def solve(n, m, p, e):
  for i in range(m):
    e[i] = (e[i][0], e[i][1], -1 * e[i][2] + p)
  # pprint(e)

  dist = BellmanFord(e, n, 1)
  # pprint(dist)
  if dist == -1:
    print -1
  else:
    print max(0, -1 * dist[n-1])


def BellmanFord(edges, num_v, source):
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0

  for i in range(num_v):
    for edge in edges:
      if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        #if i==num_v-1: return -1
        if i==num_v-1 and edge[1] == num_v: return -1
  
  # pprint(dist)
  # repeat = num_v / len(edges) + 1
  # for _ in xrange(repeat):
  #   for edge in edges:
  #     # pprint(edge)
  #     # print dist[edge[1]-1], dist[edge[0]-1] + edge[2]
  #     if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
  #       if edge[1] == num_v:
  #         # pprint(dist)
  #         return -1

  return dist


if __name__ == '__main__':

    n, m, p = map(int, sys.stdin.readline().strip().split(" "))
    e = []
    for _ in range(m):
        e.append(map(int, sys.stdin.readline().strip().split(" ")))
    solve(n, m, p, e)

Submission status: Wrong Answer

Solution code:
"""
Bellman-Ford
始点と終点が決められているとき、
経由する閉路のみを確認する必要がある。
"""
def Bellman_Ford2(g,start,goal):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    a0 = float("inf")
    for i in range(2*n):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if dist[to] <= dist[v] + cost: continue
                if i < n:
                    dist[to] = dist[v] + cost
                else:
                    dist[to] = -float("inf")
                updated = True
        if not updated: break
    if dist[goal] == -float("inf"): return None, False
#    if negative[-1]: return None, False
    return dist, True
 

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

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

dist, TF = Bellman_Ford2(g,0,-1)

if TF: print(-dist[-1])
else: print("inf")

Submission status: Wrong Answer

Solution code:
import sys
from pprint import pprint

def solve(n, m, p, e):
  for i in range(m):
    e[i] = (e[i][0], e[i][1], -1 * e[i][2] + p)
  # pprint(e)

  dist = BellmanFord(e, n, 1)
  # pprint(dist)
  if dist == -1:
    print -1
  else:
    print max(0, -1 * dist[n-1])


def BellmanFord(edges, num_v, source):
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0

  for i in range(num_v):
    for edge in edges:
      if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        #if i==num_v-1: return -1

  
  # pprint(dist)
  repeat = num_v / len(edges) + 1
  for _ in xrange(repeat):
    for edge in edges:
      # pprint(edge)
      # print dist[edge[1]-1], dist[edge[0]-1] + edge[2]
      if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        if edge[1] == num_v:
          # pprint(dist)
          return -1

  return dist


if __name__ == '__main__':

    n, m, p = map(int, sys.stdin.readline().strip().split(" "))
    e = []
    for _ in range(m):
        e.append(map(int, sys.stdin.readline().strip().split(" ")))
    solve(n, m, p, e)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bellman_ford(N: int, edges: list, src: int) -> list:
    """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

    # 頂点[ある始点からの最短距離] (経路自体を知りたい時はここに前の頂点も持たせる)
    res = [INF] * N
    res[src] = 0
    # 各辺によるコストの置き換えを頂点数N-1回繰り返す
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    # 負の閉路(いくらでもコストを減らせてしまう場所)がないかチェックする
    for src, dest, cost in edges:
        if res[dest] > res[src] + cost:
            if dest == N-1:
                # 頂点Nがそれに該当していたら空リストを返却
                return []
    # 問題なければ頂点リストを返却
    return res

N, M, P = MAP()
edges = []
for i in range(M):
    a, b, c = MAP()
    # Pは最後に請求される、だけど、ようは動く度に支払ってると思ってもいい
    edges.append((a-1, b-1, -c+P))

res = bellman_ford(N, edges, 0)
if not len(res):
    print(-1)
else:
    # 正負を直す
    ans = -res[N-1]
    # スコアがマイナスなら0
    print(max(0, ans))

Submission status: Wrong Answer

Solution code:
import sys
from pprint import pprint

def solve(n, m, p, e):
  for i in range(m):
    e[i] = (e[i][0], e[i][1], -1 * e[i][2] + p)
  # pprint(e)

  dist = BellmanFord(e, n, 1)
  # pprint(dist)
  if dist == -1:
    print -1
  else:
    print max(0, -1 * dist[n-1])


def BellmanFord(edges, num_v, source):
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0

  for i in range(num_v):
    for edge in edges:
      if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        #if i==num_v-1: return -1

  
  # pprint(dist)
  for edge in edges:
    # pprint(edge)
    # print dist[edge[1]-1], dist[edge[0]-1] + edge[2]
    if dist[edge[0]-1] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
      if edge[1] == num_v:
        # pprint(dist)
        return -1

  return dist


if __name__ == '__main__':

    n, m, p = map(int, sys.stdin.readline().strip().split(" "))
    e = []
    for _ in range(m):
        e.append(map(int, sys.stdin.readline().strip().split(" ")))
    solve(n, m, p, e)

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))

# bellman-ford
dist = [INF] * N
dist[0] = 0
prev = INF
updated = True
for _ in range(N + 1):
    for v in range(N):
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])
    updated = prev != dist[N - 1]
    prev = dist[N - 1]
if updated or dist[N - 1] == INF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))

# bellman-ford
dist = [IINF] * N
dist[0] = 0
prev = IINF
updated = True
for _ in range(N + 1):
    for v in range(N):
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])
    updated = prev != dist[N - 1]
    prev = dist[N - 1]
if updated or dist[N - 1] == IINF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]
A,B,C = zip(*ABC)
C = [P-c for c in C]

graph = csr_matrix((C,(A,B)),(N+1,N+1))
add = csr_matrix(([1],([N],[1])),(N+1,N+1))
_,comp = connected_components(graph + add, connection='strong')
select = (comp == comp[1])
graph = graph[select,:][:,select]

try:
    dist = bellman_ford(graph, indices=[0])
    answer = int((.5-dist[0,-1]) // 1)
    if answer < 0:
        answer = 0
except:
    answer = -1
print(answer)

Submission status: Wrong Answer

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

from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]
A,B,C = zip(*ABC)
C = [P-c for c in C]

graph = csr_matrix((C,(A,B)),(N+1,N+1))
graph2 = csr_matrix(([1]*(M+1),(A+(N,),B+(1,))),(N+1,N+1))
_,comp = connected_components(graph2, connection='strong')
select = (comp == comp[1])
graph = graph[select,:][:,select]

try:
    dist = bellman_ford(graph, indices=[0])
    answer = int((.5-dist[0,-1]) // 1)
    if answer < 0:
        answer = 0
except:
    answer = -1
print(answer)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 20 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    ABC = [(a, b, P - c) for a, b, c in ABC]

    table = [MAX] * (N + 1)
    table[1] = 0
    for _ in range(N):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                table[b] = table[a] + c
    if -table[N] < 0:
        print(0)
        return
    score = -table[N]
    for a, b, c in ABC:
        if table[a] == MAX:
            continue
        if table[a] + c < table[b]:
            table[b] = table[a] + c
    if -table[N] != score:
        print(-1)
        return
    print(score)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]
A,B,C = zip(*ABC)
C = [P-c for c in C]

graph = csr_matrix((C,(A,B)),(N+1,N+1))
graph2 = csr_matrix(([1]*(M+1),(A+(N,),B+(1,))),(N+1,N+1))
_,comp = connected_components(graph2, connection='strong')
select = (comp == comp[1])
graph = graph[select,:][:,select]

try:
    dist = bellman_ford(graph, indices=[0])
    answer = int(round(-dist[0,-1]))
    if answer < 0:
        answer = 0
except:
    answer = -1
print(answer)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 20 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    ABC = [(a, b, P - c) for a, b, c in ABC]

    table = [MAX] * (N + 1)
    table[1] = 0
    for _ in range(N):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                table[b] = table[a] + c
    if -table[N] < 0:
        print(0)
        return
    score = -table[N]
    for a, b, c in ABC:
        if table[a] == MAX:
            continue
        if table[a] + c < table[b]:
            table[b] = table[a] + c
    if -table[N] != score:
        print(-1)
        return
    print(-table[N])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]
A,B,C = zip(*ABC)
C = [P-c for c in C]

graph = csr_matrix((C,(A,B)),(N+1,N+1))
graph2 = csr_matrix(([1]*(M+1),(A+(N,),B+(1,))),(N+1,N+1))
_,comp = connected_components(graph2, connection='strong')
select = (comp == comp[1])
graph = graph[select,:][:,select]

try:
    dist = bellman_ford(graph, indices=[0])
    answer = int(.5-dist[0,-1])
    if answer < 0:
        answer = 0
except:
    answer = -1
print(answer)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    ABC = [(a, b, P - c) for a, b, c in ABC]

    table = [MAX] * (N + 1)
    table[1] = 0
    for _ in range(N):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                table[b] = table[a] + c
    if -table[N] < 0:
        print(0)
        return
    score = -table[N]
    for a, b, c in ABC:
        if table[a] == MAX:
            continue
        if table[a] + c < table[b]:
            table[b] = table[a] + c
    if -table[N] != score:
        print(-1)
        return
    print(-table[N])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))

# bellman-ford
dist = [IINF] * N
dist[0] = 0
prev = IINF
updated = True
for _ in range(N + 1):
    for v in range(N):
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])
    updated = prev != dist[N - 1]
    prev = dist[N - 1]
if updated:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Submission status: Wrong Answer

Solution code:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    graph = defaultdict(list)
    coins = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a-1].append(b-1)
        coins[(a-1,b-1)] = -(c - p)

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    # bellman-ford
    for loop in range(2):
        for i in range(n):
            for next_node in graph[i]:
                scores[next_node] = min(scores[next_node], scores[i] + coins[(i, next_node)])

        if loop == 0:
            ans = scores[-1]

    print(-1 if ans != scores[-1] or ans == inf else -ans)  # n 回移動した時点よりスコアが良くなってたら無限に上げられる


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

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

for i in range(1, N + 1):
    G[i] = dict()
    G_rev[i] = dict()

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = P - C
    G_rev[B][A] = 1

reachable_N = [0] * (N + 1)
reachable_N[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable_N[q] == 0:
            reachable_N[q] = 1
            queue.append(q)

reachable_1 = [0] * (N + 1)
reachable_1[1] = 1
queue = deque([1])

while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if reachable_1[q] == 0:
            reachable_1[q] = 1
            queue.append(q)

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [None] * (N + 1)
dist[1] = 0
cnt = 0

success = True
for i in range(N + 10000):
    for p in range(1, N + 1):
        if reachable[p] == 0 or dist[p] is None:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[q] is None or dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                if i > N:
                    success = False


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