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: Time Limit Exceeded

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 - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

def bellman_ford2(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(2 * n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

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
    cost -= p
    graph[a].append((b, cost))
    rev_graph[b].append((a, cost))

visited = [False] * n
def dfs():
    q = deque([0])
    visited[0] = True
    while q:
        v = q.pop()
        for nxt_v, _ in graph[v]:
            if visited[nxt_v]:
                continue
            visited[nxt_v] = True
            q.append(nxt_v)
dfs()

visited2 = [False] * n
def dfs2():
    q = deque([n - 1])
    visited2[n - 1] = True
    while q:
        v = q.pop()
        for nxt_v, _ in rev_graph[v]:
            if visited2[nxt_v]:
                continue
            visited2[nxt_v] = True
            q.append(nxt_v)
dfs2()

#print(visited)
#print(visited2)

boolian, dist = bellman_ford(0, graph)
boolian, dist2 = bellman_ford2(0, graph)
if not boolian:
    print(max(dist[-1], 0))
else:
    for i in range(n):
        if dist[i] < dist2[i]:
            print(-1)
            exit()
    print(dist2[-1])

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
adjacent = []
score = ['None' for i in range(N)]
score[0] = 0
for i in range(M):
    a, b, c = map(int, input().split())
    adjacent.append([a-1, b-1, c-P])
for i in range(N):
    for j in adjacent:
        if score[j[1]] == 'None' and score[j[0]] != 'None':
            score[j[1]] = score[j[0]] + j[2]
        if score[j[1]] != 'None' and score[j[0]] != 'None':
            if score[j[1]] < score[j[0]] + j[2]:
                score[j[1]] = score[j[0]] + j[2]
    if i == N-2:
        t = score[N-1]
    if i == N-1:
        if t != score[N-1]:
            score[N-1] = 1e+15
if score[N-1] < 1e+15:
    print(max(0,t))
else:
    print(-1)

Submission status: Time Limit Exceeded

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

edges = []
toE = [[] for _ in range(N)]
frE = [[] for _ in range(N)]
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    edges.append((fr, to, -(c - P)))
    toE[fr].append(to)
    frE[to].append(fr)

def getVisitedList(s, edges):
    visited = [False] * N
    st = [s]
    visited[s] = True
    while st:
        now = st.pop()
        for to in edges[now]:
            if not visited[to]:
                visited[to] = True
                st.append(to)
    return visited

canGo = getVisitedList(0, toE)
canBack = getVisitedList(N - 1, frE)

def sol():
    minDist = [10**18] * N
    minDist[0] = 0
    for i in range(N + 1):
        for fr, to, c in edges:
            d = minDist[fr] + c
            if minDist[to] > d:
                if i == N and canGo[fr] and canBack[to]:
                    return -1
                minDist[to] = d
    return max(0, -minDist[N - 1])

print(sol())

Submission status: Time Limit Exceeded

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

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

# 到達できる地点を決める
reach1 = [False] * (N + 1)
reach1[1] = True
node = [1]
while node:
    s = node.pop()
    for t, _ in edge[s]:
        if not reach1[t]:
            reach1[t] = True
            node.append(t)

reach2 = [False] * (N + 1)
reach2[N] = True
node = [N]
while node:
    s = node.pop()
    for t in ein[s]:
        if not reach2[t]:
            reach2[t] = True
            node.append(t)

can_go = []
Vertices = []
for i, (x, y) in enumerate(zip(reach1, reach2)):
    can_go.append(x & y)
    if x & y:
        Vertices.append(i)


inf = 10**18
cost = [inf] * (N + 1)
cost[1] = 0
for _ in range(M + 5):
    update = False
    for s in Vertices:
        now = cost[s]
        for t, c in edge[s]:
            if not can_go[t]:
                continue
            if cost[t] > now + c:
                cost[t] = now + c
                update = True


if update:
    print(-1)
else:
    print(max(0, -cost[N]))

Submission status: Time Limit Exceeded

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 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
  print(max(-d[n-1],0));exit()

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))
if find_negative_loop(n,ee):print(-1);exit()
bellman_ford(0,n,ee)

Submission status: Time Limit Exceeded

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

#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)]
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
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: Time Limit Exceeded

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

#負の閉路検出
#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: Time Limit Exceeded

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: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
INF = 10**18

edges = []
E = [[] for _ in range(N)]
R = [[] for _ in range(N)]
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    edges.append((fr, to, -(c - P)))
    E[fr].append(to)
    R[to].append(fr)

def existsPath(s, edges):
    visited = [False] * N
    visited[s] = True
    st = [s]
    while st:
        now = st.pop()
        for to in edges[now]:
            if visited[to]:
                continue
            st.append(to)
            visited[to] = True
    return visited

canGoFrom1 = existsPath(0, E)
canGoFromN = existsPath(N - 1, R)

minDist = [INF] * N
minDist[0] = 0
for i in range(N):
    for fr, to, c in edges:
        d = minDist[fr] + c
        if minDist[to] > d:
            if i == N - 1 and canGoFrom1[fr] and canGoFromN[to]:
                print('-1')
                exit()
            minDist[to] = d

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

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dfs(x,f):
        dx = d[x]
        for y,c in v[x]:
            if not f[y]:
                nd = dx+c
                if d[y] < nd:
                    d[y] = nd
                    f[y] = 1
                    dfs(y,f)
                    f[y] = 0
            else:
                nd = dx+c
                if nd > d[y]:
                    d[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        w = c-p
        v[a].append((b,w))
    d = [-float("inf")]*n
    d[0] = 0
    f = [0]*n
    f[0] = 1
    dfs(0,f)
    ans = d[n-1]
    if ans == float("inf") or ans == -float("inf"):
        print(-1)
    else:
        print(max(0,ans))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
n,m,p = map(int,input().split())
# キュー
from collections import deque

# bellman_ford
# 負の経路がある場合は、(-1,-1)を返却する
def bellman_ford(links, start, end, n):
    inf = 10**10
    d = [inf] * (n+1)
    d[start] = 0
    parent = [-1] * (n+1)

    for _ in range(n):
        update = False
        for i in range(1,n+1):
            for j in links[i]:
                cost,neigh = j
                if(d[neigh] > d[i] + cost):
                    d[neigh] = d[i] + cost
                    parent[neigh] = i
                    update = True

        if(not update):
            # 経路の算出
            route = [end]
            now = end
            while(now != start):
                now = parent[now]
                route.append(now)

            return d,route[::-1]

    # 負の経路がある場合（n-1回の更新で終わらない場合）
    return -1,-1

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

can_go_1 = set()
can_go_n = set()

d = deque()
d.append(1)
while(d):
    tmp = d.pop()
    can_go_1.add(tmp)
    for i in graph[tmp]:
        if(not i in can_go_1):
            d.append(i)

d = deque()
d.append(n)
while(d):
    tmp = d.pop()
    can_go_n.add(tmp)
    for i in graph_rev[tmp]:
        if(not i in can_go_n):
            d.append(i)

can_go = can_go_1 & can_go_n

graph2 = [[] for _ in range(n+1)]
for tmp in abc:
    a,b,c = tmp
    if(a in can_go)&(b in can_go):
        graph2[a].append((c,b))

d , _ = bellman_ford(graph2, 1, n, n)
if(d == -1):
    print(-1)
else:
    ans = d[n] * -1
    print(max(0,ans))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
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


def dfs(v, parent):
    can_reach[v] = 1
    for v2 in forward_edges[v]:
        if parent == v2:
            continue
        dfs(v2, v)


dfs(0, -1)

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: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n, m, p = map(int, input().split())
edges = []
forward_edges = [[] for _ in range(n)]
backward_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)
    backward_edges[b].append(a)

can_goal = [0]*n


def dfs(v, parent):
    can_goal[v] = 1
    for v2 in backward_edges[v]:
        if parent == v2:
            continue
        dfs(v2, v)


dfs(n-1, -1)

can_reach = [0]*n

def dfs(v, parent):
    can_reach[v] = 1
    for v2 in forward_edges[v]:
        if parent == v2:
            continue
        dfs(v2, v)

dfs(0, -1)

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
        dist[v2] = dist[v]+c
        negative[v2] = 1

got_infinity_coins = 0
for i in range(n):
    if negative[i]:
        if can_reach[i] and can_goal[i]:
            got_infinity_coins = 1
            break
            
if got_infinity_coins:
    print(-1)
else:
    print(max(0, -dist[-1]))

Submission status: Time Limit Exceeded

Solution code:
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, p-c))

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(10**5):
    for v, v2, c in edges:
        if dist[v2] <= dist[v]+c:
            continue
        dist[v2] = dist[v]+c
        negative[v2] = 1

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
n,m,p = map(int,input().split())
E1 = [[] for i in range(n)]
E2 = [[] for i in range(n)]
edge = []
for i in range(m):
    a,b,c = map(int,input().split())
    c = p-c
    a -= 1
    b -= 1
    E1[a].append(b)
    E2[b].append(a)
    edge.append((a,b,c))

dis1 = [False]*n
def dfs1(x):
    if dis1[x] == False:
        dis1[x] = True
        for nex in E1[x]:
            dfs1(nex)

dis2 = [False]*n
def dfs2(x):
    if dis2[x] == False:
        dis2[x] = True
        for nex in E2[x]:
            dfs2(nex)

dfs1(0)
dfs2(n-1)

ok = []
for i in  range(n):
    if dis1[i] and dis2[i]:
        ok.append(True)
    else:
        ok.append(False)
nedge = []
for a,b,c in edge:
    if ok[a] and ok[b]:
        nedge.append((a,b,c))

def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in nedge:
            
            if dis[a] != float("INF") and dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n+1 and check:
            return float("INF")
    
    return -dis[-1]

ans = belw()
if ans == float("INF"):
    print(-1)
else:
    print(max(ans,0))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)
from collections import defaultdict
edges = []
to = defaultdict(list) # 1から到達できるか
ot = defaultdict(list) # Nから到達できるか
N, M, P = map(int, input().split())
visited_toN = [False]*(N+1)
visited_fm1 = [False]*(N+1)    
for i in range(M):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append((a,b,-c+P))
    to[a].append(b)
    ot[b].append(a)

def dfs(v):
    global visited_fm1
    if visited_fm1[v]:return
    visited_fm1[v] = True
    for nxt in to[v]:
        dfs(nxt)
    
def dfs_r(v):
    global visited_toN
    if visited_toN[v]:return
    visited_toN[v] = True
    for nxt in ot[v]:
        dfs_r(nxt)
        
dfs(0)
dfs_r(N-1)
is_ok = []

for s, t in zip(visited_fm1,visited_toN):
    is_ok.append(s and t)


# BellmanFord    
INF = 10 ** 18
def bellmanFord(n, edges, s, g):
    """
    input
        n : 頂点の数
        edges : (始点, 終点, コスト)のリスト
        s : 探索の始点
        g : 探索の終点
    output
        sから各点への最短距離
    """    
    d = [INF] * n
    d[s] = 0
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if not is_ok[a]:continue
            if not is_ok[b]:continue
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt > n:
            print(-1)
            exit()
        # print(d,cnt)
    return d[g]



ans = bellmanFord(N,edges,0,N-1)
print(max(0,-ans))

Submission status: Time Limit Exceeded

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。
                     到達不可の場合、値はfloat("inf")
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # 始点の(最短距離, 頂点番号)をヒープに追加する

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する
                e = self.G[v][i]  # vのi個目の隣接辺e
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost  # dの更新
                    heapq.heappush(que, (d[e.to], e.to))  # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush
        return d

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: return -1

  return dist

N,M,P=map(int,input().split())
edges=[]
test=Dijkstra(N)
for i in range(0,M):
    a,b,c=map(int,input().split())
    edges.append([a,b,P-c])
    test.add(b-1,a-1,1)

use=set([N-1])
for i in range(0,N-1):
    if test.shortest_path(N-1)[i]!=10**15:
        use.add(i)

useedges=[]
for i in range(0,M):
    a,b,c=edges[i]
    if a-1 in use and b-1 in use:
        useedges.append(edges[i])

ans=BellmanFord(useedges,N,1)
if ans==-1:
    print(-1)
else:
    if -ans[N-1]>=0:
        print(-ans[N-1])
    else:
        print(0)

Submission status: Time Limit Exceeded

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

'''
PATH = [[] for _ in range(N+1)]
for _ in range(M):
    a, b, c = map(int, readline().split())
    PATH[a].append((b, c))
'''

INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N):
    update = False
    for j in range(M):
        a, b, c = ABC[j]
        pt = P - c
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i == N - 1 and b == N:
                print(-1)
                exit()

    if not update:
        break

pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, M, P = list(map(int, input().split()))
sides = []
for i in range(M):
    sides.append(list(map(int, input().split())))

scores = [-(10**10)]*N
scores[0] = 0
epoch = 0
provisional_score = 0
update_number = 1
while update_number > 0 and epoch < 2*(N-1):
    update_number = 0
    for side in sides:
        if scores[side[1]-1] < scores[side[0]-1] + side[2] - P:
            scores[side[1]-1] = scores[side[0]-1] + side[2] - P
            update_number += 1
    epoch += 1
    if epoch == N-1:
        provisional_score = scores[N-1]

if epoch == 2*(N-1) and provisional_score != scores[N-1]:
    print('-1')
else:
    print(max(scores[N-1], 0))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,M,P=map(int,input().split())
def f(x):
  x[0]-=1
  x[1]-=1
  x[2]=-(x[2]-P)
  return x
ABC=[f(list(map(int,input().split()))) for i in range(M)]
infinity=10**9
loop=set()


def BellmanFord():
  distance=[0]+[infinity]*(N-1)
  predecessor=[[] for i in range(N)]
  for i in range(N):
    for a,b,c in ABC:
      if distance[b]>distance[a]+c:
        distance[b]=distance[a]+c
        predecessor[b]=predecessor[a][:]
        predecessor[b].append(a)
  for a,b,c in ABC:
    if distance[a]+c<distance[b]:
      #print("Graph contains a negative-weight cycle",a,b,c)
      #print(-1)
      #exit(0)
      loop.add(a)
      loop.add(b)
  return distance,predecessor
d,p=BellmanFord()
#print(d,p)
ans=-min(d[-1],0)
for x in p[-1]:
  if x in loop:
    ans=-1
    break
print(ans)