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
input = sys.stdin.readline

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

INF = 10 ** 9
#入力

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

check = [False] * N
d = [INF] * N #距離を記録

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    i = 0
    while i < N - 1:
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
        i += 1
    
    i = 0
    while i < N:
        for i in range(M):
            if d[e[0]] == INF:
                continue
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                check[e[1]] = True
            if check[e[0]]:
                check[e[1]] = True

shortest_path(1)
if check[N - 1]:
    print (-1)
else:
    ans = d[N - 1]
    print (max(0, -ans))
# print (d)

Submission status: Wrong Answer

Solution code:
import sys
def main():
    input = sys.stdin.readline
    N,M,P=map(int, input().split())
    E=[]
    G=[[] for _ in range(N)]
    H=[[] for _ in range(N)]
    for _ in range(M):
        a,b,c=map(int, input().split())
        a,b=a-1,b-1
        E.append((a,b,c-P))
        G[b].append(a)
        H[a].append(b)

    R1=[False]*N
    R1[0]=True
    stk=[0]
    while stk:
        v=stk.pop()
        for to in H[v]:
            if R1[to]: continue
            R1[to]=True
            stk.append(to)

    R2=[False]*N
    R2[N-1]=True
    stk=[N-1]
    while stk:
        v=stk.pop()
        for to in G[v]:
            if R2[to]: continue
            R2[to]=True
            stk.append(to)

    dp=[-10**10]*N
    for i in range(N):
        for a,b,c in E:
            if R1[a]==False: continue
            if R2[b]==False: continue
            if dp[b] < dp[a] + c:
                dp[b] = dp[a] + c
                if i==N-1:
                    print(-1)
                    return
    print(max(0,dp[N-1]))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def main():
    input = sys.stdin.readline
    N,M,P=map(int, input().split())
    E=[]
    G=[[] for _ in range(N)]
    H=[[] for _ in range(N)]
    for _ in range(M):
        a,b,c=map(int, input().split())
        a,b=a-1,b-1
        E.append((a,b,c-P))
        G[b].append(a)
        H[a].append(b)

    R1=[False]*N
    R1[0]=True
    stk=[0]
    while stk:
        v=stk.pop()
        for to in H[v]:
            if R1[to]: continue
            R1[to]=True
            stk.append(to)

    R2=[False]*N
    R2[N-1]=True
    stk=[N-1]
    while stk:
        v=stk.pop()
        for to in G[v]:
            if R2[to]: continue
            R2[to]=True
            stk.append(to)

    dp=[0]*N
    for i in range(N):
        for a,b,c in E:
            if R1[a]==False: continue
            if R2[b]==False: continue
            if dp[b] < dp[a] + c:
                dp[b] = dp[a] + c
                if i==N-1:
                    print(-1)
                    return
    print(max(0,dp[N-1]))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def main():
    input = sys.stdin.readline
    N,M,P=map(int, input().split())
    E=[]
    G=[[] for _ in range(N)]
    H=[[] for _ in range(N)]
    for _ in range(M):
        a,b,c=map(int, input().split())
        a,b=a-1,b-1
        E.append((a,b,c-P))
        G[b].append(a)
        H[a].append(b)

    R1=[False]*N
    V=[False]*N
    V[0]=True
    stk=[0]
    while stk:
        v=stk.pop()
        R1[v]=True
        for to in H[v]:
            if V[to]: continue
            V[to]=True
            stk.append(to)

    R2=[False]*N
    V=[False]*N
    V[N-1]=True
    stk=[N-1]
    while stk:
        v=stk.pop()
        R2[v]=True
        for to in G[v]:
            if V[to]: continue
            V[to]=True
            stk.append(to)

    dp=[0]*N
    for i in range(N):
        for a,b,c in E:
            if R1[a]==False: continue
            if R2[b]==False: continue
            if dp[b] < dp[a] + c:
                dp[b] = dp[a] + c
                if i==N-1:
                    print(-1)
                    return
    print(dp[N-1])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

INF = 10 ** 9
#入力

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

check = [False] * N

d = [0] * N #距離を記録
def find_negative_loop(): #負の閉路が存在するかを確認
    check[0] = True
    for i in range(N):
        for j in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[j]
            if check[e[0]]:
                check[e[1]] = True
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                #頂点の回数と同じだけループを回しても更新が起きる-->負の閉回路が存在
                if i == N-1 and e[1] == N - 1 and check[e[0]]:
                    return True #Trueの時, 負の閉路が存在
    return False #Falseの時, 負の閉路が存在しない

#呼び出しスタート地点を入れる
if find_negative_loop():
    print (-1)
    exit()

d = [INF] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    i = 0
    while i < N + 1:
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                prev[e[1]] = e[0]
        if not update:
            break
        i += 1

shortest_path(1)
ans = d[N - 1]
print (max(0, -ans))
# print (d)

Submission status: Wrong Answer

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

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


class UnionFind(object):
    def __init__(self, N):
        self.parent = [-1] * N #parent[i] は(i+1)番目の要素が含まれる要素数の(-1)倍
    #要素が負-->その数を親とするグループに属する要素の数×(-1)
    #要素が正-->親のindex

    #Aがどのグループに属しているかを調べる
    def root(self, A):
        if self.parent[A-1] < 0: #負の数-->その数は親
            return A
        self.parent[A-1] = self.root(self.parent[A-1]) #負では無い時、親の場所が入っているから、親が属しているグループを、自分自身に入れる(一度確認したところは直接親を見れるようにする)
        return self.parent[A-1] #親の位置を返す

    #Aが含まれているグループに属している数を返す
    def size(self, A):
        return -1 * self.parent[self.root(A)-1]

    #AとBをくっ付ける
    def connect(self, A, B):
        A = self.root(A) #Aを含むグループの親を返す
        B = self.root(B) #Bを含むグループの親を返す
        if A == B: #親が同じならなにもしない
            return False
        
        #大きい方(A)に小さい方(B)をつなぎたい
        if self.size(A) < self.size(B): #大小関係が逆の時は入れ替える
            A, B = B, A
        
        self.parent[A-1] += self.parent[B-1] #大きい方に小さい方を加える　（負の数＋負の数 = 新しいグループに含まれる数×(-1)）
        self.parent[B-1] = A #加えられた親の値を、加えた先の親の位置に書き変える
        return True
    
    def same(self, A, B):
        if self.root(A) == self.root(B):
            return True
        else:
            return False




INF = 10 ** 9
#入力

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

check = [False] * N

d = [0] * N #距離を記録
def find_negative_loop(): #負の閉路が存在するかを確認
    check[0] = True
    for i in range(N):
        for j in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[j]
            if check[e[0]]:
                check[e[1]] = True
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                #頂点の回数と同じだけループを回しても更新が起きる-->負の閉回路が存在
                if i == N-1 and e[1] == N - 1 and check[e[0]]:
                    return True #Trueの時, 負の閉路が存在
    return False #Falseの時, 負の閉路が存在しない

#呼び出しスタート地点を入れる
if find_negative_loop():
    print (-1)
    exit()

d = [INF] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    i = 0
    while i < N + 1:
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                prev[e[1]] = e[0]
        if not update:
            break
        i += 1

shortest_path(1)
ans = d[N - 1]
print (max(0, -ans))
# print (d)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import heapq
import sys
sys.setrecursionlimit(10**9)

def dfs(scores, index, v, s):
    for nv,nc in Edge[v]:
        if scores[nv] == 0:
            scores[nv] = s + nc
            index[nv] = index[v] + 1
            dfs(scores,index, nv, s + nc)
        else:
            T = s + nc - scores[nv]
            L = index[nv] - index[v]
            if -T>L*P:
                if reach_bool[nv]:
                    print(-1)
                    exit()
    return 


def canReach(v):
    ret = False
    for nv,_ in Edge[v]:
        if nv == N-1:
            return True
        elif visited[nv]:
            continue
        else:
            visited[nv] = True
            ret |= canReach(nv)

    return ret


def dijkstra(S, N, Edge):
    # S: start vertex
    # N: number of vertices
    # Edge: adjacent list [node, cost]
    
    INF = 10**20
    dist = [INF]*N
    dist[S] = 0
    que = [[0, S]]
    heapq.heapify(que)
    
    while que:
        c, v = heapq.heappop(que)
        if dist[v] < c: continue

        for nv, nc in Edge[v]:
            if c+nc < dist[nv]:
                dist[nv] = c+nc
                heapq.heappush(que, [c+nc, nv])
    
    return dist



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

reach_bool = [False]*N
reach_bool[N-1] = True

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

for i in range(N):
    visited = [False]*N
    visited[i] = True
    reach_bool[i] = canReach(i)
    visited[i] = False

scores = [0]*N

index = [0]*N



dfs(scores, index, 0, 0)

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

dist = dijkstra(0, N, newEdge)
ans = max(0, -dist[N-1])
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import heapq
import sys
sys.setrecursionlimit(10**9)

def dfs(scores, index, v, s):
    for nv,nc in Edge[v]:
        if scores[nv] == 0:
            scores[nv] = s + nc
            index[nv] = index[v] + 1
            dfs(scores,index, nv, s + nc)
        else:
            T = s + nc - scores[nv]
            L = index[nv] - index[v]
            if -T>L*P:
                if reach_bool[nv]:
                    print(-1)
                    exit()
    return 


def canReach(v):
    ret = False
    for nv,_ in Edge[v]:
        if nv == N-1:
            return True
        elif visited[nv]:
            continue
        else:
            visited[nv] = True
            ret |= canReach(nv)

    return ret


def dijkstra(S, N, Edge):
    # S: start vertex
    # N: number of vertices
    # Edge: adjacent list [node, cost]
    
    INF = 10**20
    dist = [INF]*N
    dist[S] = 0
    que = [[0, S]]
    heapq.heapify(que)
    
    while que:
        c, v = heapq.heappop(que)
        if dist[v] < c: continue

        for nv, nc in Edge[v]:
            if c+nc < dist[nv]:
                dist[nv] = c+nc
                heapq.heappush(que, [c+nc, nv])
    
    return dist



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

reach_bool = [False]*N
reach_bool[N-1] = True

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

visited = [False]*N
for i in range(N):
    visited[i] = True
    reach_bool[i] = canReach(i)
    visited[i] = False

scores = [0]*N

index = [0]*N



dfs(scores, index, 0, 0)

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

dist = dijkstra(0, N, newEdge)
ans = max(0, -dist[N-1])
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M,P=map(int,input().split())
    edge=[[] for _ in range(N)]
    for _ in range(M):
        A,B,C=map(int1,input().split())
        C+=1
        edge[A].append((B,P-C))
    edge2=[]
    for i in range(N):
        que=deque()
        que.append(i)
        used=[False]*N
        while que:
            v=que.popleft()
            used[v]=True
            for nv,_ in edge[v]:
                if not used[nv]:
                    que.append(nv)
        if used[N-1]:
            for B,C in edge[i]:
                edge2.append((i,B,C))
    d=[INF]*N
    d[0]=0
    f=False
    for i in range(N*2):
        for a,b,c in edge2:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
                if i>=N-1 and b==N-1:
                    f=True
    if f:
        print(-1)
    else:
        print(max(-d[N-1],0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M,P=map(int,input().split())
    edge=[]
    for _ in range(M):
        A,B,C=map(int1,input().split())
        C+=1
        edge.append((A,B,P-C))
    d=[INF]*N
    d[0]=0
    f=False
    for i in range(N*2):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
                if i>=N-1 and b==N-1:
                    f=True
    if f:
        print(-1)
    else:
        print(max(-d[N-1],0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M,P=map(int,input().split())
    edge=[]
    for _ in range(M):
        A,B,C=map(int1,input().split())
        C+=1
        edge.append((A,B,P-C))
    d=[INF]*N
    d[0]=0
    f=False
    for i in range(N*2):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
                if i==N*2-1 and b==N-1:
                    f=True
    if f:
        print(-1)
    else:
        print(max(-d[N-1],0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M,P=map(int,input().split())
    edge=[]
    for _ in range(M):
        A,B,C=map(int1,input().split())
        C+=1
        edge.append((A,B,P-C))
    d=[INF]*N
    d[0]=0
    f=False
    for i in range(N+1):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
                if i==N and b==N-1:
                    f=True
    if f:
        print(-1)
    else:
        print(max(-d[N-1],0))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
adjacent = []
score = [-1*float('inf') for i in range(N)]
score[0] = 0
for i in range(M):
    a, b, c = map(int, input().split())
    adjacent.append([a-1, b-1, c-P])
for i in range(N):
    for j in adjacent:
      if score[j[1]] < score[j[0]] + j[2]:
        score[j[1]] = score[j[0]] + j[2]
    if i == N-2:
        t = score[N-1]
    if i == N-1:
        if t != score[N-1]:
            score[N-1] = 1e+15
if score[N-1] < 1e+15 and score[N-1] != -1*float('inf'):
    print(max(0,t))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
adjacent = []
score = [-1*float('inf') for i in range(N)]
score[0] = 0
for i in range(M):
    a, b, c = map(int, input().split())
    adjacent.append([a-1, b-1, c-P])
for i in range(N):
    for j in adjacent:
      if score[j[1]] < score[j[0]] + j[2]:
        score[j[1]] = score[j[0]] + j[2]
    if i == N-2:
        t = score[N-1]
    if i == N-1:
        if t != score[N-1]:
            score[N-1] = 1e+15
if score[N-1] < 1e+15:
    print(max(0,t))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
adjacent = []
score = ['None' for i in range(N)]
score[0] = 0
for i in range(M):
    a, b, c = map(int, input().split())
    adjacent.append([a-1, b-1, c-P])
for i in range(N):
    for j in adjacent:
        if score[j[1]] == 'None' and score[j[0]] != 'None':
            score[j[1]] = score[j[0]] + j[2]
        if score[j[1]] != 'None' and score[j[0]] != 'None':
            if score[j[1]] < score[j[0]] + j[2]:
                score[j[1]] = score[j[0]] + j[2]
    if i == N-2:
        t = score[N-1]
    if i == N-1:
        if t != score[N-1]:
            score[N-1] = 1e+15
if score[N-1] < 1e+15:
    print(t)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heapify, heappop, heappush

def solve():
    input = sys.stdin.readline
    N, M, P = map(int, input().split())
    Edge = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        Edge[A-1].append((C - P, B - 1))
    q = []
    heapify(q)
    Money = [None] * N
    heappush(q, (0, 0, False))
    Over = [False] * N
    while q:
        money, nn, isOver = heappop(q)
        if Money[nn] == None:
            Money[nn] = - money
            Over[nn] = isOver
            for cost, nextn in Edge[nn]: heappush(q, (money - cost, nextn, isOver))
        else:
            if Money[nn] < - money:
                Over[nn] = True
                if not isOver: 
                    for cost, nextn in Edge[nn]: heappush(q, (money - cost, nextn, True))
   
    if Over[N-1]: print(-1)
    else: print(max(0, Money[N-1]))


    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [-10**18] * n
ok = [False] * n
d[0] = 0
ok[0] = True

for _ in range(n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

aa = d[-1]

for _ in range(2*n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [0] * n
ok = [False] * n
ok[0] = True

for _ in range(2 * n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

aa = d[-1]

for _ in range(2*n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [0] * n
ok = [False] * n
ok[0] = True

for _ in range(n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

aa = d[-1]

for _ in range(2*n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [0] * n
ok = [False] * n
ok[0] = True

for _ in range(n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

aa = d[-1]

for _ in range(n):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[-1] -= p

d = [0] * n
ok = [False] * n
ok[0] = True

for _ in range(n-1):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

aa = d[-1]

for _ in range(n-1):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = True

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[-1] -= p

d = [0] * n
ok = [False] * n
ok[0] = True

for _ in range(n-1):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = a

aa = d[-1]

for _ in range(n-1):
    for a, b, c in e:
        if ok[a]:
            d[b] = max(d[b], d[a] + c)
            ok[b] = a

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[-1] -= p

d = [0] * n

for _ in range(n-1):
    for a, b, c in e:
        d[b] = max(d[b], d[a] + c)

aa = d[-1]

for _ in range(n-1):
    for a, b, c in e:
        d[b] = max(d[b], d[a] + c)

bb = d[-1]

if aa != bb:
    print("-1")
else:
    print(max(aa, 0))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]

INF = 10 ** 9 + 7
dist = [INF] * (N + 1)
dist[1] = 0

for i in range(2 * N):
    for u, v, c in X:
        if dist[u] != INF and dist[v] > dist[u] - (c - P):
            dist[v] = dist[u] - (c - P)
            updated = True
            
        if i == N - 1:
            prev = dist[-1]
            
if prev != dist[-1]:
    print(-1)
else:
    print(max(0, -dist[-1]))

Submission status: Wrong Answer

Solution code:

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    
    #0から他の頂点へ
    def BellmanFord(N, M, edges):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #目的地への最短距離がまだ更新されるか確認
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路
                
                d[v] = d[u] + c
        return d[N-1]
    
    N,M,P=MI()
    edges=[]
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        edges.append([a,b,-1*c])
        
    ans=BellmanFord(N,M,edges)
    if ans==None:
        print(-1)
    elif ans>=10**10:
        print(-1)
    else:
        print(max(-1*ans,0))
    
        

main()

Submission status: Wrong Answer

Solution code:

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    
    #0から他の頂点へ
    def BellmanFord(N, M, edges):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #目的地への最短距離がまだ更新されるか確認
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路
                
                d[v] = d[u] + c
        return d[N-1]
    
    N,M,P=MI()
    edges=[]
    inf=10**20
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        edges.append([a,b,-1*c])
        
    ans=BellmanFord(N,M,edges)
    if ans==None:
        print(-1)
    elif ans>=inf:
        print(-1)
    else:
        print(max(-1*ans,0))
    
        

main()

Submission status: Wrong Answer

Solution code:

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    
    #0から他の頂点へ
    def BellmanFord(N, M, edges):
        #N頂点，M辺，edgesのリスト
        inf=10**20
        d = [inf] * N
        d[0] = 0

        for i in range(N-1):
            for (u, v, c) in edges:
                if d[u] + c < d[v]:
                    d[v] = d[u] + c

        #for i in range(N):
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N-1:
                    return None#負の閉路
                
                d[v] = d[u] + c
        return d[N-1]
    
    N,M,P=MI()
    edges=[]
    for _ in range(M):
        a,b,c=MI()
        a-=1
        b-=1
        c-=P
        edges.append([a,b,-1*c])
        
    ans=BellmanFord(N,M,edges)
    if ans==None:
        print(-1)
    else:
        print(max(-1*ans,0))
    
        

main()

Submission status: Wrong Answer

Solution code:
def bellmanford(v,s,path):
    inf = float('inf')

    # 距離をinfで初期化
    d = [inf]*v

    # startの頂点までの距離 = 0
    d[s] = 0
    for j in range(2*v):
        update = False

        # 各頂点までの距離を更新
        # 全辺について、"頂点bまでの距離"が"aまでの距離"+"aからbまでの辺"よりも大きいとき更新
        for a,b,c in path:
            if d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True

                """
                # 負の閉路の検出。負の閉路を求めないならいらない。
                # v-1回更新しても、さらに更新できるときは負の閉路が存在することになる。
                if j == v-1:
                    return -1
                """

                # 頂点n-1を含む閉路が存在するかの検出（v回目の更新でn-1への最短距離が更新される = n-1を含む負の閉路が存在する）
                if j >= v-1 and b == n-1:
                    return -1


        # 更新が行われない場合はやめる。
        if not update:
            break

    return d

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

path = []
for i in range(m):
    a,b,c = map(int,input().split())
    a-=1
    b-=1
    c-=p
    path.append([a,b,-c])

a = bellmanford(n,0,path)
if a==-1:
    print(-1)
else:
    print(max(0,-a[-1]))

Submission status: Wrong Answer

Solution code:
def bellmanford(v,e,s,path):
    inf = float('inf')

    # 距離をinfで初期化
    d = [inf for i in range(v)]

    # startの頂点までの距離 = 0
    d[s] = 0
    for j in range(v):
        update = False

        # 各頂点までの距離を更新
        # 全辺について、"頂点path[i][1]までの距離"が"path[i][0]までの距離"+"path[i][0]からpath[i][1]までの辺"よりも大きいとき更新
        for i in range(e):
            if d[path[i][0]] != inf and d[path[i][1]] > d[path[i][0]] + path[i][2]:
                d[path[i][1]] = d[path[i][0]] + path[i][2]
                update = True

                """
                # 負の閉路の検出。負の閉路を求めないならいらない。
                # v-1回更新しても、さらに更新できるときは負の閉路が存在することになる。
                if j == v-1:
                    return -1
                """

                # 頂点n-1を含む閉路が存在するかの検出（v回目の更新でn-1への最短距離が更新される = n-1を含む負の閉路が存在する）
                if j == v-1 and path[i][1]==n-1:
                    return -1


        # 更新が行われない場合はやめる。
        if not update:
            break
    return d

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

path = []
for i in range(m):
    a,b,c = map(int,input().split())
    a-=1
    b-=1
    c-=p
    path.append([a,b,-c])

a = bellmanford(n,m,0,path)
if a==-1:
    print(-1)
else:
    print(max(0,-a[-1]))