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=map(int,input().split())
g=[[] for _ in range(n)]
for _ in range(m):
    a,b,l=map(int,input().split())
    g[a-1].append([b-1,p-l])

def bellman_ford(g,n):
    INF = 10**10
    res = [INF for _ in range(n)]
    res[0] = 0
    for _ in range(n-1):
        for i in range(n):
            if res[i] != INF:
                for sa,sb in g[i]:
                    res[sa] = min(res[sa],res[i]+sb)
    ret = res[-1]
    for _ in range(n-1):
        for i in range(n):
            if res[i] != INF:
                for sa,sb in g[i]:
                    res[sa] = min(res[sa],res[i]+sb)
    if ret != res[-1]:return False
    else: return ret

res = bellman_ford(g,n)
if type(res) == bool:
    print(-1)
elif res > 0:
    print(0)
else:
    print(res * -1)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
g=[[] for _ in range(n)]
for _ in range(m):
    a,b,l=map(int,input().split())
    g[a-1].append([b-1,l-p])

def bellman_ford(g,n):
    INF = -(10**10)
    res = [INF for _ in range(n)]
    res[0] = 0
    for _ in range(n-1):
        for i in range(n):
            if res[i] != INF:
                for sa,sb in g[i]:
                    res[sa] = max(res[sa],res[i]+sb)
    ret = res[-1]
    for _ in range(n-1):
        for i in range(n):
            if res[i] != INF:
                for sa,sb in g[i]:
                    res[sa] = max(res[sa],res[i]+sb)
    if ret != res[-1]:return False
    else: return ret

res = bellman_ford(g,n)
if type(res) == bool:
    print(-1)
elif res < 0:
    print(0)
else:
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
N, M, P, *D = map(int, open(0).read().split())
dp = [-N*P for _ in range(N+1)]
isway = [False for _ in range(N+1)]
dp[1] = 0
prev = [-1 for _ in range(N+1)]
isway[1] = True
for i in range(N):
  for A, B, _ in zip(*[iter(D)]*3):
    if isway[A]:
      isway[B] = True
for i in range(2*N):
  for A, B, C in zip(*[iter(D)]*3):
    if dp[A] + C - P > dp[B] and isway[A] and isway[B]:
      dp[B] = dp[A] + C - P
      prev[B] = A
is_loop = False
v = N
for i in range(N):
  if v == 1:
    break
  else:
    v = prev[v]
# print(dp, file=sys.stderr)
print(max(0, dp[N]) if v == 1 else -1)

Submission status: Wrong Answer

Solution code:
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 edge[0] != 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: dist[edge[1]-1] = -inf
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
  r = dist[-1]
  if r == -inf: r=-1
  if r > 0: r = 0
  if r < 0: r=-r
  return r

import sys
input = sys.stdin.readline
N, M, P = map(int, input().split())
edges = []
for i in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, P-C])
print(BellmanFord(edges, N, 1))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
    return d[t]
  def path_findloop(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    first = 0
    for i in range(1, self.n + 2):
      for (u, v, c) in self.edges:
        if u != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if i > N: d[v] = -float("inf")
      if i == self.n:
        first = d[t] + 0
      elif i == self.n + 1:
        if first != d[t]:
          return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path_findloop(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
    return d[t]
  def path_findloop(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    first = 0
    for i in range(1, self.n + 2):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if i > N: d[t] = -float("inf")
      if i == self.n:
        first = d[t] + 0
      elif i == self.n + 1:
        if first != d[t]:
          return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path_findloop(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
    return d[t]
  def path_findloop(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    first = 0
    for i in range(1, self.n * 2 + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
      if i == self.n:
        first = d[t] + 0
      elif i == self.n * 2:
        if first != d[t]:
          return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path_findloop(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n * 2 + 1):
      updated = 0
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if v == t: updated = 1
      if i >= self.n * 2 and updated:
        return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 2):
      updated = 0
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if v == t: updated = 1
      if i > self.n and updated:
        return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path(1, N)

if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if i == self.n and (v == self.n):
            return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
    a,b,c = map(int, input().split())
    E[a-1].append((b-1, -c+P))
    
def BellmanFord(E, N, source):
    inf = 10**20
    d = [inf for _ in range(N)]
    d[source] = 0
    for i in range(2*N):
        for j in range(N):
            e = E[j]
            if len(e) == 0:
                continue
            for edge in e:
                if d[edge[0]] > d[j]+edge[1]:
                    d[edge[0]] = d[j]+edge[1]
                    if i >= N-1 and edge[0] == N-1:
                        return -1
    return d

ans = BellmanFord(E, N, 0)
if ans == -1:
    print(ans)
else:
    print(max(-ans[-1], 0))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
    a,b,c = map(int, input().split())
    E[a-1].append((b-1, -c+P))
    
def BellmanFord(E, N, source):
    inf = 10**20
    d = [inf for _ in range(N)]
    d[source] = 0
    for i in range(N):
        for j in range(N):
            e = E[j]
            if len(e) == 0:
                continue
            for edge in e:
                if d[edge[0]] > d[j]+edge[1]:
                    d[edge[0]] = d[j]+edge[1]
                    if i == N-1 and edge[0] == N-1:
                        return -1
    return d

ans = BellmanFord(E, N, 0)
if ans == -1:
    print(ans)
else:
    print(max(-ans[-1], 0))

Submission status: Wrong Answer

Solution code:
def bellman_ford(edges, num_v, start, end):
    """
    ベルマンフォード法
    :param edges: (from, to, cost)のリスト
    :param num_v: 頂点の数
    :param start: 始点
    :param end: 終点
    :return: 最小コスト
    """
    inf = float("inf")
    dist = [inf] * num_v
    dist[start - 1] = 0
    ans = -1

    for i in range(num_v * 2):
        for edge in edges:
            if dist[edge[1] - 1] > dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i > num_v:
                    dist[edge[1] - 1] = inf
        if i == num_v - 1:
            ans = dist[end - 1]
    if dist[-1] != ans or dist[-1] == -inf:
        return -1
    return max(dist[-1], 0)


def p_e():
    N, M, P = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a, b, c - P))
    ans = bellman_ford(edges, N, 1, N)
    print(ans)


if __name__ == '__main__':
    p_e()

Submission status: Wrong Answer

Solution code:
def bellman_ford(edges, num_v, start, end):
    """
    ベルマンフォード法
    :param edges: (from, to, cost)のリスト
    :param num_v: 頂点の数
    :param start: 始点
    :param end: 終点
    :return: 最小コスト
    """
    inf = float("inf")
    dist = [inf] * num_v
    dist[start - 1] = 0
    ans = -1

    for i in range(num_v * 2):
        for edge in edges:
            if dist[edge[1] - 1] > dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i > num_v:
                    dist[edge[1] - 1] = inf
        if i == num_v - 1:
            ans = dist[end - 1]
    if dist[-1] != ans or dist[-1] == -inf:
        return -1
    return max(-dist[-1], 0)


def p_e():
    N, M, P = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a, b, P - c))
    ans = bellman_ford(edges, N, 1, N)
    print(ans)


if __name__ == '__main__':
    p_e()

Submission status: Wrong Answer

Solution code:
def bellman_ford(edges, num_v, start, end):
    """
    ベルマンフォード法
    :param edges: (from, to, cost)のリスト
    :param num_v: 頂点の数
    :param start: 始点
    :param end: 終点
    :return: 最小コスト
    """
    inf = float("inf")
    dist = [inf] * num_v
    dist[start - 1] = 0
    ans = -1

    for i in range(num_v):
        for edge in edges:
            if 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 and ans != dist[end - 1]:
                    return "not"
        if i == num_v - 2:
            ans = dist[end - 1]

    return ans


def p_e():
    N, M, P = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a, b, P - c))
    ans = bellman_ford(edges, N, 1, N)
    print(max(0, -ans) if ans != "not" else -1)


if __name__ == '__main__':
    p_e()

Submission status: Wrong Answer

Solution code:
def bellman_ford(edges, num_v, start, end):
    """
    ベルマンフォード法
    :param edges: (from, to, cost)のリスト
    :param num_v: 頂点の数
    :param start: 始点
    :param end: 終点
    :return: 最小コスト
    """
    inf = float("inf")
    dist = [inf] * num_v
    dist[start - 1] = 0
    ans = -1

    for i in range(num_v):
        for edge in edges:
            if 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 and ans != dist[end - 1]:
                    return -1
        if i == num_v - 2:
            ans = dist[end - 1]

    return ans


def p_e():
    N, M, P = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a, b, P - c))
    ans = bellman_ford(edges, N, 1, N)
    print(max(0, -ans) if ans != -1 else ans)


if __name__ == '__main__':
    p_e()

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M,P=map(int,input().split())
E = [list(map(int, input().split())) for _ in range(M)]
A = [-float("inf")] * (N+1)
A[1] = 0
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
ans = A[N]
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
if ans!=A[N]:
    print(-1)
else:
    print(max(0, ans))

Submission status: Wrong Answer

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

es = []

for i in range(M):
    a,b,c = map(int, input().split())
    es.append((a-1, b-1, c))

INF = float("inf")

d = [INF for _ in range(N)] 
d[0] = 0
"""
頂点Nに向かうまでに関係ない閉路に注意する

無限にコインを拾える場合、
・ある閉路を一周したときの得点と支払いの収支がプラス
・その閉路からゴールまで行ける
である。これがない場合、全てのノードを経由してゴールまで行く（N-1回移動）までにコインの枚数が最大になる
なので、一回ベルマンフォード法をやった後もう一回行って一回目と２回目でゴールまでのコイン枚数に変化があればゴ、
ールに行くまでの道に無限にコインをとれる閉路があるといえる

"""

def solve(start, i):
    for i in range(N):
        for a,b,c, in es:
            if d[a] != INF and d[a] + (-c) + P < d[b]:
                # ２週目と区別する。２週目で更新される部分は-INFとか適当に置いておくと、ゴールまでの影響がわかる
                if i == 0:
                    d[b] = d[a] + (-c) + P
                else:
                    d[b] = -INF
                

                if i == N-1 and b == N-1:
                    return -1


    return d[-1]


first=solve(0,0)
if first == -1:
    print(-1)
else:
    second=solve(0, 1)
    if first == second:
        print(max(-first, 0))
    else:
        print(-1)

Submission status: Wrong Answer

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

es = []

for i in range(M):
    a,b,c = map(int, input().split())
    es.append((a-1, b-1, c))

INF = float("inf")

d = [INF for _ in range(N)] 
d[0] = 0
"""
頂点Nに向かうまでに関係ない閉路に注意する

無限にコインを拾える場合、
・ある閉路を一周したときの得点と支払いの収支がプラス
・その閉路からゴールまで行ける
である。これがない場合、全てのノードを経由してゴールまで行く（N-1回移動）までにコインの枚数が最大になる
なので、一回ベルマンフォード法をやった後もう一回行って一回目と２回目でゴールまでのコイン枚数に変化があればゴ、
ールに行くまでの道に無限にコインをとれる閉路があるといえる

"""

def solve(start):
    for i in range(N):
        for a,b,c, in es:
            if d[a] != INF and d[a] + (-c) + P < d[b]:
                d[b] = d[a] + (-c) + P
                

                if i == N-1 and b == N-1:
                    return -1


    return d[-1]


first=solve(0)
if first == -1:
    print(-1)
else:
    second=solve(0)
    if first == second:
        print(max(-first, 0))
    else:
        print(-1)

Submission status: Wrong Answer

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

es = []

"""
辺を通るたびにP支払う、でよいらしい
"""
for i in range(M):
    a,b,c = map(int, input().split())
    es.append((a-1, b-1, c-P))

INF = float("inf")
d = [INF] * N
d[0] = 0

def solve(start):
    for i in range(N):
        for a,b,c, in es:
            if d[a] != INF and d[a] + (-c) < d[b]:
                d[b] = d[a] + (-c)
                

                if i == N-1 and b == N-1:
                    return -1


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

print(solve(0))

Submission status: Wrong Answer

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

es = []

for i in range(M):
    a,b,c = map(int, input().split())
    es.append((a-1, b-1, c))

INF = float("inf")

d = [[INF, 0] for _ in range(N)] 
d[0][0] = 0

def solve(start):
    for i in range(N):
        for a,b,c, in es:
            if d[a][0] != INF and d[a][0] + (-c) + P < d[b][0]:
                d[b][0] = d[a][0] + (-c) + P
                d[b][1] += 1

                if i == N-1 and b == N-1:
                    return -1


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

print(solve(0))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

# 頂点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

n, m, p = map(int, input().split())
INF = 10**18  
edge = [[] for _ in range(n)]
edge_rev = [[] for _ in range(n)]
e = []  
graph = [[0]*n for _ in range(n)]
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))
use = dfs(edge_rev, n-1)

for a, b, c in e:
  if a in use and b in use:
    graph[a][b] = c

csr = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(csr, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:      
  print(int(max(-(dist[0][-1]),0)))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

N, M, P = map(int, input().split())
INF = 10**18
graph = np.array([[0]*N for _ in range(N)])
negative_V = []
for i in range(M):
  from_V, to_V, c = map(int, input().split())
  if from_V==to_V: # 最終点以外の負閉路はスキップ
    if to_V == N: # 負閉路が最終点だと終わらない為、exit()
      print(-1)
      exit()    
    negative_V.append(from_V-1)
    
  graph[from_V-1][to_V-1] = P-c
negative_V.sort()
for remove in negative_V[::-1]:
  graph = np.delete(np.delete(graph, remove, 0), remove, 1)

csr = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(csr, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:    
  print(int(max(-(dist[0][-1]),0)))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

N, M, P = map(int, input().split())
INF = 10**18
graph = np.array([[0]*N for _ in range(N)])
negative_V = []
for i in range(M):
  from_V, to_V, c = map(int, input().split())
  if from_V==to_V: # 最終点以外の負閉路はスキップ
    if to_V == N: # 負閉路が最終点だと終わらない為、exit()
      print(-1)
      exit()    
    negative_V.append(from_V-1)
    
  graph[from_V-1][to_V-1] = P-c

for remove in negative_V[::-1]:
  graph = np.delete(np.delete(graph, remove, 0), remove, 1)

csr = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(csr, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:    
  print(int(max(-(dist[0][-1]),0)))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

N, M, P = map(int, input().split())
INF = 10**18
graph = np.array([[0]*N for _ in range(N)])
negative_V = []
for i in range(M):
  from_V, to_V, c = map(int, input().split())
  if from_V==to_V: # 最終点以外の負閉路はスキップ
    if to_V == N: # 負閉路が最終点だと終わらない為、exit()
      print(-1)
      exit()    
    negative_V.append(from_V-1)
    
  graph[from_V-1][to_V-1] = P-c

for remove in negative_V[::-1]:
  graph = np.delete(np.delete(graph, remove, 0), remove, 1)

csr = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(csr, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:    
  print(max(-(dist[0][-1]),0))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

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

graph = [[0]*N for _ in range(N)]
negative_cnt = 0
for i in range(M):
  from_V, to_V, c = map(int, input().split())
  if from_V==to_V: # 最終点以外の負閉路はスキップ
    if to_V == N: # 負閉路が最終点だと終わらない為、exit()
      print(-1)
      exit()
    graph[from_V-1][to_V-1] = float('inf')
    continue    
  graph[from_V-1][to_V-1] = P-c
a = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(a, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:    
  print(max(-(dist[0][-1]),0))

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])

def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]

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

graph = [[0]*N for _ in range(N)]
negative_cnt = 0
for i in range(M):
  from_V, to_V, c = map(int, input().split())
  if from_V==to_V: # 最終点以外の負閉路はスキップ
    if to_V == N: # 負閉路が最終点だと終わらない為、exit()
      print(-1)
      exit()    
    continue    
  graph[from_V-1][to_V-1] = P-c
a = csr_matrix(graph) # ndarrayより高速な為、変換

# 負閉路がある場合NegativeErorrを出力
try:
  	# start、goalが決まっているので,'indices=[0]'を指定
    # directed=True:有効グラフ
    dist = bellman_ford(a, indices=[0])
except Exception: # 全ての例外をキャッチ
    print(-1)
else:    
  print(max(-(dist[0][-1]),0))

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
inpl = lambda: list(map(int,input().split()))
INF = 10**12
N, M, P = inpl()
uv = [ set() for _ in range(N) ]
vu = [ set() for _ in range(N) ]
for i in range(M):
    a, b, c = inpl()
    a -= 1
    b -= 1
    uv[a].add((b,c-P))
    vu[b].add((a,c-P))

reachable = [False]*N
pool = deque([0])
while pool:
    n = pool.popleft()
    if reachable[n] == True:
        continue
    else:
        reachable[n] = True
        for k, c in uv[n]:
            pool.append(k)
goalable = [False]*N
pool = deque([N-1])
while pool:
    n = pool.popleft()
    if goalable[n] == True:
        continue
    else:
        goalable[n] = True
        for k, c in vu[n]:
            pool.append(k)

sensible = [reachable[i] and goalable[i] for i in range(N)]
sensible_list = [i for i in range(N) if sensible[i]]
sensible_set = set(sensible_list)
for i in range(N):
    if sensible[i]:
        uv[i] = set({e for e in uv[i] if e[0] in sensible_set})
        vu[i] = set({e for e in vu[i] if e[0] in sensible_set})

state = [0]*N # 0:empty, 1:tree, -1:loop
coin = [-INF]*N
for i in sensible_list:
    if state[i] == 1:
        continue
    coin[i] = 0
    pool = [(i,None,0,0,0)] # (node, parent, enter or exit, coin, get)
    while pool:
        n, p, s, d, c = pool.pop()
        if s == 1:
            state[n] = 1
        elif state[n] == 1:
            pass
        elif state[n] == -1:
            if d+c > coin[n]:
                print(-1)
                exit()
            elif coin[p]+c > coin[n]:
                coin[p] = coin[n]-c
        else: # state[n]==0 : empty
            state[n] = -1
            coin[n] = d
            pool.append((n,p,1,d,c))
            for k, cc in uv[n]:
                pool.append((k,n,0,d+c,cc))

cur = [-INF] * N
cur[0] = 0
ans = -INF
for t in range(N):
    prev = cur
    cur = [
            max(prev[f[0]]+f[1] for f in vu[i])
            if sensible[i] and vu[i] else -INF
        for i in range(N)]
    ans = max(ans,cur[N-1])
print(max(ans,0))