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())
V = [[0]*(N+1) for i in range(N+1)]
W = [[-float("inf")]*(N+1) for i in range(N+1)]
E = []
for _ in range(M):
    a,b,c = map(int,input().split())
    V[a][b] = 1
    W[a][b] = c-P
    E.append([a,b,c-P])
D = [[-float("inf")]*(N+1) for i in range(N+1)]
for i in range(1,N+1):
    for j in range(1,N+1):
        for k in range(N+1):
            if k==0: 
                D[i][j] = W[i][j]
            else: D[i][j] = max(D[i][j],D[i][k]+D[k][j])
flg = 0
d = [-float("inf")]*(N+1)
d[1] = 0
for i in range(N):
    for j in range(len(E)):
        e = E[j]
        if d[e[0]] < d[e[1]]+e[2]:
            d[e[0]] = d[e[1]]+e[2]
            if i==N-1:
                flg = 1
if flg:
    print(-1)
else:
    print(max(0,D[1][N]))

Submission status: Wrong Answer

Solution code:
from collections import deque


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

graph = [[] for i in range(n)]
for i in range(m):
    graph[info[i][0] - 1].append((info[i][1] - 1, info[i][2]))


# スタート地点からたどり着ける頂点を探す
def bfs1(start):
    q = deque([start])
    visited = [False] * n
    visited[start] = True
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            else:
                visited[i] = True
                q.append(i)
    return visited

visited_from_start = bfs1(0)
can_goal = [False] * n
can_goal[n-1] = True


# ある地点からゴールに着ける頂点を探す
def bfs2(start):
    if can_goal[start]:
        return
    q = deque([start])
    visited = [False] * n
    visited[start] = True
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            if i == n-1:
                can_goal[start] = True
                break
            else:
                visited[i] = True
                q.append(i)

for i in range(n)[::-1]:
    if visited_from_start[i]:
        bfs2(i)
# print(can_goal)


def bfs3(start):
    q = deque([(start, -1, 0, 0)])
    prev_pos_money = {}
    prev_pos_memo = {}
    while q:
        pos, prev_pos, t, mon = q.popleft()
        for next_pos, next_mon in graph[pos]:
            if not can_goal[next_pos]:
                continue
            if next_pos in prev_pos_memo:
                if pos in prev_pos_memo[next_pos]:
                    if (mon + next_mon) - (t+1)*p > prev_pos_money[next_pos][pos] - prev_pos_memo[next_pos][pos]*p:
                        return -1
                        exit()
                    else:
                        continue
                else:
                    prev_pos_memo[next_pos][pos] = -1
                    prev_pos_money[next_pos][pos] = 0
            else:
                prev_pos_memo[next_pos] = {}
                prev_pos_memo[next_pos][pos] = -1
                prev_pos_money[next_pos] = {}
                prev_pos_money[next_pos][pos] = 0
            if prev_pos_memo[next_pos][pos] == -1 or (mon + next_mon) - (t+1)*p > prev_pos_money[next_pos][pos] - prev_pos_memo[next_pos][pos]*p:
                prev_pos_memo[next_pos][pos] = t + 1
                prev_pos_money[next_pos][pos]= mon + next_mon
                q.append((next_pos, pos, t + 1, mon + next_mon))
    ans = 0
    for i in prev_pos_memo[n-1]:
        ans = max(ans, prev_pos_money[n-1][i] - prev_pos_memo[n-1][i]*p)
    return ans

print(bfs3(0))

Submission status: Wrong Answer

Solution code:
#単一始点最短経路問題
#負の辺があっても動作する

#最短経路を求める
#計算量O(N * M)

INF = 10 ** 9
#入力
# N = int(input()) #頂点の数
# M = int(input()) #辺の数
N, M, P = map(int, input().split())

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


#メイン文
d = [0] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        count += 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: #更新が終わったとき
            return True
        if count == N: #永遠に更新が起きているとき
            tmp = d[N -1]
        if count == N + 2:
            if d[N - 1] == tmp:
                return True #N-1の値が更新されていないとき
            else:
                return False

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

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

Submission status: Wrong Answer

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

for i in range(m):
    A[i][2] = - (A[i][2]-p)

#import numpy as np
# A = np.full(np.inf, (n+1, n+1))

# scipy.sparse.csgraph.bellman_ford


S = [10**13 for i in range(n+1)]

S[1]=0
for i in range(m):
    if A[i][0] == 1:
        S[A[i][1]]=A[i][2]

for j in range(n-1):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])

#print(S)
ans1 = -S[n]

for j in range(1):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])
#print(S)
ans2 = -S[n]

if ans1 != ans2:
    print(-1)
else:
    print(max(0, ans1))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1:
                if to != N-1:
                    print(-1)
                else:
                    print(max(0,-d[-1]))
                exit()

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

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


n, m, p = li()
edges = []
for _ in range(m):
    ai, bi, ci = li()
    ai -= 1
    bi -= 1
    edges.append((ai, bi, ci-p))

INF = 10**12
dist = [[-INF]*n for _ in range(n+1)]
dist[0][0] = 0

for i in range(n):
    for j in range(n):
        dist[i+1][j] = dist[i][j]

    for ai, bi, ci in edges:
        dist[i+1][bi] = max(dist[i+1][bi], dist[i][ai] + ci)

if dist[n-1][-1] < dist[n][-1]:
    print(-1)
else:
    print(max(0, dist[n-1][-1]))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1:
                if to == N-1:
                    print(-1)
                else:
                    print(max(0,-d[-1]))                    
                exit()

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

Submission status: Wrong Answer

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

E = [[0, 0, 0] for m in range(M)]
for m in range(M):
    A, B, C = map(int, input().split())
    E[m][0] = A - 1
    E[m][1] = B - 1
    E[m][2] = P - C


def BellmanFord(edges, num_v, source, end):
    inf = 10 ** 8
    dist = [inf for i in range(num_v)]
    dist[source] = 0
    parent = [-1 for i in range(num_v)]

    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                parent[edge[1]] = edge[0]

    end1 = dist[end]
    trace1 = []
    r = end
    for n in range(num_v):
        trace1.append(r)
        r = parent[r]
        if r == -1:
            break

    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                parent[edge[1]] = edge[0]

    end2 = dist[end]
    trace2 = []
    r = end
    for n in range(num_v):
        trace2.append(r)
        r = parent[r]
        if r == -1:
            break

    return max(0, -end1) if end1 == end2 and trace1 == trace2 else -1


res = BellmanFord(E, N, 0, N - 1)
print(res)

Submission status: Wrong Answer

Solution code:

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

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["second"] = -1
	tree[i]["score"] = 0
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

tree[0]["second"] = 1
stack = [0]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda"]:
		if tree[edge[1]]["reach"] == 1:
			if tree[edge[1]]["second"] == 1:
				if tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					print(-1)
					exit()
			else:
				tree[edge[1]]["score"] = max(tree[edge[1]]["score"], tree[edge[0]]["score"] + edge[2] - P)
				stack.append(edge[1])
				tree[edge[1]]["second"] = 1
print(max(tree[N - 1]["score"],0))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]

def sp(s,n,w,es):
  d=[float("inf")]*n
  d[s]=0
  count=0
  ret=[]
  while count<n*2:
    update=False
    for i in range(w):
      e=es[i]
      if d[e[0]]!=float("inf") and d[e[1]]>d[e[0]]+e[2]:
        d[e[1]]=d[e[0]]+e[2]
        update=True
    if not update:
      ret.append(d[-1])
      ret.append(d[-1])
      break
    count+=1
    if count>=2*n-1:
      ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Wrong Answer

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

for i in range(m):
    A[i][2] = - (A[i][2]-p)

#import numpy as np
# A = np.full(np.inf, (n+1, n+1))

# scipy.sparse.csgraph.bellman_ford


S = [10**10 for i in range(n+1)]

S[1]=0
for i in range(m):
    if A[i][0] == 1:
        S[A[i][1]]=A[i][2]

for j in range(n-1):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])

#print(S)
ans1 = -S[n]

for j in range(1):
    for i in range(m):
        S[A[i][1]] = min(S[A[i][1]], S[A[i][0]]+A[i][2])
#print(S)
ans2 = -S[n]

if ans1 != ans2:
    print(-1)
else:
    print(max(0, ans1))

Submission status: Wrong Answer

Solution code:
#単一始点最短経路問題
#負の辺があっても動作する

#最短経路を求める
#計算量O(N * M)

INF = 10 ** 15
#入力
# N = int(input()) #頂点の数
# M = int(input()) #辺の数
N, M, P = map(int, input().split())

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


#メイン文
d = [0] * N #最短距離を記録しておくリスト
# prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        count += 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: #更新が終わったとき
            return True
        if count == N + 1: #永遠に更新が起きているとき
            tmp = d[N -1]
        if count == N + 2:
            if d[N - 1] == tmp:
                return True #N-1の値が更新されていないとき
            else:
                return False #N + 2回目でもN - 1の値が小さくなっている-->得点が無限に大きくなる

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

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

Submission status: Wrong Answer

Solution code:
INF = 10**18
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n + 10):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update > 2:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

Solution code:

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

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["second"] = -1
	tree[i]["score"] = 0
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

tree[0]["second"] = 1
stack = [0]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda"]:
		if tree[edge[1]]["reach"] == 1:
			if tree[edge[1]]["second"] == 1:
				if tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					print(-1)
					exit()
			else:
				tree[edge[1]]["score"] = max(tree[edge[0]]["score"], tree[edge[0]]["score"] + edge[2] - P)
				stack.append(edge[1])
				tree[edge[1]]["second"] = 1
print(max(tree[N - 1]["score"],0))

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

import collections


class BellmanFord():
    def __init__(self):
        self.edges = []

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges.append([u, v, d])
            self.edges.append([v, u, d])
        else:
            self.edges.append([u, v, d])

    def BellmanFord_search(self, s):
        """
        次のBellmanFord_negative_boolまで考慮した時には、0-indexedであることに注意
        s =  始点
        return: d[i] 始点sから各点iまでの最短経路
        """
        d = collections.defaultdict(lambda: float('inf'))
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def BellmanFord_negative_bool(self, numNodes, zero_indexed=False):
        # 負の閉路の検出, Trueなら負の閉路が存在する
        d = collections.defaultdict(lambda: float('inf'))
        d[0] = 0
        numEdges = len(self.edges)
        for i in range(numNodes):
            for j in range(numEdges):
                e = self.edges[j]
                if d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    if i == numNodes-1:
                        return True
        return False

n,m,p = na()
g = BellmanFord()

for i in range(m):
    a,b,c = na()
    c -= p
    g.add(a-1,b-1,-c,True)

if g.BellmanFord_negative_bool(n):
    print(-1)
    exit()

u = g.BellmanFord_search(0)
print(u[n-1])

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    INF = 10**15
    V = [INF]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    ans = V[N-1]
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    if ans > 0:
        print(0)
        return
    if V[N-1] < ans:
        print(-1)
        return
    print( max(-ans,0))
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def BellmanFord(edges,num_v,source):
    #グラフの初期化
    inf=float("inf")
    dist=[inf for i in range(num_v)]
    dist[source-1]=0
    
    #辺の緩和
    for i in range(num_v):
      for edge in edges:
        if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
          dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
          if i==num_v-1 and edge[1]==num_v: return -1
    
    return dist

N, M, P = map(int, input().split())
edges = []
for m in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, -(C-P)])
dist = BellmanFord(edges, N, 1)
if dist == -1:
    print(-1)
else:
    print(max(-dist[N-1], 0))

Submission status: Wrong Answer

Solution code:
words = lambda t : list(map(t, input().split()))
n,m,p = words(int)

def bellman_ford(edges, numv, stt):
  #グラフの初期化
  inf = float("inf")
  dist = [inf for i in range(numv)]
  dist[stt - 1] = 0

  for i in range(numv):
    for (f,t,c) in edges:
      if dist[t-1] > dist[f-1] + c:
        dist[t-1] = dist[f-1] + c
        if i==numv-1:
          #print(dist)
          return (-1, dist)

  return (0, dist)


edges = []
for i in range(m):
    a,b,c = words(int)
    edges.append((a,b,-c+p))

ans = bellman_ford(edges, n, 1)
if ans[0] == -1 and ans[1][n-1] == float("inf"):
    print(-1)
else:
    print(max(0,-ans[1][n-1]))

Submission status: Wrong Answer

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

graph = {i:[] for i in range(1,N+1)}

d = [[-10**5] * (N+1) for i in [0]*(N+1)]
for i in [0]*M:
	a,b,c = map(int,input().split(' '))
	d[a][b] = c - P

for k in range(1,N+1):
	for i in range(1,N+1):
		for j in range(1,N+1):
			d[i][j] = max(d[i][j], d[i][k] + d[k][j])

for i in range(1,N+1):
	if d[i][i] > 0:
		print(-1)
		exit()

m = 0
for ds in d:
	m = max(m,max(ds))
print(m)

Submission status: Wrong Answer

Solution code:
INF = 10**18
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n + 10):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update > n:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

Solution code:
def main():
    N, M, P = map(int, input().split())
    Edge = []
    for i in range(M):
        a, b, c = map(int, input().split())
        a, b = a - 1, b - 1
        c -= P
        c = -c
        Edge.append([a, b, c])

    # ベルマンフォード
    dist = [float('inf')] * N
    dist[0] = 0

    for i in range(2 * N):
        for fr, to, cost in Edge:
            if (dist[fr] != float('inf')) and (dist[to] > dist[fr] + cost):
                dist[to] = dist[fr] + cost
                if (i == N - 1) & (to == N - 1):
                    print(-1)
                    exit()

    print(max(0, -dist[N - 1]) if -dist[N - 1] != float('inf') else 0)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
INF = 10**18
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n + 10):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update > m:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]

def sp(s,n,w,es):
  d=[float("inf")]*n
  d[s]=0
  count=0
  ret=[]
  while count<n+2:
    update=False
    for i in range(w):
      e=es[i]
      if d[e[0]]!=float("inf") and d[e[1]]>d[e[0]]+e[2]:
        d[e[1]]=d[e[0]]+e[2]
        update=True
    if not update:
      ret.append(d[-1])
      ret.append(d[-1])
      break
    count+=1
    if count>=n+1:
      ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


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


def read_float():
    return float(input())


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


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+1):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        return 'inf'
                    dist[v] = dist[u] + g[u][v]
                    pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):

    g =defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    def r(s):
        q = [s]
        done = set()
        done.add(s)
        while q:
            v = q.pop()
            for u in g[v]:
                if u not in done:
                    q.append(u)
                    done.add(u)
        return N in done, done

    _, r1 = r(1)
    for i in range(2, N):
        if i not in r1 and i in g:
            g.pop(i)

    d = set()
    for i in range(2, N):
        a, _ = r(i)
        if not a:
            d.add(i)
    
    for i in d:
        g.pop(i)
    for k, v in g.items():
        for i in d:
            if i in v:
                v.pop(i)
    d = BellmanFord(g, 1)
    if d == 'inf':
        return -1
    return max(0, -d[N])


def main():
    N, M, P = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    print(slv(N, M, P, ABC))

    # N = 2500
    # M = 5000
    # P = random.randint(0, 10**5)
    # P= 0
    # ABC = [
    #     [random.randint(1, N), random.randint(1, N), random.randint(1, 10**5)] for _ in range(M)
    # ]
    # print(slv(N, M, P, ABC))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1 and fr == N-1:
                print(-1)
                exit()

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

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1:
                print(-1)
                exit()

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

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


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


def read_float():
    return float(input())


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


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+1):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        return 'inf'
                    dist[v] = dist[u] + g[u][v]
                    pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):

    g =defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    def r(s):
        q = [s]
        done = set()
        done.add(s)
        while q:
            v = q.pop()
            for u in g[v]:
                if u not in done:
                    q.append(u)
                    done.add(u)
        return N in done, done

    _, r1 = r(1)
    for i in range(2, N):
        if i not in r1 and i in g:
            g.pop(i)

    d = set()
    for i in range(2, N):
        a, _ = r(i)
        if not a:
            d.add(i)
    
    for i in d:
        g.pop(i)
    for k, v in g.items():
        for i in d:
            if i in v:
                v.pop(i)
    d = BellmanFord(g, 1)
    if d == 'inf':
        return -1
    return max(0, -d[N])


def main():
    N, M, P = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    print(slv(N, M, P, ABC))

    # N = 100
    # M = 5000
    # P = random.randint(0, 10**5)
    # P= 0
    # ABC = [
    #     [random.randint(1, N), random.randint(1, N), random.randint(1, 10**5)] for _ in range(M)
    # ]
    # print(slv(N, M, P, ABC))



if __name__ == '__main__':
    main()