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 = [ int(v) for v in input().split() ]
node_list = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
distance_list = [ 10**15 for i in range(n) ]
parent_list = [ -1 for i in range(n) ]

distance_list[0] = 0
parent_list[0] = -1


turn = 0
for i in range(n+1):
    turn += 1 
    change_log = 0
    new_distanece_list = distance_list
    for j in node_list:
        a, b, c = j
        if distance_list[a] != 10**15:
            if new_distanece_list[b] > distance_list[a] + c:
                new_distanece_list[b] = distance_list[a] + c
                parent_list[b] = a
                change_log = 1
    distance_list = new_distanece_list

    
def parent(a):
    for i in range(n-1):
        if a == parent_list[a] or a == -1:
            break
        else:
            b = parent_list[a]
            a = b
    return a


if parent(n-1) == -1:
    print(max(-distance_list[-1],0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def shortest_path(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    for _ in [0]*n:
        update = False
        for p,q,r in es:
            # e: 辺iについて [from,to,cost]
            if d[p] != float("inf") and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
        if not update:
            break
    return d

def main():
    import sys
    input = sys.stdin.readline
    n,m,p = map(int,input().split())
    es = []
    for _ in range(m):
        a,b,c = map(int,input().split())
        es.append([a-1,b-1,p-c])

    d = shortest_path(0,n,m,es)

    kouho = d[-1]

    updata = True
    for _ in [0]*n:
        update = False
        for p,q,r in es:
            # e: 辺iについて [from,to,cost]
            if d[p] != float("inf") and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
        if not update:
            break

    res = d[-1]

    if kouho >= 0:
        print(0)
    elif kouho == res:
        print(max(0,-res))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
    
import sys
INT_MAX = sys.maxsize # 9223372036854775807        
    
def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    #辺の緩和
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                if dist[edge[0]] != INT_MAX:
                    dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for i in range(num_v):
        for from_edge, to_edge, cost in edges:
            if dist[from_edge] == INT_MAX:
                continue
            if dist[to_edge] > dist[from_edge] + cost:
                dist[to_edge] = dist[from_edge] + cost
                negative[to_edge] = True
            
            if negative[from_edge] == INT_MAX:
                negative[to_edge] = True
    for i, d in enumerate(dist):
        if d >=INT_MAX:
            dist[i] = INT_MAX
            negative[i] = False
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
rev_shortest_path = bellman_ford(edges, N+1, N)
ans = -1 * shortest_path[N]
rev = -1 * rev_shortest_path[1]
#print(shortest_path)
if ans == INT_MAX or ans == -INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
def shortest_path(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    for _ in range(n+1):
        updata = False
        for p,q,r in es:
            # e: 辺iについて [from,to,cost]
            if d[p] != float("inf") and d[q] > d[p] + r:
                d[q] = d[p] + r
                updata = True
        if not updata:
            break
    return d

def main():
    import sys
    input = sys.stdin.readline
    n,m,p = map(int,input().split())
    es = []
    for _ in range(m):
        a,b,c = map(int,input().split())
        es.append([a-1,b-1,p-c])

    d = shortest_path(0,n,m,es)

    kouho = d[-1]

    for _ in range(5):
        updata = True
        for i in range(m):
            e = es[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]
                updata = True
        if not updata:
            break

    res = d[-1]
    if kouho >= 0:
        print(0)
    elif kouho == res:
        print(max(0,-res))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def shortest_path(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    for _ in range(n+1):
        updata = False
        for p,q,r in es:
            # e: 辺iについて [from,to,cost]
            if d[p] != float("inf") and d[q] > d[p] + r:
                d[q] = d[p] + r
                updata = True
        if not updata:
            break
    return d

def main():
    import sys
    input = sys.stdin.readline
    n,m,p = map(int,input().split())
    es = []
    for _ in range(m):
        a,b,c = map(int,input().split())
        es.append([a-1,b-1,p-c])

    d = shortest_path(0,n,m,es)

    kouho = d[-1]

    for _ in range(5):
        updata = True
        for i in range(m):
            e = es[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]
                updata = True
        if not updata:
            break

    res = d[-1]

    if kouho == res:
        print(max(0,-res))
    else:
        print(-1)

if __name__ == '__main__':
    main()

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())


def dfs(graph: list, node: int, start: int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF] * node

    # 始点ノードの距離を0とし、dfsのためのstackを作成
    dist[start] = 0
    stack = [(0, start)]

    while stack:
        cost, cur_node = stack.pop()

        # 未探索のノードをstackに入れる
        for nex_cost, nex_node in graph[cur_node]:
            if dist[nex_node] != INF:
                continue
            else:
                dist[nex_node] = dist[cur_node] + nex_cost
                stack.append((dist[nex_node], nex_node))

    return dist


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

# グラフ構築
one2n = [[] for _ in range(n)]
n2one = [[] for _ in range(n)]
for ai, bi, _ in edges:
    one2n[ai].append((ci-p, bi))
    n2one[bi].append((ci-p, ai))

# 1から到達可能な点を抽出
one2n_dist = dfs(one2n, n, 0)
one2n_reachable = set()
for i, di in enumerate(one2n_dist):
    if di != float('inf'):
        one2n_reachable.add(i)

# Nから到達可能な点を抽出
n2one_dist = dfs(n2one, n, n-1)
n2one_reachable = set()
for i, di in enumerate(n2one_dist):
    if di != float('inf'):
        n2one_reachable.add(i)

one2n_path = one2n_reachable & n2one_reachable


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

for _ in range(n):
    for ai, bi, ci in edges:
        if ai in one2n_path and bi in one2n_path and dist[ai] + ci > dist[bi]:
            dist[bi] = dist[ai] + ci

aftern = dist[n-1]

for _ in range(n):
    for ai, bi, ci in edges:
        if ai in one2n_path and bi in one2n_path and dist[ai] + ci > dist[bi]:
            dist[bi] = dist[ai] + ci

after2n = dist[n-1]

# N回更新と2N回更新を比較
# 2N回で更新されていれば-1
if after2n > aftern:
    print(-1)
else:
    print(max(0, aftern))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
    
import sys
INT_MAX = sys.maxsize # 9223372036854775807        
    
def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    #辺の緩和
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                if dist[edge[0]] != INT_MAX:
                    dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for i in range(num_v):
        for from_edge, to_edge, cost in edges:
            if dist[from_edge] == INT_MAX:
                continue
            if dist[to_edge] > dist[from_edge] + cost:
                dist[to_edge] = dist[from_edge] + cost
                negative[to_edge] = True
            
            if negative[from_edge] == INT_MAX:
                negative[to_edge] = True
    for i, d in enumerate(dist):
        if d >=INT_MAX:
            dist[i] = INT_MAX
            negative[i] = False
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
            
    # 経路が存在しなければ距離をINT_MAXにする

    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
rev_shortest_path = bellman_ford(edges, N+1, N)
ans = -1 * shortest_path[N]
rev = -1 * rev_shortest_path[1]
#print(shortest_path)
if ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

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 = [INF] * N #最短距離を記録しておくリスト
prev = [-1] * N

def restore(g): #gまでの最短経路を復元
    path = []
    g -= 1 #0-indexに直す
    path.append(g)
    g = prev[g]
    count = 0
    while g != -1:
        # print ('C')
        path.append(g)
        g = prev[g]
        count += 1
        if count == N + 2:
            break
    path.reverse()
    return path

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        if count == N:
            path = restore(N)
            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]
                    if e[1] in path:
                        return False
                    update = True
                    prev[e[1]] = e[0]
            return 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 not shortest_path(1):
    print (-1)
    # print (d)
    exit()
# print (d)

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

Submission status: Wrong Answer

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

N, M, P = [int(item) for item in input().split()]

from collections import defaultdict
next_b = defaultdict(lambda: [])

for i in range(M):
    a, b, c = [int(item) for item in input().split()]
    next_b[a].append([b, c - P])

max_sc = [0] + [-int(1e10)] * (N - 1)
prev_sc = [0] + [-int(1e10) - 1] * (N - 1)

for loop in range(N):
    if max_sc == prev_sc:
        print(max(max_sc[N - 1], 0))
        break
    prev_sc = copy.deepcopy(max_sc)
    for i in range(N):
        for d, scr in next_b[i + 1]:
            max_sc[d - 1] = max(prev_sc[i] + scr, max_sc[d - 1])
    if loop == N - 1:
        max_sc_n = copy.deepcopy(max_sc)
else:
    if max_sc_n[N - 1] == max_sc[N - 1]:
        print(max(0, max_sc[N - 1]))
    else:
        print(-1)

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 == 5 * N:
            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 = float("inf")

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

edges = []
d = [inf for _ in range(n)]
d[0] = 0

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

for i in range(n-1):
    for e in edges:
        a, b, c = e
        if d[a] + c < d[b]:
            d[b] = d[a] + c

for e in edges:
    a, b, c = e
    if d[a] + c < d[b]:
        d[b] = -inf
    if d[b] == -inf and b == n-1:
        print(-1)
        exit()


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

Submission status: Wrong Answer

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

N, M, P = [int(item) for item in input().split()]

from collections import defaultdict
next_b = defaultdict(lambda: [])

for i in range(M):
    a, b, c = [int(item) for item in input().split()]
    next_b[a].append([b, c - P])

max_sc = [0] + [-int(1e10)] * (N - 1)
prev_sc = [0] + [-int(1e10) - 1] * (N - 1)

for loop in range(2 * N):
    if max_sc == prev_sc:
        print(max(max_sc[N - 1], 0))
        break
    prev_sc = copy.deepcopy(max_sc)
    for i in range(N):
        for d, scr in next_b[i + 1]:
            max_sc[d - 1] = max(prev_sc[i] + scr, max_sc[d - 1])
    if loop == N:
        max_sc_n = copy.deepcopy(max_sc)
else:
    if max_sc_n[N - 1] == max_sc[N - 1]:
        print(max(0, max_sc[N - 1]))
    else:
        print(-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]
d=[float("inf")]*n
d[0]=0

for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    d[e1]=min(d[e1],d[e0]+e2)
ans1=d[-1]
chk=False
for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    d[e1]=min(d[e1],d[e0]+e2)
    if d[-1]!=ans1:
      chk=True

print(-1 if chk==True else max(0,-ans1))

Submission status: Wrong Answer

Solution code:

n, m, p = [ int(v) for v in input().split() ]
node_list = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
distance_list = [ 10**15 for i in range(n) ]
parent_list = [ -1 for i in range(n) ]

distance_list[0] = 0
parent_list[0] = -1


turn = 0
for i in range(n+1):
    turn += 1 
    change_log = 0
    for j in node_list:
        a, b, c = j
        if distance_list[a] != 10**15:
            if distance_list[b] > distance_list[a] + c:
                distance_list[b] = distance_list[a] + c
                parent_list[b] = a
                change_log = 1

    


def parent(a):
    for i in range(n-1):
        if a == parent_list[a] or a == -1:
            break
        else:
            b = parent_list[a]
            a = b
    return a


if parent(n-1) == -1:
    print(max(-distance_list[-1],0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline
n,m,p=map(int,input().split())
graph=[]
gappend=graph.append
for _ in range(m):
    a,b,c=map(int,input().split())
    gappend([a-1,b-1,p-c])
points=[float("inf")]*n
points[0]=0
for _ in range(n-1):
    for i in range(m):
        if points[graph[i][1]]>points[graph[i][0]]+graph[i][2]:
            points[graph[i][1]]=points[graph[i][0]]+graph[i][2]
score=max(0,-points[n-1])
for _ in range(n-1):
    for i in range(m):
        if points[graph[i][1]]>points[graph[i][0]]+graph[i][2]:
            points[graph[i][1]]=points[graph[i][0]]+graph[i][2]
newscore=max(0,-points[n-1])
if score<newscore:
    print(-1)
else:
    print(score)

Submission status: Wrong Answer

Solution code:
n, m, p = [ int(v) for v in input().split() ]
node_list = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
distance_list = [ 10**15 for i in range(n) ]
parent_list = [ -1 for i in range(n) ]

distance_list[0] = 0
parent_list[0] = -1


turn = 0
for i in range(n+1):
    turn += 1 
    change_log = 0
    for j in node_list:
        a, b, c = j
        if distance_list[a] != 10**15:
            if distance_list[b] > distance_list[a] + c:
                distance_list[b] = distance_list[a] + c
                parent_list[b] = a
                change_log = 1
    if change_log == 0:
        break
    


def parent(a):
    for i in range(n-1):
        if a == parent_list[a] or a == -1:
            break
        else:
            b = parent_list[a]
            a = b
    return a


if parent(n-1) == -1:
    print(max(-distance_list[-1],0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
##speedtest##
import sys
input=sys.stdin.readline
n,m,p=map(int,input().split())
graph=[]
gappend=graph.append
for _ in range(m):
    a,b,c=map(int,input().split())
    gappend([a-1,b-1,p-c])
points=[float("inf")]*n
points[0]=0
for _ in range(n-1):
    for i in range(m):
        if points[graph[i][1]]>points[graph[i][0]]+graph[i][2]:
            points[graph[i][1]]=points[graph[i][0]]+graph[i][2]
score=max(0,-points[n-1])
newpoints=points
for i in range(m):
    if newpoints[graph[i][1]]>newpoints[graph[i][0]]+graph[i][2]:
        newpoints[graph[i][1]]=newpoints[graph[i][0]]+graph[i][2]
newscore=max(0,-points[n-1])
if score<newscore:
    print(-1)
else:
    print(score)

Submission status: Wrong Answer

Solution code:
n,m,p=map(int,input().split())
graph=[]
gappend=graph.append
for _ in range(m):
    a,b,c=map(int,input().split())
    gappend([a-1,b-1,p-c])
points=[float("inf")]*n
points[0]=0
for _ in range(n-1):
    for i in range(m):
        if points[graph[i][1]]>points[graph[i][0]]+graph[i][2]:
            points[graph[i][1]]=points[graph[i][0]]+graph[i][2]
score=max(0,-points[n-1])
newpoints=points
for i in range(m):
    if newpoints[graph[i][1]]>newpoints[graph[i][0]]+graph[i][2]:
        newpoints[graph[i][1]]=newpoints[graph[i][0]]+graph[i][2]
newscore=max(0,-points[n-1])
if score<newscore:
    print(-1)
else:
    print(score)

Submission status: Wrong Answer

Solution code:

n, m, p = [ int(v) for v in input().split() ]
node_list = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
distance_list = [ 10**10 for i in range(n) ]
parent_list = [ None for i in range(n) ]

distance_list[0] = 0
parent_list[0] = -1


turn = 0
for i in range(n+1):
    turn += 1 
    change_log = 0
    for j in node_list:
        a, b, c = j
        if distance_list[b] > distance_list[a] + c:
            distance_list[b] = distance_list[a] + c
            parent_list[b] = a
            change_log = 1
    if change_log == 0:
        break

def parent(a):
    for i in range(n-1):
        if a == parent_list[a] or a == -1:
            break
        else:
            b = parent_list[a]
            a = b
    return a


if parent(n-1) == -1:
    print(max(-distance_list[-1],0))
else:
    print(-1)

Submission status: Wrong Answer

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

def main():
    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,P-C])

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    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]
    ans = -1*dist[N-1]
    
    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]
    ans2 = -1*dist[N-1]

    if ans2<=ans: 
        print(max(0,ans))         
    else:
        print(-1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque


def bellman_ford(N, adj, start):
    ans = [float("inf")] * N
    q = deque()
    q.append((start, 0, {}))
    while len(q):
        i, cost, history = q.popleft()
        if cost >= ans[i]:
            continue
        ans[i] = cost
        history = {k: history[k] for k in history}
        history[i] = cost
        for j in adj[i]:
            ncost = cost + adj[i][j]
            if j in history and history[j] > ncost:
                ncost = -float("inf")
            q.append((j, ncost, history))
    return ans


def main():
    N, M, P = map(int, input().split())
    adj = [{} for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        adj[A-1][B-1] = P-C
    costs = bellman_ford(N, adj, 0)
    ans = -costs[N-1]
    if ans < 0:
        print(0)
    elif ans == float("inf"):
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
    
import sys
INT_MAX = sys.maxsize # 9223372036854775807

def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    #辺の緩和
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for i in range(num_v):
        for from_edge, to_edge, cost in edges:
            if dist[from_edge] == INT_MAX:
                continue
            if dist[to_edge] > dist[from_edge] + cost:
                dist[to_edge] = dist[from_edge] + cost
                negative[to_edge] = True
            
            if negative[from_edge] == INT_MAX:
                negative[to_edge] = True
                
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
        
    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
rev_shortest_path = bellman_ford(edges, N+1, N)
ans = -1 * shortest_path[N]
rev = -1 * rev_shortest_path[1]
if (ans < 0 and rev+ans > 0) or ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
    
import sys
INT_MAX = sys.maxsize # 9223372036854775807

def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    #辺の緩和
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for i in range(num_v):
        for from_edge, to_edge, cost in edges:
            if dist[from_edge] == INT_MAX:
                continue
            if dist[to_edge] > dist[from_edge] + cost:
                dist[to_edge] = dist[from_edge] + cost
                negative[to_edge] = True
            
            if negative[from_edge] == INT_MAX:
                negative[to_edge] = True
                
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
        
    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
rev_shortest_path = bellman_ford(edges, N+1, N)
ans = -1 * shortest_path[N]
rev = -1 * rev_shortest_path[1]
if (ans > 0 and rev > 0) or ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a, b, c))
    
import sys
INT_MAX = sys.maxsize # 9223372036854775807

def bellman_ford(edges,num_v,source):

    dist=[INT_MAX] * num_v
    dist[source]=0

    #辺の緩和
    has_negative = False
    for i in range(num_v):
        for edge in edges:
            if edge[0] != INT_MAX and dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                if i==num_v-1:
                    has_negative = True
    
    if has_negative == False:
        return dist
    
    negative = [False] * num_v
    for i in range(num_v):
        for from_edge, to_edge, cost in edges:
            if dist[from_edge] == INT_MAX:
                continue
            if dist[to_edge] > dist[from_edge] + cost:
                dist[to_edge] = dist[from_edge] + cost
                negative[to_edge] = True
            
            if negative[from_edge] == INT_MAX:
                negative[to_edge] = True
                
    for i, is_negative in enumerate(negative):
        if is_negative:
            dist[i] = -1 * INT_MAX
        
    return dist

edges = ABC[:]
edges = [(a, b, -c+P) for a, b, c in edges]

shortest_path = bellman_ford(edges, N+1, 1)
rev_shortest_path = bellman_ford(edges, N+1, N)
ans = -1 * shortest_path[N]
rev = -1 * rev_shortest_path[1]
if rev > 0 or ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
INF = pow(10, 15)

def main():
  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, p-c))  # 辺の重みの正負反転（最長路→最短路にしたいので）

  dist = [INF for _ in range(n)]
  frome = [-1 for _ in range(n)]
  dist[0] = 0
  for _ in range(n):
    for edge in edges:
      if dist[edge[0]] == INF:
        continue
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        frome[edge[1]] = edge[0]

  fromd = {}
  f = n-1
  while frome[f] != -1:
    if f in fromd:
      break
    fromd[f] = frome[f]
    f = frome[f]

  is_loop = False
  for edge in edges:
    if dist[edge[1]] > dist[edge[0]] + edge[2]:
      if edge[0] in fromd:
        is_loop = True
        break

  if is_loop:
    print(-1)
  else:
    if dist[-1] > 0:
      print(0)
    else:
      print(-dist[-1])


if __name__ == '__main__':
  main()