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: Accepted

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 == 2 * 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: Accepted

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 * 2):
    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]))
        exit()
else:
    if terminal_update > 1:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Accepted

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:
                    before_dist = dist[num_v-1]
                    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 before_dist != dist[num_v-1]:
                        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: Accepted

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(n):
    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: Accepted

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 ** 12
    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 + 10):
        trace2.append(r)
        r = parent[r]
        if r == -1:
            break

    if trace2[-1] != source:
        return -1

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


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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

from itertools import accumulate
from bisect import bisect, bisect_left
from collections import Counter, deque, defaultdict
from functools import reduce
from itertools import accumulate
from operator import itemgetter, xor
from string import ascii_lowercase as abc

from sys import setrecursionlimit
setrecursionlimit(10**9)
 
import sys
#input = sys.stdin.readline
from collections import Counter
def inpl(): return list(map(int, input().split()))

N, M, P = inpl()
INF = 10**12
G = [[] for _ in range(N)]
E = []
G2 = [[] for _ in range(N)]
rG2 = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = inpl()
    G[a-1].append([b-1, -c+P])
    G2[a-1].append(b-1)
    rG2[b-1].append(a-1)
    E.append([a-1, b-1, -c+P])


def SCC(G, rG):
    N = len(G)
    def dfs(i):
        nonlocal t, rorder, searched
        searched[i] = True
        for j in G[i]:
            if not searched[j]:
                dfs(j)
        rorder[t] = i
        t += 1

    def rdfs(i):
        nonlocal t, group, g
        group[i] = g
        for j in rG[i]:
            if group[j] == -1:
                rdfs(j)

    t = 0
    rorder = [-1]*N
    searched = [0]*N
    group = [-1]*N

    for i in range(N):
        if not searched[i]:
            dfs(i)
    g = 0
    for i in range(N-1, -1, -1):
        if group[rorder[i]] == -1:
            rdfs(rorder[i])
            g += 1
    return group, g


def belman_ford(V, edges, r):
    "If glaph contains negative cycles then return True"
    D = [INF]*(V)
    D[r] = 0
    if V == 1:
        return False, [0]
    OK = True
    for _ in range(V-1):
        update = False
        for s, t, d in edges:
            if D[t] > D[s] + d:
                D[t] = D[s] + d
                update = True
        if not update:
            OK = False
    return OK, D

group, gsize = SCC(G2, rG2)
groups = [[] for _ in range(gsize)]
for i in range(N):
    groups[group[i]].append(i)

score = [10**12 for _ in range(N)]
negative_groups = [0]*N


for g in range(gsize):
    ggs = set(groups[g])
    s = groups[g][0]
    score[s] = 0
    Q = deque([s])
    while Q:
        p = Q.popleft()
        for q, c in G[p]:
            if not q in ggs:
                continue
            if score[p] + c < score[q]:
                score[q] = score[p] + c
                Q.append(q)
        if score[s] < 0:
            for g in ggs:
                negative_groups[g] = 1
            break

s = 0
Q = deque([s])
reach1 = [0]*N
reach1[0] = 1

while Q:
    p = Q.popleft()
    for q in G2[p]:
        if not reach1[q]:
            reach1[q] = 1
            Q.append(q)

s = N-1
Q = deque([s])
reachN = [0]*N
reachN[-1] = 1

while Q:
    p = Q.popleft()
    for q in rG2[p]:
        if not reachN[q]:
            reachN[q] = 1
            Q.append(q)

NEGATIVE, D = belman_ford(N, E, 0)

if any([reach1[i]&reachN[i]&negative_groups[i] for i in range(N)]) or reach1[-1]==0:
    print(-1)
else:
    print(max(0, -D[-1]))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)

def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math
import queue

NINF = -1000000000

def reachable(n, vtxs):
    visited = [0 for i in range(n)]
    visited[0] = 1

    qu = queue.Queue()
    qu.put(0)
    while(not qu.empty()):
        curr = qu.get()
        for next in vtxs[curr]:
            if visited[next] == 0:
                visited[next] = 1
                qu.put(next)

    return visited

def reachable_rev(n, revs):
    visited = [0 for i in range(n)]
    visited[n-1] = 1
    qu = queue.Queue()
    qu.put(n - 1)
    while(not qu.empty()):
        curr = qu.get()
        for next in revs[curr]:
            if visited[next] == 0:
                visited[next] = 1
                qu.put(next)

    return visited



def bellman(n, m, edges, vtxs, revs):
    cost = [NINF for i in range(n)]
    cost[0] = 0
    tgts = [0]
    loop = 0
    final = False
    reach = reachable(n, vtxs)
    revreach = reachable_rev(n, revs)
    while(True):
        flag = False
        if loop > n:
            final = True
            break
        for e in edges:
            # print(e, cost)
            if cost[e[1]] < cost[e[0]] + e[2]:
                point = e[1]
                ppoint = e[0]
                # print("point", point)
                if reach[point] and revreach[point]:
                    if reach[ppoint] and revreach[ppoint]:
                        cost[e[1]] = cost[e[0]] + e[2]
                        flag = True
                        # print("update")
        if not flag:
            break
        loop += 1
        # print("loop", loop, cost)


    # print("judge", reach, revreach)
    if final:
        for e in edges:
            # print(e, cost)
            if cost[e[1]] < cost[e[0]] + e[2]:
                point = e[1]
                ppoint = e[0]
                # print("point", point)
                if reach[point] and revreach[point]:
                    if reach[ppoint] and revreach[ppoint]:
                        return -1

    if reach[-1] == 0:
        return -1

    return max(0, cost[-1])

n, m , p= getList()
vtxs = [[] for i in range(n)]
revs = [[] for i in range(n)]
edges = []

for i in range(m):
    a, b, c = getList()
    vtxs[a-1].append(b-1)
    revs[b-1].append(a-1)
    edges.append((a-1, b-1, c - p))

# print(edges)
print(bellman(n, m, edges, vtxs, revs))

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'


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 ans!=dist[n-1]:
            0#return 'neg'
    ans=dist[n-1]
  return dist

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
    while True:
        updata = False
        for i in range(w):
            e = es[i]
            ans=d[n-1]
            # 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
    return d

n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    #g.append((a-1,b-1,p-c))
    g.append((a,b,p-c))
    

di=BellmanFord(g,n,1)
ans=di[n-1]
di_2=BellmanFord(g,n*2,1)

if ans!=di_2[n-1]:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 5 + 5)


def omit(n, links, parents):
    q = [0]
    visited_f = [False] * n
    while q:
        v = q.pop()
        if visited_f[v]:
            continue
        visited_f[v] = True
        q.extend(u for u in links[v] if not visited_f[u])

    q = [n - 1]
    visited_b = [False] * n
    while q:
        v = q.pop()
        if visited_b[v]:
            continue
        visited_b[v] = True
        q.extend(u for u in parents[v] if not visited_b[u])

    remains = [i for i, (f, b) in enumerate(zip(visited_f, visited_b)) if f and b]
    sr = set(remains)
    for v in remains:
        links[v] &= sr

    return remains


n, m, p = list(map(int, input().split()))
INF = 10 ** 12
costs = [[INF] * n for _ in range(n)]
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    parents[b].add(a)
    costs[a][b] = min(costs[a][b], p - c)
remains = omit(n, links, parents)

dist = [INF] * n
dist[0] = 0
for _ in range(n + 1):
    updated = False
    for v in remains:
        d = dist[v]
        if d == INF:
            continue
        cv = costs[v]
        for u in links[v]:
            if dist[u] > d + cv[u]:
                dist[u] = d + cv[u]
                updated = True
    # print(dist, updated)
    if not updated:
        break
else:
    print(-1)
    exit()

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

Submission status: Accepted

Solution code:
inf = 10 ** 18
n, m, p = map(int, input().split())
edge = []
d = [inf] * n
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = p - c
    edge.append((a, b, c))
d[0] = 0
for i in range(n-1):
    pre = d[n-1]
    for a, b, c in edge:
        if (d[a] != inf and d[b] > d[a] + c):
            d[b] = d[a] + c
            update = True

pre = d[n-1]
for i in range(n-1):
    for a, b, c in edge:
        if (d[a] != inf and d[b] > d[a] + c):
            d[b] = d[a] + c

if pre != d[n-1]:
    print(-1)
else:
    print(max(0, -d[n-1]))

Submission status: Accepted

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

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

for i in range(M):
    EDGE[i][2]-=P

from collections import deque

Q=deque([1])

ANS=[-float("inf")]*(N+1)
ANS[1]=0

for i in range(N+1):
    for a,b,p in EDGE:
        if ANS[a]+p>ANS[b]:
            ANS[b]=ANS[a]+p
    
#print(max(ANS[N],0))


import copy
ANS2=copy.deepcopy(ANS)

for i in range(N+1):
    for a,b,p in EDGE:
        if ANS2[a]+p>ANS2[b]:
            ANS2[b]=ANS2[a]+p
    
#print(max(ANS2[N],0))

if ANS[N]<ANS2[N]:
    print(-1)
else:
    print(max(ANS2[N],0))

Submission status: Accepted

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

ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    ABC.append((a - 1, b - 1, P - c))

inf = float("inf")
d = [inf] * N
d[0] = 0

# Bellman-Ford
for i in range(N):
    for a, b, c in ABC:
        if d[b] <= d[a] + c:
            continue
        d[b] = d[a] + c
ans = d[N - 1]
for i in range(N):
    for a, b, c in ABC:
        if d[b] <= d[a] + c:
            continue
        d[b] = d[a] + c
if ans != d[N - 1]:
    print(-1)
else:
    print(max(0, -d[N - 1]))

Submission status: Accepted

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

Edgeinv = [[] for _ in range(N+1)]
Edge = [[] for _ in range(N+1)]
inf = 2*10**10
Edgenum = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
for a, b, c in Edgenum:
    Edgeinv[b].append(a)
    Edge[a].append(b)

used = set([N])
stack = [N]
while stack:
    vn = stack.pop()
    for vf in Edgeinv[vn]:
        if vf not in used:
            used.add(vf)
            stack.append(vf)

used2 = set([1])
stack = [1]
while stack:
    vn = stack.pop()
    for vf in Edge[vn]:
        if vf not in used2:
            used2.add(vf)
            stack.append(vf)

Edgenum = [(a, b, c) for a, b, c in Edgenum if a in used and b in used]

used &= used2

dp = [-inf]*(N+1)
dp[1] = 0
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp = dp[:]
for i in range(N):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

if any(Dp[i] < dp2[i] for i in used):
    print(-1)
else:
    print(max(0, Dp[N]))

Submission status: Accepted

Solution code:
N, M, P = map(int, input().split())
edges = []
edges1 = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edges1[b-1].append(a-1)
    edges.append((a-1, b-1, -c+P))
from collections import deque
que = deque([N-1])
flag = [True]*N
flag[-1] = False
while que:
    v = que.pop()
    for e in edges1[v]:
        if flag[e]:
            que.append(e)
            flag[e] = False
def f(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0 
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if flag[e[1]]:
                continue
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    return False
    return d
d = f(N, M, edges)
if d:
    print(max(-d[-1], 0))
else:
    print(-1)

Submission status: Accepted

Solution code:
inf = float('inf')
V,E,P = map(int,input().split())
edge = []
for i in range(E):
    A,B,C = map(int,input().split())
    edge.append([A-1,B-1,P-C])

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

ans = d[V-1]

for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break
loop = ans != d[V-1]

if loop:
    print(-1)

else:
    ans = -d[-1]
    print(max(0,ans))

Submission status: Accepted

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

e_list = []
for i in range(M):
    A,B,C = list(map(int,input().split()))
    A,B = A-1,B-1
    e_list.append((A,B,P-C))
    

#ベルマンフォード法
#e_listの用意
vi=0
min_dis_list = [10**27 for i in range(N)]
min_dis_list[vi] = 0
prev_list = [-1 for i in range(N)]

for i in range(N-1):
    for e in e_list:
        u,v,d = e
        if min_dis_list[v]>min_dis_list[u]+d:
            min_dis_list[v]=min_dis_list[u]+d
            prev_list[v]=u

neg_loop_flag=[False for i in range(N)]

for i in range(N):
    for e in e_list:
        u,v,d = e
        if min_dis_list[u] < 10**26:
            if min_dis_list[u] + d < min_dis_list[v]:
                neg_loop_flag[v]=True
                min_dis_list[v] = min_dis_list[u] + d
            if neg_loop_flag[u]:
                neg_loop_flag[v]=True


if neg_loop_flag[N-1]:
    print(-1)
else:
    print(max(0,-min_dis_list[N-1]))

Submission status: Accepted

Solution code:
n,m,p = map(int, input().split())
es = []
g1 = [[]for _ in range(n)]
g2 = [[] for _ in range(n)]
li = []
for i in range(m):
  a,b,c = map(int, input().split())
  li.append((a - 1,b - 1,c))
  g1[a - 1].append((b - 1,(c-p)*-1))
  g2[b - 1].append((a - 1,(c-p)*-1))
done1 = [0] * n
done1[0] = 1
s = [0]
while s:
  d = s.pop()
  for node,_ in g1[d]:
    if not done1[node]:
      done1[node] = 1
      s.append(node)
done2 = [0] * n
done2[n - 1] = 1
s = [n - 1]
while s:
  d = s.pop()
  for node, _ in g2[d]:
    if not done2[node]:
      done2[node] = 1
      s.append(node)
done = [0] * n
for i in range(n):
  done[i] = done1[i] & done2[i]
for a,b,c in li:
  if done[a] & done[b]:
    es.append((a,b,(c-p)*-1))
m = len(es)
d = [0]*n
for i in range(n):
  for j in range(m):
    f, t, c = es[j]
    if d[t] > d[f] + c:
      d[t] = d[f] + c
      if i == n - 1:
        print(-1)
        exit(0)
d = [float('inf')] * n
d[0] = 0
while(True):
  update = False
  for i in range(m):
    f, t, c = es[i]
    if d[f] != float('inf') and d[t] > d[f] + c:
      d[t] = d[f] + c
      update = True
  if not update:
    break
print(max(0, -d[n - 1]))

Submission status: Accepted

Solution code:
import sys
inf = 10000000000

def BellmanFord(edges,points,start):#edgeは1-indexedの起点/終点/距離
  #グラフの初期化
  dist=[inf for i in range(points)]
  dist[start-1]=0
  
  #辺の緩和
  for i in range(points):
    for edge in edges:
      if dist[edge[0]-1]!=inf and  dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
    dist1 = dist[N-1]
  for i in range(points):
    for edge in edges:
      if dist[edge[0]-1]!=inf and  dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
    dist2 = dist[N-1]
  if dist1 != dist2:return "Loop"
  return (dist)

N,M,P = [int(i) for i in input().split()]
Edges = []
for i in range(M):
    a,b,c = [int(i) for i in input().split()]
    Edges.append((a,b,P-c))
dist = BellmanFord(Edges,N,1)
if dist =="Loop":
    print(-1)
else:
    print(max(-dist[N-1],0))

Submission status: Accepted

Solution code:
N, M, P = map(int, input().split())
E = [list(map(int, input().split())) for _ in range(M)]
A = [-float("inf")] * (N+1)
A[1] = 0
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
ans = A[N]
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
if ans!=A[N]:
    print(-1)
else:
    print(max(0, ans))

Submission status: Accepted

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


INF = 10**18
dist = [INF] * n
dist[0] = 0
for i in range(2*n):
    for v, e in enumerate(G):
        if dist[v] == INF:
            continue
        for t, cost in e:
            if dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                # 頂点Nに向かう辺に負閉路があったとき
                if i >= n-1 and t == n-1:
                    print(-1)
                    exit()
print(max(0, -dist[-1]))

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, m, p = na()

def bf(es, n, start):
    d = [999999999999] * n
    d[start] = 0

    for r in range(n-1):
        updated = False
        for e in es:
            if d[e[0]] == 999999999999:
                continue
            if d[e[0]] + e[2] < d[e[1]]:
                d[e[1]] = d[e[0]] + e[2]
                updated = True
        if not updated:
            break

    for e in es:
        if d[e[0]] < 999999999999 and d[e[0]] + e[2] < d[e[1]]:
            return None

    return d

es = []
for i in range(m):
    a, b, c = na()
    es.append((a-1, b-1, -(c-p)))

import collections
q = collections.deque()
q.append(n-1)

valid = [False] * n
valid[n-1] = True
while len(q) > 0:
    cur = q.popleft()
    for e in es:
        if e[1] == cur and not valid[e[0]]:
            valid[e[0]] = True
            q.append(e[0])

nes = []
for e in es:
    if valid[e[0]] and valid[e[1]]:
        nes.append(e)
es = nes

d = bf(es, n, 0)
if not d:
    print(-1)
else:
    print(max(0, -d[n-1]))

Submission status: Runtime Error

Solution code:
from numpy.core.numeric import indices
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import numpy as np

def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        g[a][b]=min(g[a][b], -(c+1-p))
        to[a].append(b)
        ot[b].append(a)

    toflag[0]=True
    otflag[n-1]=True
    dfs(0) # check for 0 to i path
    rdfs(n-1) # check for n-1 to i path
 
    for i in range(n):
        for j in range(n):
            if toflag[i] and otflag[i] and toflag[j] and otflag[j]: continue;
            g[i][j]=0

    try:
        d=bellman_ford(g, indices=[0]).astype(int)
        print(max(-d[0][-1], 0))
    except NegativeCycleError:
        print(-1)



if __name__=='__main__':
    n,m,p=map(int,input().split())
    g=np.array([[0]*n for i in range(n)])
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    main()

Submission status: Runtime Error

Solution code:
def dfs(s):
    for i in to[s]:
        if not toflag[i]:
            toflag[i]=True
            dfs(i)


def rdfs(s):
    for i in ot[s]:
        if not otflag[i]:
            otflag[i]=True
            rdfs(i)


def bellman_ford():
    for i in range(n):
        upd=False
        for a,b,c in edges:
            if d[b]>d[a]+c:
                upd=True
                d[b]=d[a]+c     
        if not upd:
            break
        if i == n-1:
            print(-1)
            exit()


def main():

    for i in range(m):
        a,b,c=map(lambda x:int(x)-1,input().split())
        edges.append([a,b,-(c+1-p)])
        to[a].append(b)
        ot[b].append(a)

    toflag[0]=True
    otflag[n-1]=True
    dfs(0) # check for 0 to i path
    rdfs(n-1) # check for n-1 to i path
 
    for i in range(m):
        a,b,c=edges[i]
        if toflag[a] and otflag[a] and toflag[b] and otflag[b]: continue;
        edges[i]=[0,0,0]

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



if __name__=='__main__':
    n,m,p=map(int,input().split())
    edges=[]
    to=[[] for i in range(n)]
    ot=[[] for i in range(n)]
    toflag=[False]*n
    otflag=[False]*n
    d=[10**9]*n
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**3)


def dfs(s,v=0,c=0):
  global ans
  if s==n-1:
    ans=max(ans, v-p*c)
  for i in range(n):
    if not to[s][i]: continue;
    if s==i:
      if p<to[s][i] and i==n-1: print(-1); exit()
      else: continue;
    dfs(i,v+to[s][i],c+1)
  #return ans


def main():
  for i in range(m):
    a,b,c=map(lambda x:int(x)-1,input().split())
    to[a][b]=c+1
  #print(to)
  dfs(0)
  print(max(0,ans))
  

if __name__=='__main__':
  n,m,p=map(int,input().split())
  to=[[0]*n for i in range(n)]
  ans=0
  main()