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:
from collections import deque
N,M,P = map(int, input().split())
R = []
R2 = {}
R3 = {}
OPT = [float("inf")]*(N+1)
for _ in range(M):
    A,B,C = map(int, input().split())
    R.append([A,B,-C+P])
    if not B in R2:
        R2[B] = []
    if not A in R3:
        R3[A] = []
    R3[A].append(B)
    R2[B].append(A)

visited_N = [0]*(N+1)
visited_N[N] = 1
queue = deque()
queue.append(N)

while queue != deque():
    tmp = queue.pop()
    if tmp in R2:
        for i in R2[tmp]:
            if visited_N[i] == 0:
                visited_N[i] = 1
                queue.append(i)    

visited_1 = [0]*(N+1)
visited_1[1] = 1
queue = deque()
queue.append(1)

while queue != deque():
    tmp = queue.pop()
    if tmp in R3:
        for i in R3[tmp]:
            if visited_1[i] == 0:
                visited_1[i] = 1
                queue.append(i)    

visited = [0]*(N+1)
for i in range(N):
    visited[i+1] = visited_N[i+1]*visited_1[i+1]
                
OPT[1] = 0
OPT_tmp = OPT

for _ in range(N-1):
    for i in range(M):
        tmp_r = R[i]
        if visited[tmp_r[0]] == 1 and visited[tmp_r[1]] == 1:
            if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
                OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
tmp_opt = OPT[N]

flag = 0
for i in range(M):
    tmp_r = R[i]
    if visited[tmp_r[0]] == 1 and visited[tmp_r[1]] == 1:
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            flag = 1
    
if flag:
    answer = -1
else:
    answer = max(0,-tmp_opt)

print(answer)

Submission status: Accepted

Solution code:
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
revedgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  revedgedict[t-1][f-1] = 1

# Nに到達できない頂点を削除
visited = [False] * N
def dfs(f):
  visited[f] = True
  for t in revedgedict[f].keys():
    if not visited[t]:
      dfs(t)
dfs(N-1)

# ベルマンフォード
INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(N):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and visited[t] and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit((10 ** 6))
input = sys.stdin.readline
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for e in range(N):
        for w, c in G[e]:
            if dist[e] != INF and dist[w] > dist[e] + c:
                dist[w] = dist[e] + c

ans = -dist[N - 1]
is_negative = [False] * N
for i in range(N):
    for e in range(N):
        for w, c in G[e]:
            if dist[e] != INF and dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                is_negative[w] = True

            if is_negative[e]:
                is_negative[w] = True

if is_negative[N - 1]:
    print(-1)
else:
    print(max(ans, 0))

Submission status: Accepted

Solution code:
# 頂点sから到達する頂点の集合
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use

# ベルマンフォード法
def bellman_ford(v, s, t, e):
    INF = 10**18
    # コストをINFで初期化
    d = [INF] * v
    # 開始頂点は0
    d[s] = 0
    # 負の閉路が無ければ更新はV-1回までで終わる
    for _ in range(v):
        f = False
        for a, b, c in e:
            if d[a]==INF:continue
            # aまでのコスト+辺abのコストがbまでのコストより小さければ更新
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        # 更新が無ければbreak
        if not f:break
    else:
        # V回目まで更新があったら負の閉路がある
        return -1
    return max(-d[t], 0)

def main():
    import sys
    input = sys.stdin.readline
    n, m, p = map(int, input().split())
    edge = [[] for _ in range(n)]
    edge_rev = [[] for _ in range(n)]
    e = []
    for _ in range(m):
        a, b, c = map(int, input().split())
        edge[a-1].append(b-1)
        # 頂点Nからdfsするため辺の向きを逆にする
        edge_rev[b-1].append(a-1)
        e.append((a-1, b-1, p-c))
    """
    # 頂点1と頂点Nのどちらからも到達できる頂点の集合
    use = dfs(edge, 0) & dfs(edge_rev, n-1)
    # fromとtoがどちらもuseに含まれる辺のみ使う
    # そうすることで負の閉路を検出した場合答えは必ず-1になる
    """
    # ↑って思ってたけど頂点Nから到達できるか見るだけでいいらしいよ(えー)
    use = dfs(edge_rev, n-1)
    e = [(a, b, c) for a, b, c in e if a in use and b in use]
    print(bellman_ford(n, 0, n-1, e))   
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
INF = 10**10
 
def dfs(edge, visited, n):
    if visited[n]:
        return
    visited[n] = True
    for to, _ in edge[n]:
        dfs(edge, visited, to)

def bellman_ford(edge, mask):
    dist = [INF] * n
    dist[0] = 0

    for _ in range(n):
        update = False
        for i, es in enumerate(edge):
            if not mask[i]:
                continue
            for to, cost in es:
                if not mask[to]:
                    continue
                if dist[i] != INF and dist[i] + cost < dist[to]:
                    dist[to] = dist[i] + cost
                    update = True
        if not update:
            return dist
    else:
        # Found minus loops
        return -INF

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    redge = [[] for _ in range(n)]
    for i in range(m):
        a, b, c = [int(item) for item in input().split()]
        # Think as penalty costs per walk
        a -= 1; b -= 1; c -= p
        # Reverse cost to assume as shortest path problem
        c *= -1
        edge[a].append((b, c))
        redge[b].append((a, c)) 
    
    # Is the node can be arrived from start?
    visited = [False] * n
    dfs(edge, visited, 0)
    # Is the node can go to the end?
    rvisited = [False] * n
    dfs(redge, rvisited, n-1)
    mask = [forward and backward for forward, backward in zip(visited, rvisited)]

    dist = bellman_ford(edge, mask)
    if dist == -INF:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
INF = 10**10
 
def dfs(edge, visited, n):
    if visited[n]:
        return
    visited[n] = True
    for to, _ in edge[n]:
        dfs(edge, visited, to)

def bellman_ford(edge, mask):
    dist = [INF] * n
    dist[0] = 0

    for _ in range(n):
        update = False
        for i, es in enumerate(edge):
            if not mask[i]:
                continue
            for to, cost in es:
                if not mask[to]:
                    continue
                if dist[i] != INF and dist[i] + cost < dist[to]:
                    dist[to] = dist[i] + cost
                    update = True
        if not update:
            return dist
    else:
        # Found minus loops
        return -INF

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    redge = [[] 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))
        redge[b].append((a, c)) 
    
    visited = [False] * n
    dfs(edge, visited, 0)
    rvisited = [False] * n
    dfs(redge, rvisited, n-1)
    mask = [forward and backward for forward, backward in zip(visited, rvisited)]
    dist = bellman_ford(edge, mask)
    if dist == -INF:
        print(-1)
    else:
        print(max(0, -dist[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:
# 頂点sから到達する頂点の集合
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use

# ベルマンフォード法
def bellman_ford(v, s, t, e):
    # コストをINFで初期化
    d = [10**18] * v
    # 開始頂点は0
    d[s] = 0
    # 負の閉路が無ければ更新はV-1回までで終わる
    for _ in range(v):
        f = False
        for a, b, c in e:
            # aまでのコスト+辺abのコストがbまでのコストより小さければ更新
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        # 更新が無ければbreak
        if not f:break
    else:
        # V回目まで更新があったら負の閉路がある
        return -1
    return max(-d[t], 0)

def main():
    import sys
    input = sys.stdin.readline
    n, m, p = map(int, input().split())
    edge = [[] for _ in range(n)]
    edge_rev = [[] for _ in range(n)]
    e = []
    for _ in range(m):
        a, b, c = map(int, input().split())
        edge[a-1].append(b-1)
        # 頂点Nからdfsするため辺の向きを逆にする
        edge_rev[b-1].append(a-1)
        e.append((a-1, b-1, p-c))
    # 頂点1と頂点Nのどちらからも到達できる頂点の集合
    use = dfs(edge, 0) & dfs(edge_rev, n-1)
    # fromとtoがどちらもuseに含まれる辺のみ使う
    # そうすることで負の閉路を検出した場合答えは必ず-1になる
    e=[(a, b, c) for a, b, c in e if a in use and b in use]
    print(bellman_ford(n, 0, n-1, e))   
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    def dfs(edge,s):
        use={s}
        q=[s]
        while q:
            v=q.pop()
            for w in edge[v]:
                if w in use:continue
                use.add(w)
                q.append(w)
        return use
    n,m,p,*t=map(int,open(0).read().split())
    edge=[[]for _ in range(n)]
    edge_rev=[[]for _ in range(n)]
    e=[]
    for a,b,c in zip(t[::3],t[1::3],t[2::3]):
        edge[a-1].append(b-1)
        edge_rev[b-1].append(a-1)
        e.append((a-1,b-1,p-c))
    use=dfs(edge,0)&dfs(edge_rev,n-1)
    e=[(a,b,c)for a,b,c in e if a in use and b in use]
    INF=10**18
    d=[0]+[INF]*(n-1)
    for _ in range(n):
        f=False
        for a,b,c in e:
            cost=d[a]+c
            if cost<d[b]:
                d[b]=cost
                f=True
        if not f:break
    else:
        print(-1)
        exit()
    print(max(-d[-1],0))
main()

Submission status: Accepted

Solution code:
from collections import deque
def solve():
    N, M, P = map(int, input().split())
    G = [[] for i in range(N)]
    RG = [[] for i in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        G[a-1].append((b-1, P-c))
        RG[b-1].append((a-1, P-c))

    def chk(s, G):
        P = [0]*N
        que = deque([s])
        used = [0]*N
        used[s] = 1
        while que:
            v = que.popleft()
            P[v] = 1
            for w, c in G[v]:
                if used[w]:
                    continue
                que.append(w)
                used[w] = 1
        return P
    P0 = chk(0, G); P1 = chk(N-1, RG)
    F = [P0[i] == P1[i] == 1 for i in range(N)]
    I = [i for i in range(N) if F[i]]

    E0 = []
    for v in I:
        for w, c in G[v]:
            if not F[w]:
                continue
            E0.append((v, w, c))

    dist = [10**18]*N
    dist[0] = 0
    L = len(I)
    for i in range(L):
        update = 0
        for v, w, c in E0:
            x = c + dist[v]
            if x < dist[w]:
                dist[w] = x
                update = 1
        if not update:
            break
    else:
        print("-1")
        return

    print(max(-dist[N-1], 0))
solve()

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, 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 _ in range(N):
        for edge in edges:
            if dist[edge[0]] == INT_MAX:
                continue
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]
                negative[edge[1]] = True
            # ある頂点が負閉路の一部なら、それに隣接する頂点も負閉路の一部
            if negative[edge[0]]:
                negative[edge[1]] = 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)
ans = -1 * shortest_path[N]
#print(shortest_path)
if ans == -INT_MAX or ans == INT_MAX:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Accepted

Solution code:
def e_coins_respawn(N, M, P, Edges, INF=float('inf')):
    edges = [(a - 1, b - 1, P - c) for a, b, c in Edges]
    dist = [INF] * N
    dist[0] = 0

    for _ in range(N - 1):
        for u, v, w in edges:
            if dist[u] == INF:
                continue
            if dist[v] > dist[u] + w:
                dist[v] = dist[u] + w
    ans_tmp = dist[N - 1]  # 負閉路がなければ、これが解

    # 負閉路がなければここからのループで距離は変わらない
    is_negative = [False] * N
    for _ in range(N):
        for u, v, w in edges:
            if dist[u] == INF:
                continue
            if dist[v] > dist[u] + w:
                dist[v] = dist[u] + w
                is_negative[v] = True

            # ある頂点が負閉路の一部なら、それに隣接する頂点も負閉路の一部
            if is_negative[u]:
                is_negative[v] = True
    # 頂点Nが負閉路に含まれるなら、元のグラフでのスコアは無限大
    return -1 if is_negative[N - 1] else max(-ans_tmp, 0)

N, M, P = [int(i) for i in input().split()]
Edges = [[int(i) for i in input().split()] for j in range(M)]
print(e_coins_respawn(N, M, P, Edges))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)



# グラフ定義
class Edge:
    def __init__(self, f: int, t: int, cost: int):
        self._t = t
        self._cost = cost
        self._f = f

    @property
    def t(self):
        return self._t

    @property
    def f(self):
        return self._f

    @property
    def cost(self):
        return self._cost


INF = 1 << 28


# ここから本実装
def bellman_ford(n: int, edges, s: int):
    dist = [INF for _ in range(n)]
    dist[s] = 0

    for i in range(2 * n):
        for e in edges:

            if dist[e.t] > dist[e.f] + e.cost:
                dist[e.t] = dist[e.f] + e.cost
                if i >= n - 1:
                    return None

    return dist


def visitable_node(n, g, rg):

    vis = [False] * n

    def dfs(idx):
        vis[idx] = True
        for e in g[idx]:
            if not vis[e]:
                dfs(e)

    dfs(0)

    rvis = [False] * n

    def rdfs(idx):
        rvis[idx] = True
        for e in rg[idx]:
            if not rvis[e]:
                rdfs(e)

    rdfs(n - 1)

    return [vis[i] & rvis[i] for i in range(n)]


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

edges = []
g = [[] for _ in range(n)]
rg = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append(Edge(a, b, -c + p))
    g[a].append(b)
    rg[b].append(a)

visitable = visitable_node(n, g, rg)
updated = [e for e in edges if visitable[e.f] and visitable[e.t]]

dist = bellman_ford(n, updated, 0)

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

Submission status: Accepted

Solution code:
#入力
n,m,r=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]
#グラフ
g=[[] for _ in [0]*n]
[g[a-1].append([b-1,c]) for a,b,c in abc]

#逆辺
g2=[[] for _ in [0]*n]
[g2[b-1].append([a-1,c]) for a,b,c in abc]

#前処理用のDFS
def remove_edge(graph,start):
    q=[start]
    memo=[True for _ in range(n)]
    memo[start]=False
    while q:
        qq=q.pop()
        for i,j in graph[qq]:
            if memo[i]:
                q.append(i)
                memo[i]=False
    return {i for i,j in enumerate(memo) if j==True}

#前処理
rmv=remove_edge(g,0)|remove_edge(g2,n-1)
for i in rmv:
    g[i]=[]
for i in range(n):
    for j in g[i]:
        if j[0] in rmv:
            g[i].remove(j)

#ベルマンフォード
dist=[-10**15 for _ in [0]*n]
dist[0]=0

for k in range(n):
    for p in range(n):
        for i,j in g[p]:
            dist[i]=max(dist[i],dist[p]+j-r)
    if k==n-2:
        d1=[t for t in dist]
    if k==n-1:
        d2=[t for t in dist]
        
#1からでもnの間に負の閉路があるときは-1
if d1==d2:
    print(max(d1[-1],0))
else:
    print(-1)

Submission status: Accepted

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

edge_dic = {}

for _ in range(M):
    A,B,C = map(int,input().split())
    if not A - 1 in edge_dic:
        edge_dic[A-1] = [[B-1,C-P]]
    else:
        edge_dic[A-1].append([B-1,C-P])

# print(edge_dic)

INF = 10 ** 10

ans_array = [-INF] * N
can_visit = [0] * N
ans_array[0] = 0
can_visit[0] = 1 
last_ans_change = -1

for i in range(N*2):
    change_flag = 0
    for key, value in edge_dic.items():
        if can_visit[key] == 0:
            continue
        for v in value:
            goal, cost = v
            if ans_array[goal] < ans_array[key] + cost:
                ans_array[goal] = ans_array[key] + cost
                if i >= N:
                    ans_array[goal] = INF
                can_visit[goal] = 1
                change_flag = 1
                if goal == N - 1:
                    last_ans_change = i
                    if i >= N:
                        print(-1)
                        exit()
    if change_flag == 0:
        break


ans = max(0,ans_array[N-1])

print(ans)

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
    flag = False

    #辺の緩和
    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:
                if edge[1] == num_v:
                    return -1
                else:
                    dist[edge[1]-1] = -inf
                    flag = True
    if flag:
        for i in range(num_v):
            for edge in edges:
                if dist[edge[1]-1]>dist[edge[0]-1] + edge[2]:
                    dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
                    if edge[1] == num_v :
                        return -1

    return dist

N,M,P = [int(x) for x in input().split()]
gp = []
for _ in range(M):
    A,B,C = [int(x) for x in input().split()]
    gp.append([A,B,P-C])

li = BellmanFord(gp,N,1)
if(li==-1):
    print(-1)
else:
    print(max(0,-li[N-1]))

Submission status: Accepted

Solution code:
from collections import deque
N, M, P = map(int, input().split())
G = [[] for i in range(N)]
RG = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    G[a-1].append((b-1, P-c))
    RG[b-1].append((a-1, P-c))

def chk(s, G):
    P = [0]*N
    que = deque([s])
    used = [0]*N
    used[s] = 1
    while que:
        v = que.popleft()
        P[v] = 1
        for w, c in G[v]:
            if used[w]:
                continue
            que.append(w)
            used[w] = 1
    return P
P0 = chk(0, G); P1 = chk(N-1, RG)
I = [i for i in range(N) if P0[i] == P1[i] == 1]

dist = [10**18]*N
dist[0] = 0
L = len(I)
for i in range(L+1):
    update = 0
    for v in I:
        d = dist[v]
        for w, c in G[v]:
            if d + c < dist[w]:
                dist[w] = d + c
                update = 1
    if not update:
        break
else:
    print("-1")
    exit(0)

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

Submission status: Accepted

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

v = [[] for _ in range(N)]
abc = []
for _ in range(M) :
    a, b, c = map(int, input().split())
    v[b-1].append((a-1, -(c-P)))
    
visited = [False] * N
visited[N-1] = True
queue = [N-1]
while queue :
    cur = queue.pop()
    for nex, cost in v[cur] :
        if not visited[nex] :
            queue.append(nex)
            visited[nex] = True
        abc.append((nex, cur, cost))
        
dist = [float('inf')] * N
dist[0] = 0

def bellmanford() :
    for i in range(N) :
        for a, b, c in abc :
            if dist[a] + c < dist[b] :
                dist[b] = dist[a] + c
                if i == N-1 :
                    return True
    return False
    
if bellmanford() :
    print(-1)
else :
    print(max(0, -dist[N-1]))

Submission status: Accepted

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


def b_f(node_list,n,t):
    distance_list = [ 10**15 for i in range(n) ]
    distance_list[t] = 0

    for i in range(n):
        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
        distance_list = new_distanece_list

        if i == n-2:
            distance_list_n_minus_1 = [i for i in distance_list]
        elif i == n-1:
            distance_list_n = [i for i in distance_list]

    if distance_list_n_minus_1 == distance_list_n:
        negative_cycle = 0
    else:
        negative_cycle = 1

    return distance_list_n_minus_1, negative_cycle


point_list_s = b_f(node_list,n,0)[0]
point_list_g = b_f(node_list_2,n,n-1)[0]
point_list = [ True for i in range(n) ]

for i in range(n):
    if point_list_s[i] == 10**15 or point_list_g[i] == 10**15:
        point_list[i] = False

node_list_3 = [ i for i in node_list if point_list[i[0]] == True and point_list[i[1]] == True ]
ans = b_f(node_list_3,n,0)

if ans[1] == 0:
    print(-min(0,ans[0][-1]))
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

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]*N
min_dis_list[vi] = 0
 
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
 
neg_loop_flag=[False]*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:
# -*- 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(N, e, s, goal):
    dist = [sys.maxsize] * (N+1)
    dist[s] = 0
    for i in range(N+1):
        for u, v, c in e:
            if dist[v] > dist[u] + c:
                if i == N:
                    return 'inf'
                dist[v] = dist[u] + c
    return dist

@mt
def slv(N, M, P, ABC):
    g = [[] for _ in range(N+1)]
    for a, b, c in ABC:
        g[a].append(b)

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

    d = set()
    for i in range(2, N):
        reachable = r(i, N)
        if N not in reachable:
            d.add(i)
    
    e = []
    sr = r(1, N)
    for a, b, c in ABC:
        if a not in d and b not in d and a in sr and b in sr:
            e.append((a, b, -(c - P)))

    d = BellmanFord(N, e, 1, N)
    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()