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:
def BF(N, edges, start):
    D = {}
    P = {}
    for i in range(N):
        P[i] = None
        if i == start:
            D[i] = 0
        else:
            D[i] = float("inf")

    for i in range(N-1):
        for edge in edges:
            a, b, c = edge
            if D[b] > D[a] + c:
                D[b] = D[a] + c
                P[b] = a

    ret = (D, P)

    Nega = {}
    for i in range(N):
        Nega[i] = False
    
    for i in range(N):
        for edge in edges:
            a, b, c = edge
            if Nega[a] == True:
                Nega[b] = True
            if D[b] > D[a] + c:
                D[b] = D[a] + c
                P[b] = a
                Nega[b] = True
        
    return (D, P, Nega)

N, M, P = (int(i) for i in input().split())
edges = []
for i in range(M):
    A, B, C = (int(i) for i in input().split())
    edges.append((A-1, B-1, P-C))
D, P, Nega = BF(N, edges, 0)
if Nega[N-1] == True:
    print(-1)
else:
    if D[N-1] <= 0:
        print(-D[N-1])
    else:
        print(0)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


def main():
    N, M, P = map(int, input().split())
    edge = [[] for _ in range(N)]
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge[A].append((B,C))
        g[A].append(B)
        rg[B].append(A)

    # 0 => N-1の間にある閉路を検出したいので
    # 0とN-1からたどりつけない場所は前処理で取り除く
    visited = [False] * N
    rvisited = [False] * N
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        visited[v] = True
        for i in g[v]:
            if not visited[i]:
                Q.append(i)

    Q.append(N-1)
    while Q:
        v = Q.popleft()
        rvisited[v] = True
        for i in rg[v]:
            if not rvisited[i]:
                Q.append(i)
    
    OK = [False] * N
    for i in range(N):
        OK[i] = visited[i] & rvisited[i]
    
    new_edge = [[] for _ in range(N)]
    for s in range(N):
        for t, c in edge[s]:
            if OK[s]:
                new_edge[s].append((t,c))

    flag = True
    d = [float('inf')] * N
    d[0] = 0
    for _ in range(N):
        flag = False
        for v, e in enumerate(new_edge):
            for t, c in e:
                if d[v] != float('inf') and d[v] + c < d[t]:
                    d[t] = d[v] + c
                    flag = True
        if not flag:
            print(max(0,-d[N-1]))
            exit()
    else:
        print(-1)
        exit()


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def main():
    N, M, P = map(int, input().split())
    edge = [[] for _ in range(N)]
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge[A].append((B,C))
        g[A].append(B)
        rg[B].append(A)

    # 0 => N-1の間にある閉路を検出したいので
    # 0とN-1からたどりつけない場所は前処理で取り除く
    visited = [False] * N
    rvisited = [False] * N
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        visited[v] = True
        for i in g[v]:
            if not visited[i]:
                Q.append(i)

    Q.append(N-1)
    while Q:
        v = Q.popleft()
        rvisited[v] = True
        for i in rg[v]:
            if not rvisited[i]:
                Q.append(i)
    
    OK = [False] * N
    for i in range(N):
        OK[i] = visited[i] & rvisited[i]
    
    new_edge = []
    for s in range(N):
        for t, c in edge[s]:
            if OK[s]:
                new_edge.append((s,t,c))

    flag = True
    d = [float('inf')] * N
    d[0] = 0
    step = 0
    while flag:
        flag = False
        for A, B, C in new_edge:
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)

    # 0 => N-1の間にある閉路を検出したいので
    # 0とN-1からたどりつけない場所は前処理で取り除く
    visited = [False] * N
    rvisited = [False] * N
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        visited[v] = True
        for i in g[v]:
            if not visited[i]:
                Q.append(i)

    Q.append(N-1)
    while Q:
        v = Q.popleft()
        rvisited[v] = True
        for i in rg[v]:
            if not rvisited[i]:
                Q.append(i)
    
    OK = [False] * N
    for i in range(N):
        OK[i] = visited[i] & rvisited[i]
    
    flag = True
    d = [10 ** 9] * N
    d[0] = 0
    step = 0
    while flag:
        flag = False
        for A, B, C in edge:
            if not OK[A]:
                continue
            if not OK[B]:
                continue
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)

    
    visited = [False] * N
    rvisited = [False] * N
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        visited[v] = True
        for i in g[v]:
            if not visited[i]:
                Q.append(i)

    Q.append(N-1)
    while Q:
        v = Q.popleft()
        rvisited[v] = True
        for i in rg[v]:
            if not rvisited[i]:
                Q.append(i)
    
    OK = [False] * N
    for i in range(N):
        OK[i] = visited[i] & rvisited[i]
    
    flag = True
    d = [float('inf')] * N
    d[0] = 0
    step = 0
    while flag:
        flag = False
        for A, B, C in edge:
            if not OK[A]:
                continue
            if not OK[B]:
                continue
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)
    visited = [False] * N
    rvisited = [False] * N
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        visited[v] = True
        for i in g[v]:
            if not visited[i]:
                Q.append(i)

    Q.append(N-1)
    while Q:
        v = Q.popleft()
        rvisited[v] = True
        for i in rg[v]:
            if not rvisited[i]:
                Q.append(i)
    
    OK = [False] * N
    for i in range(N):
        OK[i] = visited[i] & rvisited[i]
    
    flag = True
    d = [float('inf')] * N
    d[0] = 0
    step = 0
    while flag:
        flag = False
        for A, B, C in edge:
            if not OK[A]:
                continue
            if not OK[B]:
                continue
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()

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


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M,P = map(int,input().split())
E = []
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c=-c+P
  E.append([a,b,c])
  
def BellmanFord(s,g):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(N)]
  dist[s]=0
  rout=[]
  
  #辺の緩和
  for i in range(N*N):
    for edge in E:
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==N*N-1 and edge[1]==g: return -1
  
  return max(0,-dist[g])
print(BellmanFord(0,N-1))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10**10
 
class ExtendedBellmanFord:
    def __init__(self, edge):
        self.f_edge = edge
        self.b_edge = [[] for _ in range(len(edge))]
        for src, es in enumerate(edge):
            for dst, cost in es:
                self.b_edge[dst].append((src, -cost))

    def bellman_ford(self, mask, start):
        dist = [INF] * n
        dist[start] = 0
        for _ in range(n):
            update = False
            for i, es in enumerate(self.f_edge):
                if not mask[i]:
                    continue
                for to, cost in es:
                    if not mask[to]:
                        continue
                    if dist[i] != INF and dist[i] + cost < dist[to]:
                        dist[to] = dist[i] + cost
                        update = True
            if not update:
                return dist
        else:
            # Minus loops detected
            return -INF

    def calc(self, start, end):
        visited = [False] * n
        visited[start] = True
        st = [start]
        while st:
            node = st.pop()
            for to, _ in self.f_edge[node]:
                if not visited[to]:
                    visited[to] = True
                    st.append(to)
        rvisited = [False] * n
        rvisited[end] = True
        st = [end]
        while st:
            node = st.pop()
            for to, _ in self.b_edge[node]:
                if not rvisited[to]:
                    rvisited[to] = True
                    st.append(to)
        mask = [forward and backward for forward, backward in zip(visited, rvisited)]
        dist = self.bellman_ford(mask, start)
        if dist == -INF:
            return -INF
        else:
            return dist[end]

if __name__ == "__main__":
    n, m, p = [int(item) for item in input().split()]
    edge = [[] for _ in range(n)]
    for i in range(m):
        a, b, c = [int(item) for item in input().split()]
        a -= 1; b -= 1; c -= p
        c *= -1
        edge[a].append((b, c))
    
    EBF = ExtendedBellmanFord(edge)
    ret = EBF.calc(0, n-1)
    if ret == -INF:
        print(-1)
    else:
        print(max(0, -ret))

Submission status: Time Limit Exceeded

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

class BellmanFord():
	def __init__(self, adj, start, size):
		self.adj = adj
		self.start = start
		self.size = size
		self.dist = [10**30 for _ in range(self.size)]
		self.dist[self.start] = 0

	def solve(self):
		for _ in range(self.size-1):
			for x in range(self.size):
				for y, w in self.adj[x]:
					if s_reachable[x] and s_reachable[y] and g_reachable[x] and g_reachable[y]:
						if self.dist[y] > self.dist[x] + w:
							self.dist[y] = self.dist[x] + w
		for x in range(self.size):
			for y, w in self.adj[x]:
				if s_reachable[x] and s_reachable[y] and g_reachable[x] and g_reachable[y]:
					if self.dist[y] > self.dist[x] + w:
						return False

		return True

	def GetDistance(self, goal):
		return self.dist[goal]

n, m, p = map(int, input().split())
adj = [[] for _ in range(n)]
adj_rev = [[] for _ in range(n)]

for _ in range(m):
	a, b, c = map(int, input().split())
	adj[a-1].append((b-1, -c+p))
	adj_rev[b-1].append(a-1)

s_reachable = [False for _ in range(n)]
s_reachable[0] = True
g_reachable = [False for _ in range(n)]
g_reachable[n-1] = True

def dfs_s(x):
	for v, w in adj[x]:
		if not s_reachable[v]:
			s_reachable[v] = True
			dfs_s(v)
	return

def dfs_g(x):
	for v in adj_rev[x]:
		if not g_reachable[v]:
			g_reachable[v] = True
			dfs_g(v)
	return

dfs_s(0)
dfs_g(n-1)

bf = BellmanFord(adj, 0, n)
if not bf.solve():
	print(-1)
else:
	print(max(-bf.GetDistance(n-1), 0))

Submission status: Time Limit Exceeded

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

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

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

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

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

    for k in range(n):
        for p in range(n):
            for i, j in g[p]:
                dist[i] = max(dist[i], dist[p]+j-r)
        if k == n-2:
            d1 = [t for t in dist]
        if k == n-1:
            d2 = [t for t in dist]

    # 1からでもnの間に負の閉路があるときは-1
    if d1 == d2:
        print(max(d1[-1], 0))
    else:
        print(-1)
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N, M, P = map(int, input().split())
e = dd(list)
for _ in range(M):
  a, b, c = map(int, input().split())
  e[a].append((b, -c + P))
class BellmanFord:
  def __init__(self, n, e):
    self.n = n
    self.edges = []
    for k in e.keys():
      for t in e[k]:
        self.edges.append((k, t[0], t[1]))
  def path(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    for i in range(self.n + 1):
      for (u, v, c) in self.edges:
        if d[u] != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
    return d[t]
  def path_findloop(self, s, t):
    d = [float("inf")] * (self.n + 1)
    d[s] = 0
    first = 0
    for i in range(1, self.n * 2 + 1):
      for (u, v, c) in self.edges:
        if u != float("inf") and (d[u] + c < d[v]):
          d[v] = d[u] + c
          if i > N: d[v] = -float("inf")
      if i == self.n:
        first = d[t] + 0
      elif i == self.n * 2:
        if first != d[t]:
          return "-loop"
    return d[t]
bf = BellmanFord(N, e)
res = bf.path_findloop(1, N)
if res == "-loop": print(-1)
else: print(max(0, -res))

Submission status: Time Limit Exceeded

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

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

def Bellman_Ford(edges, start, N):
    inf = float("inf")
    # dist[i]: 頂点iまでの最短距離
    dist = [inf for i in range(N)]
    dist[start] = 0

    for i in range(N+N):
        for a,b,c in edges:
            if a != inf and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c
                # startからgoalまでに負閉路がある場合
                if i >= N:
                    dist[b] = -inf
        # 一回目のベルマンフォード法の結果
        if i == N-1:
            first_time = dist[-1]
    # (一回目,二回目)
    return first_time, dist[-1]

first,second = Bellman_Ford(edge, 0, N)
if first != second:
    answer = -1
else:
    answer = max(0,-second)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
inf = float('inf')
# ベルマンフォード法 計算量(VE)
# [引数]: 隣接リスト, 始点, 終点
class Bellmanford:
    def __init__(self, to : list, start : int, goal : int):
        self.N = len(to)
        self.to = [s[:] for s in to]
        self.start = start
        self.goal = goal
        self.dist = [inf] * self.N
        self.dist[start] = 0
    
    # self.distを更新
    def update(self) -> None:
        for _ in range(self.N - 1):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
    
    # グラフの負閉路検出
    def detection(self) -> bool:
        exists_negative_cycle = False
        for v, s in enumerate(self.to):
            if not s: continue
            for nv, w in s:
                if self.dist[nv] > self.dist[v] + w:
                    self.dist[nv] = self.dist[v] + w
                    exists_negative_cycle = True
        return exists_negative_cycle
    
    # スタートからゴールまでのパスの負閉路検出
    def detection_stog(self) -> bool:
        exists_negative_cycle_stog = False
        is_updated = [False] * self.N
        for _ in range(self.N):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
                        is_updated[nv] = True
                    if is_updated[v] is True:
                        is_updated[nv] = True
        exists_negative_cycle_stog = is_updated[self.goal]
        return exists_negative_cycle_stog

N, M, P = map(int,input().split())
to = [[] for _ in range(N)]
for _ in range(M):
    A, B, C = map(int,input().split())
    A -= 1; B -= 1
    C -= P
    to[A].append((B, -C))

BF = Bellmanford(to, 0, N-1)
BF.update()

if BF.detection_stog():
    ans = -1
else:
    ans = max(-BF.dist[N-1], 0)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
inf = float('inf')
# ベルマンフォード法 計算量(VE)
# [引数]: 隣接リスト, 始点, 終点
class Bellmanford:
    def __init__(self, to : list, start : int, goal : int):
        self.N = len(to)
        self.to = [s[:] for s in to]
        self.start = start
        self.goal = goal
        self.dist = [inf] * self.N
        self.dist[start] = 0
        self.exists_negative_cycle = False
        self.exists_negative_cycle_stog = False
        self.is_updated = [False] * self.N
    
    # self.distを更新
    def update(self) -> None:
        for _ in range(self.N - 1):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
    
    # グラフの負閉路検出
    def detection(self) -> bool:
        for v, s in enumerate(self.to):
            if not s: continue
            for nv, w in s:
                if self.dist[nv] > self.dist[v] + w:
                    self.dist[nv] = self.dist[v] + w
                    self.exists_negative_cycle = True
        return self.exists_negative_cycle
    
    # スタートからゴールまでのパスの負閉路検出
    def detection_stog(self) -> bool:
        for _ in range(self.N):
            for v, s in enumerate(self.to):
                if not s: continue
                for nv, w in s:
                    if self.dist[nv] > self.dist[v] + w:
                        self.dist[nv] = self.dist[v] + w
                        self.is_updated[nv] = True
                    if self.is_updated[v] is True:
                        self.is_updated[nv] = True
        self.exists_negative_cycle_stog = self.is_updated[self.goal]
        return self.exists_negative_cycle_stog

N, M, P = map(int,input().split())
to = [[] for _ in range(N)]
for _ in range(M):
    A, B, C = map(int,input().split())
    A -= 1; B -= 1
    C -= P
    to[A].append((B, -C))

BF = Bellmanford(to, 0, N-1)
BF.update()

if BF.detection_stog():
    ans = -1
else:
    ans = max(-BF.dist[N-1], 0)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
inf = float('inf')
# ベルマンフォード法
# 計算量O(VE) V:頂点数, E:辺の数
# [引数]   n:頂点数, edges:辺集合, start:始点, end:終点
# [返り値] dist:startからの最短距離, exists_negative_cycle: 負閉路が存在するかどうか
def bellmanford(n : int, edges : list, start : int, goal : int) -> (list, bool):
    dist = [inf] * n
    dist[start] = 0
    exist_negative_cycle = True

    # 負閉路を含まないとき、頂点数nなら更新は高々n-1回で済む
    for _ in range(N-1):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w


    # (1)グラフに負閉路が含まれるときの検出
    # N回目で更新があったとき、グラフは負閉路を含む
    # for v, nv, w in edges:
    #     if dist[nv] > dist[v] + w:
    #         is_cycle = False

    # (2)startとgoalのパスに負閉路が含まれるときの検出
    is_updated = [False] * n
    for _ in range(N):
        for v, nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w
                is_updated[nv] = True
            if is_updated[v] is True:
                is_updated[nv] = True

    exist_negative_cycle = is_updated[goal]

    return dist, exist_negative_cycle

N, M, P = map(int,input().split())
edges = []
for _ in range(M):
    A, B, C = map(int,input().split())
    A -= 1; B -= 1
    C = C - P
    edges.append((A, B, -C))

dist, exist_negative_cycle = bellmanford(N, edges, 0, N-1)

if exist_negative_cycle is True:
    ans = -1
else:
    ans = max(-dist[N-1], 0)

print(ans)

Submission status: Time Limit Exceeded

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

def main():
    N, M, P = map(int, input().split())
    Edges = [list(map(int, input().split())) for _ in range(M)]
    INF = 10**18

    graph1 = [[] for _ in range(N+1)]
    graph2 = [[] for _ in range(N+1)]
    for a, b, c in Edges:
        graph1[a].append(b)
        graph2[b].append(a)

    checked1 = [False]*(N+1)
    checked1[1] = True
    q = [1]
    while q:
        qq = []
        for p in q:
            for np in graph1[p]:
                if not checked1[np]:
                    checked1[np] = True
                    qq.append(np)
        q = qq
    
    checked2 = [False]*(N+1)
    checked2[N] = True
    q = [N]
    while q:
        qq = []
        for p in q:
            for np in graph2[p]:
                if not checked2[np]:
                    checked2[np] = True
                    qq.append(np)
        q = qq
    
    Canuse = [False]*(N+1)
    for i in range(1, N+1):
        if checked1[i] and checked2[i]:
            Canuse[i] = True



    D = [INF for _ in range(N+1)]
    D[1] = 0
    for i in range(2*N+100):
        update = False
        for a, b, c in Edges:
            if not Canuse[a] or not Canuse[b]: continue
            if D[b] > D[a] + P - c:
                D[b] = D[a] + P - c
                update = True


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

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
E = [None] * M
for i in range(M):
    a, b, c = map(int, input().split())
    E[i] = (a - 1, b - 1, P - c)
INF = float("inf")
d = [INF for _ in range(N)]
d[0] = 0
for i in range(2*N):
    for f, t, w in E:
        if d[t] > d[f] + w:
            d[t] = d[f] + w
            if i >= N:
                d[t] = -INF
    if i == N-1:
        dN = d[-1]
if dN != d[-1]:
    print(-1)
elif dN > 0:
    print(0)
else:
    print(-dN)

Submission status: Time Limit Exceeded

Solution code:
#####コピペ
def BellmanFord(edges, num_v, source):
    # グラフの初期化
    inf = float("inf")
    dist = [-inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    buf = 0
    for i in range(num_v * 2):
        for edge in edges:
            if dist[edge[1] - 1] < dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i >= num_v:
                    dist[edge[1] - 1] = inf
        if i == num_v - 1:
            buf = dist[-1]
    if dist[-1] != buf or dist[-1] == -inf:
        return -1
    return max(dist[-1], 0)
##########################################################################
from scipy.sparse.csgraph import csgraph_from_dense,dijkstra,floyd_warshall
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = []

N, M, P = LI()
cou = int(0)
maxC = 10000
d = [[float("inf") for i in range(N)] for i in range(N)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
V = []*M
for i in range(M):
    a, b, c = list(map(int,input().split()))
    V.append((a,b,c-P))
print(BellmanFord(V, N, 1))


#print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") ]*(N+1)	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
for i in range(new_N):
	for a,b,c in fedge:
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
st=set()
while q:
	fro=q.popleft()
	Visit[fro]=1
	st.add(fro)
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
revst=set()
while q:
	fro=q.popleft()
	Visit[fro]=1
	revst.add(fro)
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

#1からもNからも到達可能な頂点の集合
use = st & revst

new_N=sum(use)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if a in use and b in use:
		fedge.append((a,b,c))


D=[ float("-inf") for _ in range(N+1) ]	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
cnt=0
for i in range(new_N):
	for a,b,c in fedge:
		cnt+=1
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])