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:
import sys
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().strip()


def main():
    N, M, P = map(int, input().split())

    """
    あらかじめ各辺のコイン枚数からP引いておけば、求めるのは単純にコイン枚数の最大値となる。
    すなわちこれは「最長経路問題」に他ならない。
    するとコイン枚数を(-1)倍して「最短経路問題」を求めればよく典型問題に帰着。
        ダイクストラ　　　→　負辺があるのでダメ
        ベルマンフォード　→　O(VE)で解けるので今回はこれ
        ワ―シャルフロイド →　O(V^3)なので間に合わない

    ベルマンフォード復習：
        １．スタートする頂点をsとしてd[s] = 0、その他の頂点はd[v] = \inftyで初期化
        ２．重みwの辺u→vに対してd[v] = min(d[v], d[u] + w)
        ３．この更新を「すべての辺」（E本）に対して行う
        ４．２－３ステップをN（頂点数）回繰り返すと値の更新が（負閉路を除き）収束する
    
    ただし本問では負閉路検出後にそれが1-(負閉路)-Nのように頂点1と頂点Nの間にいることを
    確認する必要がある。
    """

    edges = [] # ベルマンフォードするなら頂点よりも辺が主役なので
    repn = [[] for _ in range(N)]
    reverse_repn = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        repn[a - 1].append(b - 1)
        reverse_repn[b - 1].append(a - 1)
        edges.append((a - 1, b - 1, P - c))

    """
    後々必要なので、頂点0「から」たどり着ける頂点と、
    頂点(N-1)「に」たどり着ける頂点をそれぞれ列挙する
    """

    reachable_from_1 = [0] * N
    reachable_to_N = [0] * N
    ok = [0] * N # 始点と終点の間にいる頂点（ここだけ考慮すれば十分）

    def dfs(v):
        if reachable_from_1[v]:
            return
        reachable_from_1[v] = 1
        for u in repn[v]:
            dfs(u)
    
    def reverse_dfs(v):
        if reachable_to_N[v]:
            return
        reachable_to_N[v] = 1
        for u in reverse_repn[v]:
            reverse_dfs(u)
    
    dfs(0)
    reverse_dfs(N - 1)
    for i in range(N):
        if reachable_from_1[i] and reachable_to_N[i]:
            ok[i] = 1

    """
    ここからベルマンフォード
    """

    d = [float("inf")] * N
    d[0] = 0
    step = 0
    update = True
    while update:
        update = False
        for i in range(M):
            a, b, cost = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            new_cost = d[a] + cost
            if new_cost < d[b]:
                update = True
                d[b] = new_cost
        step += 1
        if step > N:
            print(-1)
            return
    print(max(0, -d[N - 1]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def bellmanford(v,s,path):
    # 距離をinfで初期化
    d = [float('inf')]*v

    # startの頂点までの距離 = 0
    d[s] = 0
    for j in range(v):
        update = False

        # 各頂点までの距離を更新
        # 全辺について、"頂点bまでの距離"が"aまでの距離"+"aからbまでの辺"よりも大きいとき更新
        for a,b,c in path:
            if d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True

        # 更新が行われない場合はやめる。
        if not update:
            break
        # 負の閉路の検出。負の閉路を求めないならいらない。
        # v-1回更新しても、さらに更新できるときは負の閉路が存在することになる。
        elif j == v-1:
            return -1

    return d

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

path = [[] for i in range(n)]
path_inv = [[] for i in range(n)]

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

a = [0]*n
s = 0
a[0]=1
stack = [s]
while stack:
    p = stack.pop()
    for q,r in path[p]:
        if a[q]==0:
            a[q]=1
            stack.append(q)

b = [0]*n
g = n-1
b[n-1]=1
stack = [g]
while stack:
    p = stack.pop()
    for q,r in path_inv[p]:
        if b[q]==0:
            b[q]=1
            stack.append(q)

c = [i for i in range(n) if a[i]==b[i]==1]

path2 = []
for i in c:
    for to,cost in path[i]:
        path2.append([i,to,cost])

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

Submission status: Accepted

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

def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return -1
  return max(-d[n-1],0)

from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

def glaph_bfs(s,n,e):
  ans=[0]*n
  Q=[s]
  visited={s}
  while Q:
    P=[]
    for i in Q:
      ans[i]=1
      for j in e[i]:
        if j in visited:continue
        visited.add(j)
        P.append(j)
    Q=P
  return ans

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append((a,b,c))
eff=glaph_bfs(0,n,ef)
eef=glaph_bfs(n-1,n,ee)
ee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    ee.append((a,b,-c))
print(find_negative_loop(n,ee))

Submission status: Accepted

Solution code:
#入力高速化 + 再帰回数制限解除
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10000000)

#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return -1
  return max(-d[n-1],0)

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append((a,b,c))
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
ee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    ee.append((a,b,-c))
print(find_negative_loop(n,ee))

Submission status: Accepted

Solution code:
#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

#ベルマンフォード(d[i]=頂点sから頂点iの最短距離)
#単一始点最短経路(負の辺対応)
#s=始点 n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def bellman_ford(s,n,e):
	inf=10**20;d=[inf]*n;d[s]=0
	while 1:
		f=True
		for i,j,k in e:
			if d[i]!=inf and d[j]>d[i]+k:d[j]=d[i]+k;f=False
		if f:break
	return d

#グラフ上でのBFS
#s=始点 n=頂点数 e=隣接リスト
def glaph_bfs(s,n,e):
  ans=[0]*n
  Q=[s]
  visited={s}
  while Q:
    P=[]
    for i in Q:
      ans[i]=1
      for j in e[i]:
        if j in visited:continue
        visited.add(j)
        P.append(j)
    Q=P
  return ans

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append([a,b,c])
eff=glaph_bfs(0,n,ef)
eef=glaph_bfs(n-1,n,ee)
edge=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    edge.append([a,b,-c])
if find_negative_loop(n,edge):print(-1);exit()
print(max(-bellman_ford(0,n,edge)[n-1],0))

Submission status: Accepted

Solution code:
#DAG判定
#n=頂点数 e=隣接リスト
#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

#ベルマンフォード(d[i]=頂点sから頂点iの最短距離)
#単一始点最短経路(負の辺対応)
#s=始点 n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def bellman_ford(s,n,e):
	inf=10**20;d=[inf]*n;d[s]=0
	while 1:
		f=True
		for i,j,k in e:
			if d[i]!=inf and d[j]>d[i]+k:d[j]=d[i]+k;f=False
		if f:break
	return d

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  e.append([a,b,c])
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
edge=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    edge.append([a,b,-c])
if find_negative_loop(n,edge):print(-1);exit()
print(max(-bellman_ford(0,n,edge)[n-1],0))

Submission status: Accepted

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

N, M, P = map(int, input().split())
edges = [None] * M
for i in range(M):
    A, B, C = map(int, input().split())
    edges[i] = (A, B, P-C)

dist = [float('inf')] * (N+1)
dist[1] = 0
for i in range(N-1):
    for u, v, weight in edges:
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
negative = [False] * (N+1)
for i in range(N):
    for u, v, weight in edges:
        if negative[u]:
            negative[v] = True
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
            negative[v] = True
print(max(-dist[N], 0) if not negative[N] else -1)

Submission status: Accepted

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

def dfs(edges, s):
    use = {s}
    stack = [s]
    while stack:
        v = stack.pop()
        for w in edges[v]:
            if w in use: continue
            use.add(w)
            stack.append(w)
    return use

def bellmanford(num_v, edges, source):
    inf = float('inf')
    dist = [inf] * num_v
    dist[source] = 0
    for i in range(num_v):
        flag = False
        for s, t, cost in edges:
            if dist[s] == inf: continue
            if dist[s] + cost < dist[t]:
                dist[t] = dist[s] + cost
                flag = True
        if not flag: break
    else:
        return False
    return dist

def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    G_rev = [[] for _ in range(N)]
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append(b)
        G_rev[b].append(a)
        edges.append((a, b, P-c))
    
    use = dfs(G_rev, N-1)
    edges = [(a, b, c) for a, b, c in edges if a in use and b in use]
    dist = bellmanford(N, edges, 0)
    if dist:
        print(max(0, -dist[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque


def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if (not reach[nxt_v]) or (not rev_reach[nxt_v]):
                    continue
                if dist[v] != INF and dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            return dist[n - 1]
    return -INF


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

graph = [[] for i in range(n)]
rev_graph = [[] for i in range(n)]
for a, b, cost in info:
    a -= 1
    b -= 1
    graph[a].append((b, -(cost - p)))
    rev_graph[b].append(a)

reach = [False] * n
reach[0] = True
q = deque([0])
while q:
    v = q.popleft()
    for nxt_v, _ in graph[v]:
        if reach[nxt_v]:
            continue
        reach[nxt_v] = True
        q.append(nxt_v)
        
rev_reach = [False] * n
rev_reach[n - 1] = True
q = deque([n - 1])
while q:
    v = q.popleft()
    for nxt_v in rev_graph[v]:
        if rev_reach[nxt_v]:
            continue
        rev_reach[nxt_v] = True
        q.append(nxt_v)

dist = bellman_ford(0, graph)
if dist == -float("inf"):
    print(-1)
else:
    print(max(-dist, 0))

Submission status: Accepted

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
es = [[] for _ in range(N)]
rs = [[] for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    es[a].append((b,P-c))
    rs[b].append(a)

stack = [0]
govisit = set([0])
while stack:
    v = stack.pop()
    for to,_ in es[v]:
        if to in govisit: continue
        govisit.add(to)
        stack.append(to)

stack = [N-1]
backvisit = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in backvisit: continue
        backvisit.add(to)
        stack.append(to)
use = govisit & backvisit

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for fr,e in enumerate(es):
        if fr not in use: continue
        for to,c in e:
            if to not in use: continue
            if dist[to] > dist[fr] + c:
                dist[to] = dist[fr] + c
                if i==N-1:
                    print(-1)
                    exit()
print(max(0,-dist[-1]))

Submission status: Accepted

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

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


def find_negative_loop(s,n,w,es):
    # s: start
    # n: number of nodes
    # w: number of edges
    # es[i]: from, to, cost

    # d: shortest dist of s -> i
    inf = float('inf')
    d = [inf for _ in range(n)]
    d[s] = 0
    for i in range(2*n):
        for j in range(w):
            p, q, r = es[j]
            if d[p] != inf and (d[q] > d[p] + r):
                d[q] = d[p] + r
                if i >= n:
                    d[q] = (-1)*inf
        if i == n-1:
            temp = d[-1]
    return temp, d[-1]

temp, d = find_negative_loop(0, n, m, es)
if temp == d:
    if temp > 0:
        print(0)
    else:
        print(-temp)
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


def BellmanFord(edges, v, source):
    INF = float("inf")
    dist = [INF for _ in range(v)]
    dist[source] = 0
    for i in range(2 * v + 1):
        for now, fol, cost in edges:
            if dist[now] != INF and dist[fol] > dist[now] + cost:
                dist[fol] = dist[now] + cost
                if i >= v:
                    dist[fol] = -INF
    if dist[-1] == -INF:
        return -1
    else:
        return max(0, -dist[-1])


n, m, p = map(int, readline().split())
abc = [list(map(int, readline().split())) for i in range(m)]
edges = []
for a, b, c in abc:
    edges.append((a - 1, b - 1, p - c))
print(BellmanFord(edges, n, 0))

Submission status: Accepted

Solution code:
import queue as qu
def BFS(connectinons:list,N):
    bfs_connections=[[] for _ in range(N)]
    reverse_connections=[[] for _ in range(N)]


    for A,B,_ in connectinons:
        bfs_connections[A].append(B)
        reverse_connections[B].append(A)
    
    reachable= [False]*N
    rev_reachable=[False]*N

    q = qu.Queue()
    q.put(0)

    while not q.empty():
        node = q.get()
        if reachable[node]:
            continue
        reachable[node]=True

        for B in bfs_connections[node]:
            q.put(B)
    
    q = qu.Queue()
    q.put(N-1)

    while not q.empty():
        node = q.get()
        if rev_reachable[node]:
            continue
        rev_reachable[node]=True

        for B in reverse_connections[node]:
            q.put(B)

    use=set()
    for i in range(N):
        if reachable[i] and rev_reachable[i]:
            use.add(i)
        
    return [[a,b,c] for a,b,c in connectinons if a in use and b in use]









def b_ford(connections:list,N):
    inf=float('inf')
    cost =[inf]*N
    cost[0]=0
    newchanged = set()
    oldchanged = set()

    for i in range(N):
        oldchanged=newchanged
        newchanged= set()
        for A,B,C in connections:
            if cost[A]+C < cost[B]:
                newchanged.add(B)
                cost[B]=cost[A]+C
        
        if not newchanged:
            if cost[-1] > 0:
                print(0)
            else:
                print(-cost[-1])
            return
    print(-1)







def resolve():
    N,M,P = map(int,input().split())
    
    connections = []
    for i in range(M):
        A,B,C = map(int,input().split())
        
        connections.append([A-1,B-1,P-C])
    #print(connections)
    connections = BFS(connections,N)
    #print(connections)
    b_ford(connections,N)

resolve()

Submission status: Accepted

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


can_reach = [0]*n
stack = [0]
while stack:
    v = stack.pop()
    if can_reach[v]:
        continue
    can_reach[v] = 1
    for v2 in forward_edges[v]:
        if can_reach[v2]:
            continue
        stack.append(v2)


INF = 10**10
dist = [INF]*n
dist[0] = 0
for i in range(n):
    for v, v2, c in edges:
        if dist[v2] <= dist[v]+c:
            continue
        dist[v2] = dist[v]+c

negative = [0]*n
for i in range(n):
    for v, v2, c in edges:
        if dist[v2] <= dist[v]+c:
            continue
        if not can_reach[v2]:
            continue
        dist[v2] = -INF
        negative[v2] = 1

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

Submission status: Accepted

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

def main():
    N,M,P = map(int,input().split())
    
    def BellmanFord(edges,v,source):
        INF = float("inf")
        dist = [INF for _ in range(v)]
        dist[source] = 0
        for i in range(2*v+1):
            for now,fol,cost in edges:
                if (dist[now] != INF and dist[fol]>dist[now]+cost):
                    dist[fol] = dist[now]+cost
                    if i >= v:
                        dist[fol] = -INF
        if dist[v-1] == -INF:
            return -1
        else:
            return max(0,-1*dist[v-1])
    
    edges = []
    for _ in range(M):
        a,b,c = map(int,input().split())
        edges.append((a-1,b-1,P-c))
    
    print(BellmanFord(edges,N,0))

if __name__ == "__main__":
    main()

Submission status: Accepted

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

def main():
    N,M,P = map(int,input().split())
    
    def BellmanFord(edges,v,source):
        INF = float("inf")
        dist = [-INF for _ in range(v)]
        dist[source-1] = 0
        for i in range(2*v+1):
            for now,fol,cost in edges:
                b = dist[v-1]
                if (dist[now] != -INF and dist[fol]<dist[now]+cost):
                    dist[fol] = dist[now]+cost
                    if i > v-1:
                        dist[fol] = INF
        if dist[N-1] == INF:
            return -1
        else:
            return max(0,dist[N-1])
    
    edges = []
    for _ in range(M):
        a,b,c = map(int,input().split())
        edges.append((a-1,b-1,c-P))
    
    print(BellmanFord(edges,N,1))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, m, p = map(int, input().split())
abcs = [list(map(int, input().split())) for _ in range(m)]
distance = [-1000000 * n] * (n + 1)

distance[1] = 0
reachable1 = set([1])
reachableN = set([n])
for _ in range(n + 1):
    for a, b, c in abcs:
        if distance[b] < distance[a] + c - p:
            distance[b] = distance[a] + c - p
        # 枝刈りが必要                                                                                                                                                                                                                
        if a in reachable1:
            reachable1.add(b)
        if b in reachableN:
            reachableN.add(a)

for a, b, c in abcs:
    if (distance[b] < distance[a] + c - p) and (a in reachable1) and (b in reachableN):
        print(-1)
        exit(0)

print(max(distance[n], 0))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n,m,p = map(int,input().split())
abd = [list(map(int,input().split())) for i in range(m)]
come = [[] for i in range(n+1)]
for a,b,d in abd:
  come[b].append(a)
visitable = [0]*(n+1)
stack = [n]
visitable[n] = 1
while stack:
  x = stack.pop()
  for y in come[x]:
    if visitable[y] == 0:
      visitable[y] = 1
      stack.append(y)
score = [10**15 for i in range(n+1)]
score[1] = 0
for j in range(n+1):
  flg = 0
  for i in range(m):
    v1,v2,e = abd[i]
    if visitable[v1] & visitable[v2] == 0:
      continue 
    e = -e+p
    if score[v1] != 10**15 and score[v2] > score[v1]+e:
      score[v2] = score[v1]+e
      flg = 1
      if j == n-1:
        last = score[:]
      if j == n:
        onemore = score[:]
  if flg == 0:
    break
if flg == 0:
  print(max(0,-score[n]))
else:
  if last == onemore:
    print(max(last[n],0))
  else:
    print(-1)

Submission status: Accepted

Solution code:
#ABC137-E Coins Respawn
"""
1の移動に対してpだけコストを支払うと考える事ができる。
pを考慮しても無限にコインを増やすような閉路が存在する場合、-1を出力、そうでないならばコストが最大と
なるようにゴールに行くことが最適である。
すべての辺上のコインをマイナス値でもって、pを足し合わせることによってこれが達成できる。
ベルマンフォード法を用いて負の重みを扱えるようにする。
この時、負の閉路の検出が可能だが、この問題では1→Nへの道とは関係ない場所に負の閉路が存在しても、
それは無限にコインを増やせるとは言わない。
よって、まず1と関係する辺をすべて求めた後、Nと関係する逆辺を求める事により、どちらもに該当しない辺を除去することで達成できる。
"""
import sys
from collections import deque
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n,m,p = map(int,readline().split())
g = [[] for i in range(n)]
rev = [[] for i in range(n)] #逆辺
for i in range(m):
	x,y,w = map(int,readline().split())
	x,y,w = x-1,y-1,-w
	g[x].append((y,w+p))
	rev[y].append((x,w+p))

res1 = [0]
queue = deque([0])
#頂点1からスタートして、関係のある辺を求める
while True:
	if len(queue) <= 0:
		break
	v = queue.pop()
	for e in g[v]:
		if e[0] not in res1:
			res1.append(e[0])
			queue.append(e[0])
		else:
			continue

res2 = [n-1]
queue = deque([n-1])
#頂点nからスタートして、関係のある辺を求める
while True:
	if len(queue) <= 0:
		break
	v = queue.pop()
	for e in rev[v]:
		if e[0] not in res2:
			res2.append(e[0])
			queue.append(e[0])
		else:
			continue
itr = set([i for i in range(n)])
res3 = itr - (set(res1) & set(res2))

def BellmanFord(edges,num_v,source): #[x,y,weight]のリスト,頂点数,始点
	#グラフの初期化
	inf=float("inf")
	dist=[inf for i 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: return [] #負の閉路が存在する場合,空のリストが帰る
  
	return dist

edges = []
for i in range(n):
	if i in res3:
		continue
	for j in g[i]:
		if j[0] in res3:
			continue
		edges.append([i,j[0],j[1]])

dist = BellmanFord(edges,n,0)

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

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Bellman_Ford(s,n,w,es,ppp):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [Max] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    po = 0
    while po < 2*N + 2*M:
        update = False
        for p,q,r in es:
        # e: 辺iについて [from,to,cost]
            if d[p] != Max and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
                if (ppp[q] != 0 and po > N):
                    d[-1] = None
                    update = False
                    break
        if not update:
            break
        po += 1
    return d

import heapq

def dijkstra(n,w,e):
    #n:辺数,w:スタート一

    edge = [[] for i in range(n)]
    dg = 10**18
    # edge[i]:[コスト]
    for i in e:
        x,y = i
        z = 1
        x -= 1
        y -= 1
        edge[x].append(dg + y)
        
    
    s = w-1
    d = [-1]*n
    
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d




N,M,P = m()

es = []
ess = []

gr = [[] for i in range(N)]

ok = [0 for i in range(N)]

for _ in range(M):

    x,y,z = map(int,input().split())

    x -= 1
    y -= 1
    es.append([x,y,-z+P])
    gr[y].append(x)


ok[-1] = 1
po = cl.deque([N-1])
while po:
    o = po.popleft()
    
    for i in gr[o]: 
        if not ok[i]:
            po.append(i)
            ok[i] = 1





po = Bellman_Ford(0,N,M,es,ok)


print(-1 if po[-1] == None else -po[-1] if po[-1] <= 0 else 0)