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:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, m, p = LI()
abc = [LI() for _ in range(m)]
edges = [[] for _ in range(n)]
for a, b, c in abc:
    edges[a-1].append((b-1, c))

stack = [(0, 0)]
dp = [0] * n
tmp = -1
while stack:
    v, score = stack.pop()
    if tmp == v:
        print(-1)
        quit()
    tmp = v
    for u, c in edges[v]:
        if dp[u] < score + c - p:
            dp[u] = score + c - p
            stack.append((u, score + c - p))
print(dp[n-1])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, m, p = LI()
abc = [LI() for _ in range(m)]
edges = [[] for _ in range(n)]
for a, b, c in abc:
    edges[a-1].append((b-1, c))

que = deque([(0, 0)])
dp = [0] * n
tmp = -1
while que:
    v, score = que.popleft()
    if v == n - 1 and score > 10**7:
        print(-1)
        quit() 
    for u, c in edges[v]:
        if dp[u] < score + c - p:
            dp[u] = score + c - p
            que.append((u, score + c - p))
print(dp[n-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    inf=10**14
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[set() for _ in range(N)]
        d[s]=0
        count=0
        while True:
            update=False
            for e in range(N):
                if d[e]==inf:
                    continue
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if e in upper[ne] and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif e not in upper[ne] and x<d[ne]:
                        d[ne]=x
                        upper[ne].add(e)
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]==-inf:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[set() for _ in range(N)]
        d[s]=0
        count=0
        while True:
            update=False
            for e in range(N):
                if d[e]==inf:
                    continue
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if e in upper[ne] and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif e not in upper[ne] and x<d[ne]:
                        d[ne]=x
                        upper[ne].add(e)
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[set() for _ in range(N)]
        d[s]=0
        count=0
        while True:
            update=False
            for e in range(N):
                if d[e]==inf:
                    continue
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if e in upper[ne] and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif upper[ne]!=e and x<d[ne]:
                        d[ne]=x
                        upper[ne].add(e)
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[-1]*N
        d[s]=0
        count=0
        while True:
            update=False
            for e in range(N):
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if upper[ne]==e and d[ne]!=inf and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif upper[ne]!=e and x<d[ne] and d[e]!=inf:
                        d[ne]=x
                        upper[ne]=e
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[-1]*N
        d[s]=0
        count=0
        while True:
            update=False
            for e in range(N):
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if upper[ne]==e and d[ne]!=-inf and d[ne]!=inf and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif upper[ne]!=e and x<d[ne] and d[e]!=inf:
                        d[ne]=x
                        upper[ne]=e
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        upper=[-1]*N
        d[s]=0
        count=0
        while count<=10000:
            update=False
            for e in range(N):
                for nd,ne in edge[e]:
                    x=max(-inf,d[e]+nd+P)
                    if upper[ne]==e and d[ne]!=-inf and d[ne]!=inf and x<d[ne]:
                        d[ne]=-inf
                        update=True
                    elif upper[ne]!=e and x<d[ne] and d[e]!=inf:
                        d[ne]=x
                        upper[ne]=e
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, M, P = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    def tree_init(N):
        ws=[]
        edgelist = [[] for _ in range(N)]
        for a, b, w in [map(int, input().split()) for i in range(M)]:#木じゃない場合N-1をNに変える
            edgelist[a-1].append((-w,b-1))
            ws.append(-w)
        return edgelist,ws


    edge,ws=tree_init(N)

    inf=10**12#最大距離より多くとる
    visited = [inf] * N
    q = [(0,0)]

    #print([c[0] for c in edge])
    cmax=min(0,min(ws)+P)
    cmax*=M
    def bellman_ford(N,s,edge):#ベルマンフォード法,負の経路がある場合も有効、O(VE)
        inf=10**14
        d=[inf]*N
        d[s]=0
        count=0
        while count<=10000:
            update=False
            for e in range(N):
                for nd,ne in edge[e]:
                    x=d[e]+nd+P
                    if x<d[ne]:
                        d[ne]=x
                        update=True
            if update==False: break
            count+=1
        return d

    visited=bellman_ford(N,0,edge)
    if visited[-1]<cmax:
        print(-1)
        return
    print(max(-visited[-1],0))
    #print(visited)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import heapq
N,M,P = map(int,input().split())
G = {i:[] for i in range(1,N+1)}
F = {i:[] for i in range(1,N+1)}
hist = {}
for _ in range(M):
    a,b,c = map(int,input().split())
    G[a].append((b,c))
    F[b].append(a)
    hist[(a,b)] = 0
dist = [N*M for _ in range(N+1)]
dist[N]=0
hist0 = [0 for _ in range(N+1)]
que = [(0,N)]
hist0[N] = 1
while que:
    d,x = heapq.heappop(que)
    if dist[x]<d:continue
    hist0[x]=1
    for y in F[x]:
        if hist0[y]==0 and dist[y]>d+1:
            dist[y] = d+1
            heapq.heappush(que,(d+1,y))
    
heap = deque([(1,0)])
cash = [-1 for _ in range(N+1)]
cash[1] = 0
flag = 0
while heap:
    x,m = heap.popleft()
    for y,c in G[x]:
        if hist[(x,y)]==0:
            hist[(x,y)] = 1
            cash[y] = max(cash[y],m+c-P)
            heap.append((y,cash[y]))
        else:
            if cash[y]<m+c-P:
                if dist[y]<N*M:
                    flag = 1
                    break
    if flag==1:break
if flag==1:
    print(-1)
else:
    print(max(cash[N],0))

Submission status: Wrong Answer

Solution code:
from collections import deque
import heapq
N,M,P = map(int,input().split())
G = {i:[] for i in range(1,N+1)}
F = {i:[] for i in range(1,N+1)}
hist = {}
for _ in range(M):
    a,b,c = map(int,input().split())
    G[a].append((b,c))
    F[b].append(a)
    hist[(a,b)] = 0
dist = [N*M for _ in range(N+1)]
hist0 = [0 for _ in range(N+1)]
que = [(0,N)]
hist0[N] = 1
while que:
    d,x = heapq.heappop(que)
    if dist[x]<d:continue
    hist0[x]=1
    for y in F[x]:
        if hist0[y]==0 and dist[y]>d+1:
            dist[y] = d+1
            heapq.heappush(que,(d+1,y))
    
heap = deque([(1,0)])
cash = [-1 for _ in range(N+1)]
cash[1] = 0
flag = 0
while heap:
    x,m = heap.popleft()
    for y,c in G[x]:
        if hist[(x,y)]==0:
            hist[(x,y)] = 1
            cash[y] = max(cash[y],m+c-P)
            heap.append((y,cash[y]))
        else:
            if cash[y]<m+c-P:
                if dist[y]<N*M:
                    flag = 1
                    break
    if flag==1:break
if flag==1:
    print(-1)
else:
    print(max(cash[N],0))