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:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Bellman_Ford(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [mod] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    po = 0
    while po < 2*N + 100:
        update = False
        for p,q,r in es:
        # e: 辺iについて [from,to,cost]
            if d[p] != mod and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
                if (q == n-1 and po > N):
                    d[-1] = None
                    update = False
                    break
        if not update:
            break
        po += 1
    return d

N,M,P = m()

es = []
for _ in range(M):

    x,y,z = map(int,input().split())

    x -= 1
    y -= 1
    es.append([x,y,-z+P])



po = Bellman_Ford(0,N,M,es)
print(-1 if po[-1] == None else -po[-1] if po[-1] <= 0 else 0)

Submission status: Wrong Answer

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。
                     到達不可の場合、値はfloat("inf")
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # 始点の(最短距離, 頂点番号)をヒープに追加する

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する
                e = self.G[v][i]  # vのi個目の隣接辺e
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost  # dの更新
                    heapq.heappush(que, (d[e.to], e.to))  # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush
        return d

N,M,P=map(int,input().split())
edges=[]
test=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    edges.append([a,b,P-c])
    test.add(b-1,a-1,1)

use=set([N-1])
for i in range(0,N-1):
    if test.shortest_path(N-1)[i]!=10**15:
        use.add(i)

useedges=[]
for i in range(0,M):
    a,b,c=edges[i]
    if a-1 in use and b-1 in use:
        useedges.append(edges[i])

import heapq
hen=[[] for i in range(0,N)]
for edge in useedges:
    a,b,c=edge
    hen[a-1].append((b-1,c))
inf=float("inf")
ans=[inf for i in range(N)]
ans[0]=0
q=[0]
heapq.heapify(q)
sub=[]
heapq.heapify(sub)
flag=0
count=0
while q and N>count:
    while q:
        x=heapq.heappop(q)
        for p in hen[x]:
            to,cost=p
            test=ans[x]+cost
            if ans[to]>test:
                ans[to]=test
                heapq.heappush(sub,to)
        if q==[]:
            q=sub
            sub=[]
            heapq.heapify(sub)
            count+=1
            break
if count==N:
    print(-1)
else:
    if ans[N-1]>0:
        print(0)
    else:
        print(-ans[N-1])

Submission status: Wrong Answer

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N*2 + 1):
    update = False
    for j in range(M):
        a, b, c = ABC[j]
        pt = - (c - P)
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i > N-1 and b == N:
                print(-1)
                exit()

    if not update:
        break

#print(POINT)
pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Wrong Answer

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N*2 + 1):
    update = False
    for j in range(M):
        a, b, c = ABC[j]
        pt = - (c - P)
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i > N-1 and b == N:
                print(-1)
                exit()

    if not update:
        break

print(POINT)
pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Wrong Answer

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N+1):
    update = False
    for j in range(M):
        a, b, c = ABC[j]
        pt = - (c - P)
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i == N:
                print(-1)
                exit()

    if not update:
        break

print(POINT)
pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Wrong Answer

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N):
    update = False
    for j in range(M):
        a, b, c = ABC[j]
        pt = P - c
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i == N - 1 and b == N:
                print(-1)
                exit()

    if not update:
        break

pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
# 終了時、T*P枚支払う
graph = []
for _ in range(M):
    a, b, c = lr()
    graph.append((a, b, c))

def bellmanford(N, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(N+N+5):
        for (pre, ne, weight) in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # n回繰り返してもスコアが更新された場合
                if i > N-1 and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(N, 1)
print(answer)

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
# 終了時、T*P枚支払う
graph = []
for _ in range(M):
    a, b, c = lr()
    graph.append((a, b, c))

def bellmanford(N, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(N+5):
        for (pre, ne, weight) in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # n回繰り返してもスコアが更新された場合
                if i > N-1 and ne == N:
                    print(-1); exit()
    return dist[N]

answer = bellmanford(N, 1)
print(max(0, answer))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N,M,P=map(int,input().split())
def f(x):
  x[0]-=1
  x[1]-=1
  x[2]=-(x[2]-P)
  return x
ABC=[f(list(map(int,input().split()))) for i in range(M)]
infinity=10**9
loop=[]


def BellmanFord():
  distance=[0]+[infinity]*(N-1)
  predecessor=[[] for i in range(N)]
  for i in range(N):
    for a,b,c in ABC:
      if distance[b]>distance[a]+c:
        distance[b]=distance[a]+c
        predecessor[b].append(a)
  for a,b,c in ABC:
    if distance[a]+c<distance[b]:
      #print("Graph contains a negative-weight cycle",a,b,c)
      #print(-1)
      #exit(0)
      loop.append(a)
      loop.append(b)
  return distance,predecessor
d,p=BellmanFord()
ans=-min(d[-1],0)
for x in p[-1]:
  if x in loop:
    ans=-1
    break
print(ans)

Submission status: Wrong Answer

Solution code:
#import decimal
#decimal.getcontext().prec==500 Floatの桁数を500まで増やす
#Decimal(c).sqrt() それで平方根を求める
#Decimal(1) / Decimal(7) 1/7
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
import sys
#input = sys.stdin.readline


#N=int(input())
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
for i in range(M):
    ABC[i][2]=-1*(ABC[i][2]-P)

idle_max=10**9
data=[idle_max for i in range(N+1)]
data[1]=0

for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
value=data[N]
for i in range(N):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
if data[N]!=value:
    print(-1)
else:
    print(max(-value,0))

Submission status: Wrong Answer

Solution code:
#import decimal
#decimal.getcontext().prec==500 Floatの桁数を500まで増やす
#Decimal(c).sqrt() それで平方根を求める
#Decimal(1) / Decimal(7) 1/7
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
import sys
#input = sys.stdin.readline


#N=int(input())
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
for i in range(M):
    ABC[i][2]=-1*(ABC[i][2]-P)

idle_max=10**9
data=[idle_max for i in range(N+1)]
data[1]=0

for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
value=data[N]
for i in range(N):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
print(data)
if data[N]!=value:
    print(-1)
else:
    print(max(-value,0))

Submission status: Wrong Answer

Solution code:
#import decimal
#decimal.getcontext().prec==500 Floatの桁数を500まで増やす
#Decimal(c).sqrt() それで平方根を求める
#Decimal(1) / Decimal(7) 1/7
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
import sys
#input = sys.stdin.readline


#N=int(input())
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
for i in range(M):
    ABC[i][2]=-1*(ABC[i][2]-P)

idle_max=10**9
data=[idle_max for i in range(N+1)]
data[1]=0

for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
value=data[N]
for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
print(data)
if data[N]!=value:
    print(-1)
else:
    print(max(-value,0))

Submission status: Wrong Answer

Solution code:
import copy
n,m,p=map(int,input().split())
g=[]
for i in range(m):
  a,b,c=map(int,input().split())
  g+=[[a-1,b-1,c-p]]
l=[1]+[0]*(n-1)
t=[0]*n
for i in range(2*m):
  s=copy.deepcopy(t)
  for j in range(m):
    if l[g[j][0]]:
      t[g[j][1]]=max(t[g[j][1]],t[g[j][0]]+g[j][2])
      l[g[j][1]]=1
if s[-1]==t[-1]:
  print(max(s[-1],0))
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10 ** 19
    dist = [-INF] * (N+1) # 1-indexed
    dist[s] = 0
    for i in range(N+N+10):
        for pre, ne, weight in graph:
            x = dist[pre] + weight - P
            if dist[pre] != -INF and x > dist[ne]:
                dist[ne] = x
                # N回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10 ** 15
    dist = [-INF] * (N+1) # 1-indexed
    dist[s] = 0
    for i in range(N+N+10):
        for pre, ne, weight in graph:
            x = dist[pre] + weight - P
            if dist[pre] != -INF and x > dist[ne]:
                dist[ne] = x
                # N回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    dist = [10**19] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10 ** 17
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10 ** 12
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = 10 ** 12
    dist = [INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] - weight + P < dist[ne]:
                dist[ne] = dist[pre] - weight + P
                # m回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, -dist[N])

answer = bellmanford(N+N+10, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(N+N+10, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(3*N, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(N+N+10, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i >= N and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(M+N+2, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i == m-1 and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(M+N+2, graph, 1)
print(answer)
#

Submission status: Wrong Answer

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i == m-1 and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(M+N+2, graph, 1)
print(answer)
#

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i == m-1 and ne == N and dist[ne] > 0:
                    return -1
    if dist[N] == -INF:
        return -1
    return max(0, dist[N])

answer = bellmanford(M+N+10, graph, 1)
print(answer)
# 58

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i == m-1 and ne == N:
                    return -1
    if dist[N] == -INF:
        return -1
    return max(0, dist[N])

answer = bellmanford(M+N+10, graph, 1)
print(answer)
# 58

Submission status: Wrong Answer

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(m, graph, start):
    INF = float('inf')
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0

    for i in range(m):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # m回繰り返してもスコアが更新された場合
                if i == m-1 and ne == N:
                    return -1
    return max(0, dist[N])

answer = bellmanford(M+N, graph, 1)
print(answer)
# 58

Submission status: Wrong Answer

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


def bellman_ford(s, g):
    # loop 0 - (n-1) : bellman ford
    # loop n - (2n-1): check g can be updated
    dist = [float("inf")] * n
    dist[s] = 0
    negative = [False] * n
    for i in range(2 * n):
        for a, b, c in abc:
            a -= 1
            b -= 1
            cost = -(c - p)

            if dist[b] > dist[a] + cost:
                dist[b] = dist[a] + cost
                if i >= n:
                    negative[b] = True

    if negative[g]:
        return -1

    else:
        return max(-dist[g], 0)


ans = bellman_ford(0, n - 1)
print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
E = dict()
for i in range(M):
    a, b, c = map(int, input().split())
    E[(i, a, b)] = c-P
INF = float('inf')

dist = {i: -INF for i in range(1, N+1)}
dist[1] = 0
ans = 0
for i in range(N*2):
    for iuv, c in E.items():
        _, u, v = iuv
        if dist[v] < dist[u] + c:
            dist[v] = dist[u] + c

    if i == N-1:
        ans = dist[N]

print(max(0, dist[N]) if ans == dist[N] else -1)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
def BellmanFord(edges,num_v,s):
  #グラフの初期化
  inf=float("inf")
  dist=[inf]*num_v
  dist[s]=0

  #辺の緩和
  for i in range(num_v):
    for edge in edges: #edges[頂点][頂点][重み]
      if dist[edge[0]] != inf and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1 and edge[1]==num_v-1: return -1

  return dist[num_v-1]
edges=[]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  c*=-1
  edges.append((a,b,c))
f = BellmanFord(edges,n,0)
if f == -1:
  print(-1)
else:
  print(max(-f, 0))

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
def BellmanFord(edges,num_v,s):
  #グラフの初期化
  inf=float("inf")
  dist=[inf]*num_v
  dist[s]=0

  #辺の緩和
  for i in range(num_v):
    for edge in edges: #edges[頂点][頂点][重み]
      if dist[edge[0]] != inf and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1 and edge[1]==num_v-1: return -1

  return dist[num_v-1]
edges=[]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  c*=-1
  edges.append((a,b,c))
f = BellmanFord(edges,n,0)
if f == -1:
  print('inf')
else:
  print(max(-f, 0))

Submission status: Wrong Answer

Solution code:
class BellmanFord:
  def __init__(self, n, edge):
    self.edge = edge
    self.n = n
    self.dist = [float('inf')] * self.n

  def fit(self):
    self.dist[0] = 0
    for _ in range(self.n - 1):
      for source, destination, weight in self.edge:
        tmp = self.dist[source] + weight
        if self.dist[destination] > tmp:
          self.dist[destination] = tmp
  
  def is_negative_cycle(self) -> bool:
    for source, destination, weight in self.edge:
      if self.dist[destination] > self.dist[source] + weight:
        return True
    return False

n, m, p = map(int, input().split())
edge = []
for _ in range(m):
  a, b, c = map(int, input().split())
  edge.append((a-1, b-1, p-c))
  
bf = BellmanFord(n, edge)
bf.fit()
if bf.is_negative_cycle():
  print(0)
else:
  print(-bf.dist[-1])

Submission status: Wrong Answer

Solution code:
class BellmanFord:
  def __init__(self, n, edge):
    self.edge = edge
    self.n = n
    self.dist = [float('inf')] * self.n

  def fit(self):
    self.dist[0] = 0
    for _ in range(self.n - 1):
      for source, destination, weight in self.edge:
        tmp = self.dist[source] + weight
        if self.dist[destination] > tmp:
          self.dist[destination] = tmp

n, m, p = map(int, input().split())
edge = []
for _ in range(m):
  a, b, c = map(int, input().split())
  edge.append((a-1, b-1, p-c))
  
bf = BellmanFord(n, edge)
bf.fit()
print(-min(0, bf.dist[-1]))