Problem:


Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Wrong Answer

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

from collections import defaultdict
G = defaultdict(dict)
for i in range(n):
    G[i+1] = {}
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

def bellmanford(G, start_vertex):
    if start_vertex not in G:
        return -1,-1 # no key
    distances = {}
    parents   = {}
    for node in G:
        # distances[node] = float('inf')
        distances[node] = float('-inf')
        parents[node]   = None
    distances[start_vertex] = 0
    for _ in range(len(G)-1):
        for node in G.keys():
            for neighbor in G[node]:
                if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                # if distances[neighbor] > distances[node] + G[node][neighbor]:
                    distances[neighbor] = distances[node] + G[node][neighbor] - p
                    parents[neighbor]   = node
    # for node in G.keys():
    #     for neighbor in G[node]:
    #         if (distances[neighbor] < distances[node] + G[node][neighbor]):
    #         # if (distances[neighbor] > distances[node] + G[node][neighbor]):
    #             return -1,-1 # occurs recursion.
    # if you only need to check the recursion on right path
    node = n
    while node != start_vertex:
        for neighbor in G[node]:
            if distances[neighbor] < distances[node] + G[node][neighbor] - p:
                return -1,-1
        node = parents[node]
    return distances, parents
distances, parents = bellmanford(G, 1)

ans = 0
if distances == -1:
    print(-1, flush=True)
else:
    print(max(ans, distances[n]), flush=True)

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())
from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c
 
from collections import deque
def dfs(G, src, tgt):
    pathes = []
    if src not in G:
        return -1
    parents = {src: None}
    queue = deque([src])
    while queue:
        node = queue.pop()
        for neighbor in G[node]:
            if neighbor not in parents.values():
                parents[neighbor] = node
                queue.append(neighbor)
                if neighbor == tgt:
                    pivot = neighbor
                    point = 0
                    path = [pivot]
                    while parents[pivot] is not None:
                        parent = parents[pivot]
                        if parent in path:
                            print(pivot, parent, flush=True)
                            return -1
                        path.insert(0, parent)
                        point += G[parent][pivot]
                        pivot = parent
                    pathes.append(
                        {
                            'times': len(path)-1,
                            'point': point
                        }
                    )
    return pathes
pathes = dfs(G, 1, n)
if pathes == -1:
    print(-1 , flush=True)
else:
    ans = 0
    for i in pathes:
        ans = max(ans, i['point'] - i['times']*p)
    print(ans , flush=True)

Submission status: Wrong Answer

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

for i in range(M):
  A,B,C=map(int,input().split())
  ways[A-1].append([B-1,C-P])
  Rways[B-1].append(A-1)
  
  
visited=[-float("inf")]*N
visited[0]=0

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

for c in range(M):
  for i in range(N):
    if blacklist[i]==True:
      continue
    for to in Rways[i]:
      blacklist[to]=False

for c in range(M):
  flag=False
  for i in range(N):
    debit=visited[i]
    if debit==-float("inf"):
      continue
    for to,cost in ways[i]:
      if visited[to]<debit+cost and not blacklist[to]:
        visited[to]=debit+cost
        flag=True
        
  if not flag:
    break
  if c==M-1:
    print(-1)
    exit()
      
ans=visited[-1]
if ans==-float("inf"):
  print(-1)
else:
  print(max(ans,0))

Submission status: Wrong Answer

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

for i in range(M):
  A,B,C=map(int,input().split())
  ways[A-1].append([B-1,C-P])
  Rways[B-1].append(A-1)
  
  
visited=[-float("inf")]*N
visited[0]=0

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

for c in range(M):
  for i in range(N):
    if blacklist[i]==False:
      continue
    for to in Rways[i]:
      blacklist[to]=True

for c in range(M):
  flag=False
  for i in range(N):
    debit=visited[i]
    if debit==-float("inf"):
      continue
    for to,cost in ways[i]:
      if visited[to]<debit+cost and not blacklist[to]:
        visited[to]=debit+cost
        flag=True
        
  if not flag:
    break
  if c==M-1:
    print(-1)
    exit()
      
ans=visited[-1]
if ans==-float("inf"):
  print(-1)
else:
  print(max(ans,0))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())
from collections import defaultdict
G = defaultdict(dict)
for i in range(m):
    a,b,c = map(int, input().split())
    G[a][b] = c

from collections import deque
def dfs(G, src, tgt):
    pathes = []
    if src not in G:
        return -1
    parents = {src: None}
    queue = deque([src])
    while queue:
        node = queue.pop()
        for neighbor in G[node]:
            if neighbor not in parents.values():
                parents[neighbor] = node
                queue.append(neighbor)
                if neighbor == tgt:
                    pivot = neighbor
                    point = 0
                    path = [pivot]
                    while parents[pivot] is not None:
                        parent = parents[pivot]
                        if parent in path:
                            print(pivot, parent, flush=True)
                            return -1
                        path.insert(0, parent)
                        point += G[parent][pivot]
                        pivot = parent
                    pathes.append(
                        {
                            'times': len(path)-1,
                            'point': point
                        }
                    )
    return pathes
pathes = dfs(G, 1, n)
if pathes == -1:
    print(-1 , flush=True)
else:
    ans = 0
    for i in pathes:
        ans = max(ans, i['point'] - i['times']*p)
    print(ans , flush=True)

Submission status: Wrong Answer

Solution code:
# ベルマンフォード
N,M,P = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(M)]
inf = 10 **31
flag = True

cost = [inf] * N
cost[0] = 0
for _ in range(M-1):
    flag = True
    for branch in A:
        a,b,c = branch
        if cost[b-1] >cost[a-1]+P-c:
            flag = False
            cost[b-1] = cost[a-1]+P-c
    if flag:
        break

if flag :
    print(-cost[-1])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

N, M, P = getNM()
que = [getList() for i in range(M)]

edges = []
for a, b, c in que:
    # 次の点に行った時に獲得できる点 - 支払うコインP
    # 重みが負になることもある　→　ベルマンフォード
    edges.append([a - 1, b - 1, c - P])

# どのようにNに到達すればいいか
# 最長距離を求める

def bellman(edges, num_v):
    dist = [-float('inf') for i in range(num_v)]
    dist[0] = 0

    # 一回目のループ
    for i in range(N - 1):
        for edge in edges:
            if dist[edge[1]] < dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]

    # 負閉路検出
    nega = [0] * N
    for i in range(N):
        for edge in edges:
            if dist[edge[1]] < dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                nega[edge[1]] = 1

    if nega[N - 1]:
        print('-1')
        exit()

    return dist

ans = bellman(edges, N)[N - 1]
if ans <= 0:
    print(0)
else:
    print(ans)

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, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,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 printe(*x):print("## ",*x,file=sys.stderr)
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 binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=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)) #改行行列
    edge = [[] for i in range(N)]
    for i in range(M):#木の場合M=N-1
        a,b,w = map(int,input().split())
        edge[a-1].append((P-w,b-1))

    start=0
    inf=10**14
    d=[inf]*N
    d[start]=0
    for _ in range(N):#更新はせいぜい（ノード数)回
        update=False
        for e in range(N):
            for nd,ne in edge[e]:
                x=d[e]+nd
                if x<d[ne]:
                    d[ne]=x
                    update=True
        if update==False: break
    cd=d[-1]
    for _ in range(N):#更新はせいぜい（ノード数)回
        update=False
        for e in range(N):
            for nd,ne in edge[e]:
                x=d[e]+nd
                if x<d[ne]:
                    d[ne]=-inf
                    update=True
        if update==False: break
    
    if d[-1]==-inf:
        print(-1)
        return
    print(max(0,-d[N-1]))




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, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,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 printe(*x):print("## ",*x,file=sys.stderr)
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 binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=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)) #改行行列
    edge = [[] for i in range(N)]
    for i in range(M):#木の場合M=N-1
        a,b,w = map(int,input().split())
        edge[a-1].append((P-w,b-1))

    start=0
    inf=10**14
    d=[inf]*N
    d[start]=0
    for _ in range(N):#更新はせいぜい（ノード数)回
        update=False
        for e in range(N):
            for nd,ne in edge[e]:
                x=d[e]+nd
                if x<d[ne]:
                    d[ne]=x
                    update=True
        if update==False: break
    cd=d[-1]
    for _ in range(N):#更新はせいぜい（ノード数)回
        update=False
        for e in range(N):
            for nd,ne in edge[e]:
                x=d[e]+nd
                if x<d[ne]:
                    d[ne]=x
                    update=True
        if update==False: break
    
    if cd>d[-1]:
        print(-1)
        return
    print(max(0,-d[N-1]))




if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

input=sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()


def II(): return int(input())


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


def MF(): return map(float,input().split())


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


def LF(): return list(map(float,input().split()))


def TI(): return tuple(map(int,input().split()))


# rstrip().decode('utf-8')


def main():
	n,m,p=MI()
	G=[[] for _ in range(n+1)]
	
	for _ in range(m):
		a,b,c=MI()
		G[a].append([b,c-p])
	#print(G)
	
	coin=[-10**10]*(n+1)
	coin[1]=0
	
	for _ in range(m+5):
		for i in range(1,n+1):
			for b,c in G[i]:
				coin[b]=max(coin[b],coin[i]+c)
	
	k=coin[-1]
	#print(k)
	for i in range(1,n+1):
		for b,c in G[i]:
			coin[b]=max(coin[b],coin[i]+c)
	
	ans=0
	
	if k!=coin[-1]:
		ans=-1
	elif coin[-1]>0:
		ans=coin[-1]
	
	print(ans)
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

if __name__=="__main__":
	main()

Submission status: Wrong Answer

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

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

from collections import deque

def main():
	n,m,p=MI()
	G=[[] for _ in range(n+1)]
	for _ in range(m):
		a,b,c=MI()
		G[a].append((b,c-p))
	#print(G)

	ng=set()

	for i in range(1,n+1):
		if i not in ng:
			Q=deque()
			Q.append([i,0])
			f=1
			mm=m+5
			while Q and f and mm:
				#print(i,Q,f)
				now,nowcoin=Q.popleft()
				for next,coin in G[now]:
					mm-=1
					if next==i:
						if nowcoin+coin>0:
							ng.add(i)
							f=0
							break
					else:
						Q.append([next,nowcoin+coin])
	#print(ng)

	if n in ng:
		print(-1)
		exit()


	Q=deque()
	Q.append(1)

	ans=[-10**10]*(n+1)
	ans[1]=0

	while Q:
		now=Q.popleft()
		for next,coin in G[now]:
			if ans[next]<ans[now]+coin and now not in ng:
				Q.append(next)
				ans[next]=ans[now]+coin

	print(ans[-1] if ans[-1]>0 else 0)












if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
N,M,P=map(int,input().split())
G=[]
a,b,c=0,0,0
for i in range(M):
  a,b,c=map(int,input().split())
  G.append((a-1,b-1,P-c))
INF=10**15
D=[INF]*N
D[0]=0
e=0
for r in range(N-1):
  for i in range(M):
    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]
X=D[-1]
for r in range(2*max(M,N)):
  for i in range(M):
    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]
if X>D[-1]:
  print(-1)
else:
  print(-min(D[-1],0))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int,input().split())
edges = []
for _ in range(m):
    a,b,c = map(int,input().split())
    edges.append((a-1,b-1,c-p))
def Bellmanford(n,edges,r):
    d = [-float('inf')]*n
    d[r] = 0
    for i in range(n):
        for u,v,c in edges:
            if d[u] != -float('inf') and d[u]+c > d[v]:
                d[v] = d[u]+c
                if i ==n-1 and v == n-1:
                    return 'inf'
    return d[n-1]

ans = Bellmanford(n,edges,0)
if ans =='inf': print(-1);exit()
elif ans <=0: print(0);exit()
else: print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop
from time import time

N,M,P=map(int,input().split())
G=[{} for i in range(N+1)]
for i in range(M):
  a,b,c=map(int,input().split())
  G[a][b]=c
  
def dijkstra(G, start = 1, INF=0):
    begin=time()
    
    d = [INF for i in range(len(G))]
    d[start] = 0
    
    que = []
    heappush(que, (0, start))
    finish=0
    while len(que) != 0:
        if time() - begin > 1.5:
          print(-1)
          finish=-1
          break
        p = heappop(que)
        v = p[1]
        
        if d[v] < p[0]:
            continue
            
        for u in G[v].keys():
            if d[u] > d[v] + (-G[v][u]) + P:
                d[u] = d[v] + (-G[v][u]) + P
                heappush(que, (d[u], u))
    
    return d,finish
  
d,finish = dijkstra(G,1)

if finish==0:print(max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop

N,M,P=map(int,input().split())
G=[{} for i in range(N+1)]
for i in range(M):
  a,b,c=map(int,input().split())
  G[a][b]=c
  
def dijkstra(G, start = 1, INF=0):
    
    d = [INF for i in range(len(G))]
    d[start] = 0
    
    que = []
    heappush(que, (0, start))

    while len(que) != 0:
        p = heappop(que)
        v = p[1]
        
        if d[v] < p[0]:
            continue
            
        for u in G[v].keys():
            if d[u] > d[v] + (-G[v][u]) + P:
                d[u] = d[v] + (-G[v][u]) + P
                heappush(que, (d[u], u))
    
    return d
  
d = dijkstra(G,1)

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

Submission status: Wrong Answer

Solution code:
from collections import deque

N,M,P=map(int,input().split())
G=[{} for i in range(N+1)]
for i in range(M):
  a,b,c=map(int,input().split())
  G[a][b]=c
  
def bfs(s):
    seen = [0 for i in range(N+1)]
    d = [0 for i in range(N+1)]
    prev = [0 for i in range(N+1)]
    coin = [0 for i in range(N+1)]
    cycles=[]
    todo = deque([])
    now = s
    seen[now]=1
    todo.append(now)
    while 1:
      if len(todo)==0:break
      a = todo.popleft()
      for b in G[a].keys():
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          d[b] += d[a] + 1
          coin[b] += G[a][b]
          prev[b] = a
        else:
          cycles.append((a,b))
    return d, prev, coin, cycles

d, prev, coin, cycles = bfs(1)
finish=0
    
if finish == 0:print(max(coin[N] - d[N]*P,0))

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

'''
lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
'''
n,m,p = input().split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(1,m+1):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))



inf = 0

maxx = 0
dst = [10**10 for _ in range(n+1)]
dst[1] = 0
for i in range(n-1):
    for x,y,c in edge:
        if(dst[x]==10**10): continue
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from heapq import heappush,heappop

'''
lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
'''
n,m,p = input().split()
n = int(n)
m = int(m)
p = int(p)

e = [[] for _ in range(n+1)]
edge = []
a=[]
for i in range(1,m+1):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    c = int(c)
    edge.append((x,y,p-c))
    #e[x].append((y,c-p))



inf = 0

maxx = 0
dst = [10**9 for _ in range(n+1)]
dst[1] = 0
for i in range(n-1):
    for x,y,c in edge:
        if dst[y]>dst[x]+c:
            dst[y] = dst[x]+c
for x,y,c in edge:
        if y==n and dst[y]>dst[x]+c:
            print("-1")
            inf = 1

if not inf:
    print((dst[n]<0)*dst[n]*(-1))

Submission status: Wrong Answer

Solution code:
import sys

def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N,M,P = LI()

import collections

class BellmanFord():
    def __init__(self,N):  # Nは頂点の個数
        self.N = N
        self.e = collections.defaultdict(list)
    def add(self,u,v,d,directed = False):
        if directed is False:  # 無向グラフの場合
            self.e[u].append((v,d))
            self.e[v].append((u,d))
        else:  # 有向グラフの場合
            self.e[u].append((v,d))
    def BellmanFord_search(self,s):  # sから各点までの最短距離
        d = collections.defaultdict(lambda: float('inf'))
        d[s] = 0
        while True:
            update = False
            for u in self.e.keys():
                for v,c in self.e[u]:
                    if d[v] > d[u] + c:
                        d[v] = d[u] + c
                        update = True
            if not update:
                break
        return d
    def BellmanFord_negative_bool(self,s):  # sから辿り着ける負の閉路が存在するか
        d = collections.defaultdict(lambda: float('inf'))
        d[s] = 0
        for i in range(self.N):
            for u in self.e.keys():
                for v,c in self.e[u]:
                    if d[v] > d[u] + c:
                        d[v] = d[u] + c
                        if i == self.N - 1:
                            return True,d
        return False,d

G = BellmanFord(N)

for i in range(M):
    a,b,c = LI()
    G.add(a,b,P-c,directed=True)

a,d = G.BellmanFord_negative_bool(1)

if not a:
    print(max(0,-d[N]))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys

def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N,M,P = LI()

import collections

class BellmanFord():
    def __init__(self,N):  # Nは頂点の個数
        self.N = N
        self.e = collections.defaultdict(list)
    def add(self,u,v,d,directed = False):
        if directed is False:  # 無向グラフの場合
            self.e[u].append((v,d))
            self.e[v].append((u,d))
        else:  # 有向グラフの場合
            self.e[u].append((v,d))
    def BellmanFord_search(self,s):  # sから各点までの最短距離
        d = collections.defaultdict(lambda: float('inf'))
        d[s] = 0
        while True:
            update = False
            for u in self.e.keys():
                for v,c in self.e[u]:
                    if d[v] > d[u] + c:
                        d[v] = d[u] + c
                        update = True
            if not update:
                break
        return d
    def BellmanFord_negative_bool(self,s):  # sから辿り着ける負の閉路が存在するか
        d = collections.defaultdict(lambda: float('inf'))
        d[s] = 0
        for i in range(self.N):
            for u in self.e.keys():
                for v,c in self.e[u]:
                    if d[v] > d[u] + c:
                        d[v] = d[u] + c
                        if i == self.N - 1:
                            return True,d
        return False,d

G = BellmanFord(N)

for i in range(M):
    a,b,c = LI()
    G.add(a,b,P-c,directed=True)

a,d = G.BellmanFord_negative_bool(1)

if not a:
    print(-d[N])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
    ans = min(0, d[n-1])
    for i in range(n):
        for x, y, z in g:
            if d[x] > -1 * INF and d[y] > d[x] + z:
                d[y] = -1 * INF
    if d[n-1] <= -1 * INF:
        ans = 1
    return -ans
  

n, m, p = map(int,input().split())
edge = [list(map(int,input().split())) for i in range(m)]
graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
print(bellman_ford(graph, 0))

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
    ans = min(0, d[n-1])
    for i in range(n):
        for x, y, z in g:
            if d[x] != -1 * INF and d[y] > d[x] + z:
                d[y] = -1 * INF
    if d[n-1] == -1 * INF:
        ans = 1
    return -ans
n, m, p = map(int,input().split())
edge = [list(map(int,input().split())) for i in range(m)]
graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
print(bellman_ford(graph, 0))

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
    for i in range(n):
        for x, y, z in g:
            if d[x] != -1 * INF and d[y] > d[x] + z:
                d[y] = -1 * INF
    if d[n-1] == -1 * INF:
        return False
    return d[n-1]

n, m, p = map(int,input().split())
edge = [list(map(int,input().split())) for i in range(m)]

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)