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 = list(map(int, input().split()))

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] -= p

start = 0
goal = n - 1

# dist: cost from start
dist = [-float("inf")] * n
dist[start] = 0

# cut edges
reachable = [False] * n
reachable[goal] = True
d = deque()
d.append(goal)
reachable[goal] = True
while len(d) > 0:
    x = d.popleft()
    for edge in edges:
        if edge[1] == x and reachable[edge[0]] is False:
            d.append(edge[0])
            reachable[edge[0]] = True

cant_reach = []
for i in range(n):
    if reachable[i] is False:
        cant_reach.append(i)

for edge in edges:
    if edge[0] in cant_reach or edge[1] in cant_reach:
        edges.remove(edge)

# bellman-ford

# relaxing
negative_cycle = False
for i in range(n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != -float("inf") and dist[edge[1]] < dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
            if i == n - 1:
                negative_cycle = True

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

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())
    c = P-C
    if A == B:
        c *= 10**6
    edge.append([A-1,B-1,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 = 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 = [[float('inf'), 0, 0] for i in range(n+1)]

S[1][0]=0
S[1][1]=1
S[n][2]=1

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

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

ANS0 = [S[i][0] for i in range(len(S))]

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


#print(ANS0, ANS1)

imp = 0

for i in range(len(S)):
    if S[i][1] == 1 and S[i][2] == 1:
        if ANS0[i] != S[i][0]:
            imp = 1

if imp == 1:
    print(-1)
else:
    print(max(0, -ANS0[n]))

Submission status: Accepted

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bellman_ford(N: int, edges: list, src: int) -> list:
    """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

    # 頂点[ある始点からの最短距離] (経路自体を知りたい時はここに前の頂点も持たせる)
    res = [INF] * N
    res[src] = 0
    # 各辺によるコストの置き換えを頂点数N-1回繰り返す
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    # 頂点Nが負の閉路に含まれていないかチェックする
    for i in range(N):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = -INF
                if dest == N-1:
                    # 該当していたら空リストを返却
                    return []
    # 問題なければ頂点リストを返却
    return res

N, M, P = MAP()
edges = []
for i in range(M):
    a, b, c = MAP()
    # Pは最後に請求される、だけど、ようは動く度に支払ってると思ってもいい
    edges.append((a-1, b-1, -c+P))

res = bellman_ford(N, edges, 0)
if not len(res):
    print(-1)
else:
    # 正負を直す
    ans = -res[N-1]
    # スコアがマイナスなら0
    print(max(0, ans))

Submission status: Accepted

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

graph = [[] for _ in range(N)]
for a, b, c in ABC:
    graph[a - 1].append((b - 1, P - c))


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


vertices = []
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    if v1 & v2:
        vertices.append(i)

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for v in vertices:
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in vertices:
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for v in vertices:
    updated |= prev[v] != dist[v]

if updated or dist[N - 1] == INF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Submission status: Accepted

Solution code:
"""
Bellman-Ford
始点と終点が決められているとき、
経由する閉路のみを確認する必要がある。
"""
def Bellman_Ford2(g,start,goal):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    a0 = float("inf")
    for i in range(2*n):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if dist[to] <= dist[v] + cost: continue
                if i < n:
                    dist[to] = dist[v] + cost
                else:
                    dist[to] = -float("inf")
                updated = True
        if not updated: break
    if dist[goal] == -float("inf"): return None, False
#    if negative[-1]: return None, False
    return dist, True
 

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m,p = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
for i in range(m):
    a,b,c = [int(i) for i in readline().split()]
    g[a-1].append((b-1,-c+p))
#    g[b-1].append((a-1,c))

dist, TF = Bellman_Ford2(g,0,-1)

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

Submission status: Accepted

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

def BF(edges,n,s):
    inf=float("inf")
    d=[inf for i in range(n+1)]
    d[s]=0
    update=True
    for i in range(n+1):
      update=False
      for v,u,cost in edges:
        if cand[v]!=1 or cand[u]!=1:
          continue
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
          update=True
      if update==False:
        break
      if i==n:
        return inf
    return -d[-1]

def DFS_1toN(v):
  for u in to[v]:
    if toflag[u]==0:
      toflag[u]=1
      DFS_1toN(u)
      
def DFS_Nto1(v):
  for u in ot[v]:
    if otflag[u]==0:
      otflag[u]=1
      DFS_Nto1(u)
    
n,m,p=map(int,input().split())
g=[]
to=[[] for _ in range(n+1)]
ot=[[] for _ in range(n+1)]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
  to[a].append(b)
  ot[b].append(a)
toflag=[0]*(n+1)
toflag[1]=1
DFS_1toN(1)
otflag=[0]*(n+1)
otflag[n]=1
DFS_Nto1(n)
cand=[0]*(n+1)
for i in range(1,n+1):
  cand[i]=toflag[i]*otflag[i]
ans=BF(g,n,1)
if ans==float('inf'):
  print(-1)
else:
  print(max(ans,0))

Submission status: Accepted

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

def BF(edges,n,s):
    inf=float("inf")
    d=[inf for i in range(n+1)]
    d[s]=0
    update=True
    cnt=0
    while 1:
      update=False
      for v,u,cost in edges:
        if cand[v]!=1 or cand[u]!=1:
          continue
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
          update=True
      if update==False:
        break
      cnt+=1
      if cnt>n:
        return inf
    return -d[-1]

def DFS_1toN(v):
  for u in to[v]:
    if toflag[u]==0:
      toflag[u]=1
      DFS_1toN(u)
      
def DFS_Nto1(v):
  for u in ot[v]:
    if otflag[u]==0:
      otflag[u]=1
      DFS_Nto1(u)
    
n,m,p=map(int,input().split())
g=[]
to=[[] for _ in range(n+1)]
ot=[[] for _ in range(n+1)]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
  to[a].append(b)
  ot[b].append(a)
toflag=[0]*(n+1)
toflag[1]=1
DFS_1toN(1)
otflag=[0]*(n+1)
otflag[n]=1
DFS_Nto1(n)
cand=[0]*(n+1)
for i in range(1,n+1):
  cand[i]=toflag[i]*otflag[i]
ans=BF(g,n,1)
if ans==float('inf'):
  print(-1)
else:
  print(max(ans,0))

Submission status: Accepted

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

def BellmanFord(Edges,num_v,start,goal):
    inf=float('inf')
    Dist=[inf]*num_v
    Dist[start]=0
    for _ in range(num_v):
        for fr,to,cost in Edges:
            if Dist[fr]!=inf and Dist[to]>Dist[fr]+cost:
                Dist[to]=Dist[fr]+cost
    d=Dist[goal]
    for _ in range(num_v):
        for fr,to,cost in Edges:
            if Dist[fr]!=inf and Dist[to]>Dist[fr]+cost:
                Dist[to]=-inf
    if d!=Dist[goal]:
        return -inf
    return d

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    Edges.append((a,b,-(c-p)))
d=BellmanFord(Edges,n,0,n-1)
print(-1 if d==-float('inf') else max(0,-d))

Submission status: Accepted

Solution code:

import sys

sys.setrecursionlimit(10000)

n, m, p = list(map(int, input().split()))
abc = [list(map(int, input().split())) for _ in range(m)]
al = [[] for _ in range(n)]

for i in range(m):
    abc[i][0] -= 1
    abc[i][1] -= 1
    abc[i][2] = -(abc[i][2] - p)

for a, b, c in abc:
    al[a].append(b)

d = [1e9] * n
d[0] = 0

for _ in range(n - 1):
    for u, v, c in abc:
        if d[v] > d[u] + c:
            d[v] = d[u] + c

res = -d[-1]

for _ in range(n - 1):
    for u, v, c in abc:
        if d[v] > d[u] + c:
            d[v] = d[u] + c
    

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

Submission status: Accepted

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 10000000))
G_rev = defaultdict(lambda: defaultdict(lambda: 10000000))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = min(G[A][B], P - C)
    G_rev[B][A] = 1

reachable_N = [0] * (N + 1)
reachable_N[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable_N[q] == 0:
            reachable_N[q] = 1
            queue.append(q)

reachable_1 = [0] * (N + 1)
reachable_1[1] = 1
queue = deque([1])

while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if reachable_1[q] == 0:
            reachable_1[q] = 1
            queue.append(q)

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000 for i in range(N + 1)]
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > N:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, -dist[N]))

Submission status: Accepted

Solution code:
import sys

def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    dist = [sys.maxsize] * (N + 1)

    dist[1] = 0
    for _ in range(N):
        for j in range(M):
            weight = -(C[j] - P)
            if dist[B[j]] > dist[A[j]] + weight:
                dist[B[j]] = dist[A[j]] + weight

    result = -dist[N]

    for _ in range(N + 1):
        for j in range(M):
            weight = -(C[j] - P)
            if dist[B[j]] > dist[A[j]] + weight:
                dist[B[j]] = dist[A[j]] + weight

    if result != -dist[N]:
        print(-1)
    else:
        print(max(-dist[N], 0))


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

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] = -inf
if ans != d[N - 1]:
    print(-1)
else:
    print(max(0, -d[N - 1]))

Submission status: Accepted

Solution code:
N, M, P = map(int, input().split())
E = [list(map(int, input().split())) for _ in range(M)]
reachable = [False] * (N+1)
reachable[N] = True
for v in range(N):
    for a, b, c in E:
        if reachable[b]:
            reachable[a] = True
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
A_copy = A[:]
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
for a_copy, a, r in zip(A_copy, A, reachable):
    if r and a_copy != a:
        print(-1)
        exit()
else:
    print(max(0, A[N]))

Submission status: Accepted

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0)]
D=[0]*2+[-9e9]*N
def f():
	for _ in D:
		for a,b,c in E:D[b]=max(D[b],D[a]+c-P)
f()
s=D[N]
f()
print([max(s,0),-1][s<D[N]])

Submission status: Accepted

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0)]
D=[0]*2+[-9e9]*N
def f():
	for _ in D:
		for (a,b,c)in E:D[b]=max(D[b],D[a]+c-P)
f()
s=D[N]
f()
print([max(s,0),-1][s<D[N]])

Submission status: Accepted

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0).readlines()]
D=[0]*2+[-9e9]*N
def f():
	for _ in D:
		for (a,b,c)in E:D[b]=max(D[b],D[a]+c-P)
f()
s=D[N]
f()
print([max(s,0),-1][s<D[N]])

Submission status: Accepted

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0).readlines()]
D=[0]*2+[-9e9]*N
def f():
	for _ in D:
		for (a,b,c)in E:D[b]=max(D[b],D[a]+c-P)
	return D[N]
s=f()
print([max(s,0),-1][s<f()])

Submission status: Accepted

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

    reachable_from = [False for _ in range(N)]
    reachable_from[0] = True
    reachable_to = [False for _ in range(N)]
    reachable_to[N-1] = True

    for i in range(N-1):
        for edge in edges:
            if reachable_from[edge[0]]:
                reachable_from[edge[1]] = True
            if reachable_to[edge[1]]:
                reachable_to[edge[0]] = True

    edges2 = []
    for edge in edges:
        if reachable_from[edge[0]] and reachable_to[edge[0]]:
            edges2.append(edge)

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N):
        for edge in edges2:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
                if i==N-1:
                    print(-1)
                    break
        else:
            continue
        break
    else:
        print(max(0,-1*dist[N-1]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def BF(edges,n,s):
    inf=float("inf")
    d=[inf for i in range(n+1)]
    d[s]=0
    flag=False
    for i in range(n+1):
      for v,u,cost in edges:
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
    ans1=d[-1]
    for i in range(n+1):
      for v,u,cost in edges:
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
    ans2=d[-1]
    if ans2<ans1:
      return -1
    else:
      return max(-ans1,0)

n,m,p=map(int,input().split())
g=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
ans=BF(g,n,1)
print(ans)

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 = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist = [sys.maxsize] * (N+1)
    dist[s] = 0
    for _ in range(N+1):
        for u, v, c in e:
            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
    
    d = dist[goal]
    for _ in range(N+1):
        for u, v, c in e:
            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
    return dist, d != dist[goal]

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

    e = []
    for a, b, c in ABC:
        e.append((a, b, -(c - P)))

    d, loop = BellmanFord(N, e, 1, N)
    return max(0, -d[N]) if not loop else -1


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

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

for i in range(M):
    A, B, C = map(int, input().split())
    edge.append((A, B, P-C))

inf = float('inf')
cost = [inf] * (N+1)
cost[1] = 0
for i in range(N-1):
    for e in edge:
        a, b, c = e
        if cost[a] + c < cost[b]:
            cost[b] = cost[a] + c

for i in range(N):
    for e in edge:
        a, b, c = e
        if cost[a] + c < cost[b]:
            if b == N:
                print(-1)
                exit()
            else:
                cost[b] = cost[a] + c
        
print(max(-cost[N], 0))

Submission status: Accepted

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

INF = float('inf')
d = [INF] * n
d[0] = 0
for i in range(n):
    for v_from, v_to, cost in edge:
        if d[v_from] != INF and d[v_to] > d[v_from] + cost:
            d[v_to] = d[v_from] + cost

exist = True
for i in range(n):
    for v_from, v_to, cost in edge:
        if d[v_from] != INF and d[v_to] > d[v_from] + cost:
            d[v_to] = d[v_from] + cost
            if v_to == n - 1:
                exist = False

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

Submission status: Accepted

Solution code:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect


def main():
    node_num, edge_num, p = map(int, input().split())
    data = [list(map(int, input().split())) for i in range(edge_num)]
    # graph_data = defaultdict(set)
    # weight_graph = defaultdict(int)

    # for i in range(edge_num):
    #     a, b, c = data[i]
    #     graph_data[a].add(b)
    #     weight_graph[(a, b)] = c - p

    inf = 10 ** 10
    length_data = [inf for i in range(node_num + 1)]
    length_data[1] = 0
    for i in range(node_num):
        for j in range(edge_num):
            a, b, c = data[j]
            weight = -1 * (c - p)
            length_data[b] = min(length_data[b], length_data[a] + weight)


    ans = length_data[node_num]
    for i in range(node_num):
        for j in range(edge_num):
            a, b, c = data[j]
            weight = -1 * (c - p)
            length_data[b] = min(length_data[b], length_data[a] + weight)

    ans2 = length_data[node_num]

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







if __name__ == '__main__':
    main()

Submission status: Accepted

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

def BellmanFord(Edges,num_v,source):
    inf=float('inf')
    dist=[inf for _ in range(num_v)]
    dist[source]=0
    for i in range(num_v):
        for edge in Edges:
            if edge[0]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                dist[edge[1]]=dist[edge[0]]+edge[2]
                if i==num_v-1:
                    before_dist=dist[num_v-1]
                    for _ in range(num_v):
                        for edge in Edges:
                            if edge[0]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                                dist[edge[1]]=dist[edge[0]]+edge[2]
                    if before_dist!=dist[num_v-1]:
                        return -1
    return dist

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    Edges.append((a,b,-(c-p)))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

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**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])

ans0 = -S[n]

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

ans1 = -S[n]

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys

inf = float('inf')

def solve(N: int, M: int, P: int, a: "List[int]", b: "List[int]", c: "List[int]"):
    V = list(range(N))
    
    next_v = [[] for v in V]
    for i in range(M):
        next_v[a[i]-1].append((b[i]-1, c[i]))
    
    D = [-inf for v in V]
    D[0] = 0
    
    prev = [None for v in V]

    positive = [False for v in V]

    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    prev[v] = u
    ans = D[N-1]
    
    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    positive[v] = True
                if positive[u]:
                    positive[v] = True

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


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]" 
    B = [int()] * (M)  # type: "List[int]" 
    C = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = (int(next(tokens))-P)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

def BellmanFord(Edges,num_v,source):
    inf=float('inf')
    dist=[inf for _ in range(num_v)]
    dist[source]=0
    for i in range(num_v):
        for edge in Edges:
            if edge[0]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                dist[edge[1]]=dist[edge[0]]+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]] > dist[edge[0]]+edge[2]:
                                dist[edge[1]]=dist[edge[0]]+edge[2]
                    if before_dist!=dist[num_v-1]:
                        return -1
    return dist

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    Edges.append((a,b,-(c-p)))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

Submission status: Accepted

Solution code:
# 単一始点最短路
def bellman_ford(s):
    # 始点sから各頂点への最短距離
    d = [inf] * n
    d[s] = 0

    ref = inf
    for cnt in range(n * 2):
        for s, t, w in g:
            if d[s] != inf and d[t] > d[s] + w:
                d[t] = d[s] + w
        if cnt == n - 1:
            ref = d[n - 1]

    if ref == d[n - 1]:
        return max(0, -ref)
    else:
        return -1


inf = float('inf')

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

g = []
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    g.append((a, b, -(c - p)))  # (始点,終点,正負を逆にした重み)

ans = bellman_ford(0)
print(ans)
# 無限なら-1