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: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
    for i in range(n):
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = -1 * INF
    if d[n-1] == -1 * INF:
        return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(3*n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                if y == n-1:
                    update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i >= n - 1 and update_dn:
            return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(3*n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i >= n - 1 and update_dn:
            return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(2*n+1):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i >= n - 1 and update_dn:
            return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

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

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

INF = 10 ** 18
dist = [INF] * (N+1)
dist[1] = 0

loop = False
for i in range(2*N+100):
    for a,b,c in ABC:
        x = dist[a] + P - c
        if dist[b] > x:
            dist[b] = x
            if b == N and i > N:
                loop = True

if loop:
    answer = -1
else:
    answer = -dist[N]
    if answer < 0:
        answer = 0

print(answer)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(2*n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i == n - 1 and update_dn:
            return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i == n - 1 and update_dn:
            return False
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == False:
    print(-1)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i == n - 1 and update_dn:
            return -1
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
elif d == -1:
    print(d)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
def bellman_ford(g, s):
    INF = 10**9
    d = [INF]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        update = False # 更新が行われたか
        update_dn = False
        for x, y, z in g:
            if y != n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
            elif y == n-1 and d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
                update_dn = True
        if not update:
            break
        # 負閉路が存在
        if i == n - 1 and update_dn:
            return -1
    return d[n-1]

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

graph = []
for i in range(m):
    u, v, w = edge[i][0]-1, edge[i][1]-1, p - edge[i][2]
    graph.append([u,v,w])
    
d = bellman_ford(graph, 0)
if d > 0:
    print(0)
else:
    print(-1*d)

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict

    n, m, p = map(int, readline().split())
    edge = defaultdict(list)

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

    dist = [INF] * n
    dist[0] = 0

    for _ in range(n - 1):
        for u in range(n):
            for v, w in edge[u]:
                dist[v] = min(dist[v], dist[u] + w)

    loop = [False] * n

    for _ in range(n):
        for u in range(n):
            for v, w in edge[u]:
                if dist[v] > dist[u] + w:
                    dist[v] = dist[u] + w
                    loop[v] = True

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

N, M, P = rl()
E = []
for i in range(M):
	a, b, c = rl()
	E.append((a-1, b-1, P-c))
V = list(range(N))

def belmanford(V, E, s=0):
	D = [float('inf')] * len(V)
	D[s] = 0
	P = [None] * len(V)

	for i in range(len(V)-1):
		m = i+1
		for u, v, c in E:
			if D[v] > D[u] + c:
				D[v] = D[u] + c
				P[v] = (u, c)

	n = N-1
	while n != 0:
		prev, c = P[n]
		if D[prev] + c < D[n]:
			return None, None
		n = prev
	return D, P

D, P = belmanford(V, E)
if D == None:
	print(-1)
else:
	print(max(-D[N-1], 0))

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys


class mEdge():

    def __init__(self, _from, _to, _cost):
        self.fro = _from
        self.to = _to
        self.cost = _cost


class bellman_ford():
    def __init__(self, V):
        self.G = []
        self._V = N
        self._E = 0

    def add(self, _from, _to, _cost):
        self.G.append(mEdge(_from, _to, _cost))
        self._E += 1

    def shortest_path(self, s):
        d = [10**20]*(self._V+1)
        d[s] = 0
        for _ in range(self._V):
            flag = False
            for edge in self.G:
                newlen = d[edge.fro]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
        return d

    def have_negative_circle(self):
        d = [10**20]*(self._V+1)
        d[1] = 0
        for _ in range(self._V):
            flag = False
            for edge in self.G:
                newlen = d[edge.fro]+edge.cost
                if newlen < d[edge.to]:
                    flag = True
                    d[edge.to] = newlen
            if not flag:
                break
        return _ == self._V - 1


# Coins Respawn
sys.setrecursionlimit(10**7)
N, M, P = map(int, input().split())
graph = []
d = deque()


from_1 = [[] for i in range(N+1)]
from_N = [[] for i in range(N+1)]

for _ in range(M):
    a, b, c = map(int, input().split())
    from_1[a].append(b)
    from_N[b].append(a)
    d.append((a, b, P-c))


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True
G = bellman_ford(N)

while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        G.add(p, q, weight)

if G.have_negative_circle():
    print(-1)
else:

    print(max(0, -G.shortest_path(1)[N]))

Submission status: Wrong Answer

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

N, M, P = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]

to = [[] for _ in range(N + 1)]
ot = [[] for _ in range(N + 1)]
edges = [[] for _ in range(N + 1)]

for a, b, c in X:
    edges[a].append((b, c - P))
    to[a].append(b)
    ot[b].append(a)

ok_1 = [False] * (N + 1)
ok_1[1] = True

q = deque()
q.append(1)
while q:
    u = q.popleft()
    for v in to[u]:
        if not ok_1[v]:
            ok_1[v] = True
            q.append(v)

ok_n = [False] * (N + 1)
ok_n[N] = True

q = deque()
q.append(N)
while q:
    u = q.popleft()
    for v in ot[u]:
        if not ok_n[v]:
            ok_n[v] = True
            q.append(v)

INF = 10 ** 9 + 7
d = [INF] * (N + 1)
d[1] = 0
updated = True
cnt = 0
while updated and cnt <= N:
    updated = False
    for u in range(N):
        if not ok_1[u] or not ok_n[u]:
            continue
            
        for v, c in edges[u]:
            if not ok_1[v] or not ok_n[v]:
                continue
                
            if d[v] > d[u] - c:
                d[v] = d[u] - c
                updated = True
                
if cnt > N:
    print(-1)
else:
    print(max(0, -d[-1]))

Submission status: Wrong Answer

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

N, M, P = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]

visited = [False] * (N + 1)
visited[1] = True

graph = [[] for _ in range(N + 1)]
for a, b, _ in X:
    graph[a].append(b)

q = deque()
q.append(1)
while q:
    u = q.popleft()
    for v in graph[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

graph_inv = [[] for _ in range(N + 1)]
for a, b, _ in X:
    graph_inv[b].append(a)

q = deque()
q.append(N)
while q:
    u = q.popleft()
    for v in graph_inv[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

graph = [[] for _ in range(N + 1)]
for a, b, c in X:
    graph[a].append((b, c - P))
            
d = [0] * (N + 1)
q = deque()
q.append(1)
tmp = 0
for i in range(2):
    for _ in range(M):
        if not q:
            break
        u = q.popleft()
        for v, x in graph[u]:
            if d[v] < d[u] + x:
                d[v] = d[u] + x
                q.append(v)

    if i == 0:
        tmp = d[-1]

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

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M, P = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]

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

visited = [False] * (N + 1)
visited[1] = True

q = deque()
q.append(1)
while q:
    u = q.popleft()
    for v, _ in graph[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

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

q = deque()
q.append(N)
while q:
    u = q.popleft()
    for v, _ in graph_inv[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

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

q = deque()
q.append(1)
cnt = [0] * (N + 1)
for i in range(2):
    for _ in range(M):
        if not q:
            break
        u = q.popleft()
        for v, y in graph[u]:
            if cnt[v] < cnt[u] + y:
                cnt[v] += cnt[u] + y
                q.append(v)
    
    if i == 0:
        tmp = cnt[:]

if cnt[-1] == tmp[-1]:
    print(max(0, cnt[-1]))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

N, M, P = map(int, input().split())
X = [list(map(int, input().split())) for _ in range(M)]

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

visited = [False] * (N + 1)
visited[1] = True

q = deque()
q.append(1)
while q:
    u = q.popleft()
    for v, _ in graph[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

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

q = deque()
q.append(N)
while q:
    u = q.popleft()
    for v, _ in graph_inv[u]:
        if not visited[v]:
            visited[v] = True
            q.append(v)

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

q = deque()
q.append(1)
cnt = [0] * (N + 1)
for i in range(2):
    for _ in range(N):
        if not q:
            break
        u = q.popleft()
        for v, y in graph[u]:
            if cnt[v] < cnt[u] + y:
                cnt[v] += cnt[u] + y
                q.append(v)
    
    if i == 0:
        tmp = cnt[:]

if cnt[-1] == tmp[-1]:
    print(max(0, cnt[-1]))
else:
    print(-1)

Submission status: Wrong Answer

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

n, m, p = map(int, input().split())
edge = []
for _ in range(m):
  a, b, c = map(int, input().split())
  edge.append((a, b, c-p))
dist = [-float("inf")]*(n+1)
dist[1] = 0
for i in range(2*n+1):
  for a, b, c in edge:
    if dist[b] < dist[a] + c:
      dist[b] = dist[a] + c
      if i == 2*n and b == n:
        print(-1)
        exit()
ans = max(dist[n], 0)
print(ans)

Submission status: Wrong Answer

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

n, m, p = map(int, input().split())
edge = []
for _ in range(m):
  a, b, c = map(int, input().split())
  edge.append((a, b, c-p))
dist = [-float("inf")]*(n+1)
dist[1] = 0
for i in range(n):
  for a, b, c in edge:
    if dist[b] < dist[a] + c:
      dist[b] = dist[a] + c
      if i == n-1 and b == n:
        print(-1)
        exit()
ans = max(dist[n], 0)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N, M, P = map(int, input().split())
edge = [list(map(int, input().split())) for _ in range(M)]

INF = 1 << 60
cost = [- INF] * (N + 1)
cost[1] = 0

for i in range(N):
    for n, nn, c in edge:
        if cost[nn] < cost[n] + c - P:
            # ベルマンフォード法の性質より、N回目に更新があるならinf
            if i == N - 1 and nn == N:
                print("-1")
                sys.exit()
            cost[nn] = cost[n] + c - P

print(max(cost[N], 0))

Submission status: Wrong Answer

Solution code:
INF = 10 ** 10


def bellman_ford(N, edges, weights):
    start_node = 0
    goal_node = N - 1
    dists = [INF for _ in range(N)]
    dists[start_node] = 0
    for _ in range(N - 1):
        for edge in edges:
            from_node, to_node = edge
            new_dist = weights[from_node][to_node] + dists[from_node]
            if dists[to_node] > new_dist:
                dists[to_node] = new_dist
    # check negative loops on s-t path
    for _ in range(N):
        from_node, to_node = edge
        new_dist = weights[from_node][to_node] + dists[from_node]
        if dists[to_node] > new_dist:
            dists[to_node] = - INF
    return dists[goal_node]


def main():
    N, M, P = list(map(int, input().split(' ')))
    edges = list()
    weights = [[0 for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        A, B, C = list(map(int, input().split(' ')))
        weights[A - 1][B - 1] = - C + P
        edges.append((A - 1, B - 1))
    d = bellman_ford(N, edges, weights)
    if d == - INF:
        print(-1)
    else:
        print(max(- d, 0))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline
epsilon = 2 ** -26 # > 10 ** -8, which is the smallest cost scipy's bellman_ford can deal with. 

N, M, P = map(int, input().split())
graph = np.zeros((N, N), np.float64)
for _ in range(M):
    a, b, c = map(int, input().split())
    if graph[a-1][b-1] == 0:
        if -c+P == 0:
            graph[a-1][b-1] = epsilon
        else:
            graph[a-1][b-1] = -c+P
    elif graph[a-1][b-1] > -c+P:
        if -c+P == 0:
            graph[a-1][b-1] = epsilon
        else:
            graph[a-1][b-1] = -c+P

print(graph)

tmp = graph[-1, 0]
#connect N to 1
graph[-1, 0] = epsilon
_, labels = connected_components(graph, connection = "strong")
mask = (labels == labels[0])

#recover original N to 1 path.
graph[-1, 0] = tmp
graph = graph[mask, :][:, mask]

try:
    ans = bellman_ford(graph, directed = True, indices = 0)[-1]
    ans = max(0, int(round(-ans)))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline
epsilon = 2 ** -26 # > 10 ** -8, which is the smallest cost scipy's bellman_ford can deal with. 

N, M, P = map(int, input().split())
graph = np.zeros((N, N))
for _ in range(M):
    a, b, c = map(int, input().split())
    if graph[a-1][b-1] > -c+P:
        if -c+P == 0:
            graph[a-1][b-1] = epsilon
        else:
            graph[a-1][b-1] = -c+P

tmp = graph[-1, 0]
#connect N to 1
graph[-1, 0] = epsilon
_, labels = connected_components(graph, connection = "strong")
mask = (labels == labels[0])

#recover original N to 1 path.
graph[-1, 0] = tmp
graph = graph[mask, :][:, mask]

try:
    ans = bellman_ford(graph, directed = True, indices = 0)[-1]
    ans = max(0, int(round(-ans)))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline
epsilon = 2 ** -26 # > 10 ** -8, which is the smallest cost scipy's bellman_ford can deal with. 

N, M, P = map(int, input().split())
starts = []
ends = []
costs = []
# I hope there's no pair that satisfies (ai, bi) == (aj, bj)
for _ in range(M):
    a, b, c = map(int, input().split())
    starts.append(a-1)
    ends.append(b-1)
    costs.append(-c+P if -c+P else epsilon)

look_for_loop = csr_matrix((costs + [epsilon], (starts + [N-1], ends + [0])), shape = (N, N))
_, labels = connected_components(look_for_loop, connection = "strong")
mask = (labels == labels[0])

graph = csr_matrix((costs, (starts, ends)), shape = (N, N)).toarray()
graph = graph[mask, :][:, mask]

try:
    ans = bellman_ford(graph, directed = True, indices = 0)[-1]
    ans = max(0, int(round(-ans)))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque #,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,m,p = inm()
dst = [{} for i in range(n+1)]
src = [{} for i in range(n+1)]
for i in range(m):
    a,b,c = inm()
    dst[a][b] = src[b][a] = c

rf1 = [False]*(n+1)
rf1[1] = True
q = deque([1])
while len(q)>0:
    x = q.popleft()
    for y in dst[x]:
        if not rf1[y]:
            rf1[y] = True
            q.append(y)

rtn = [False]*(n+1)
rtn[n] = True
q = deque([n])
while len(q)>0:
    x = q.popleft()
    for y in src[x]:
        if not rtn[y]:
            rtn[y] = True
            q.append(y)

ddprint(rf1)
ddprint(rtn)

use = [rf1[i] and rtn[i] for i in range(n+1)]

dp = [[-1]*(n+1) for i in range(2*m+1)]
dp[0][1] = 0
for i in range(2*m):
    for j in range(1,n+1):
        if not use[j] or dp[i][j]<0:
            continue
        for x in dst[j]:
            if use[x] and dp[i+1][x]<dp[i][j]+dst[j][x]:
                dp[i+1][x] = dp[i][j]+dst[j][x]

for i in range(2*m+1):
    ddprint(dp[i])

for i in range(2*m-1):
    for j in range(i+1,2*m):
        if dp[j][n]>=0 and dp[i][n]>=0 and \
           (j-i)*p < dp[j][n]-dp[i][n]:
            print(-1)
            exit()
mx = 0
for i in range(2*m):
    mx = max(mx, dp[i][n]-i*p)
print(mx)

Submission status: Wrong Answer

Solution code:
from collections import deque #,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True  and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n,m,p = inm()
dst = [{} for i in range(n+1)]
src = [{} for i in range(n+1)]
for i in range(m):
    a,b,c = inm()
    dst[a][b] = src[b][a] = c

rf1 = [False]*(n+1)
rf1[1] = True
q = deque([1])
while len(q)>0:
    x = q.popleft()
    for y in dst[x]:
        if not rf1[y]:
            rf1[y] = True
            q.append(y)

rtn = [False]*(n+1)
rtn[n] = True
q = deque([n])
while len(q)>0:
    x = q.popleft()
    for y in src[x]:
        if not rtn[y]:
            rtn[y] = True
            q.append(y)

ddprint(rf1)
ddprint(rtn)

use = [rf1[i] and rtn[i] for i in range(n+1)]
for i in range(n+1):
    if not use[i]:
        dst[i] = {}
        src[i] = {}
    else:
        ky = list(dst[i].keys())
        for j in ky:
            if not use[j]:
                del dst[i][j]
        ky = list(src[i].keys())
        for j in ky:
            if not use[j]:
                del src[i][j]

dp = [[-1]*(n+1) for i in range(2*m+1)]
dp[0][1] = 0
for i in range(2*m):
    for j in range(1,n+1):
        if dp[i][j]<0:
            continue
        for x in dst[j]:
            if dp[i+1][x]<dp[i][j]+dst[j][x]:
                dp[i+1][x] = dp[i][j]+dst[j][x]

for i in range(2*m+1):
    ddprint(dp[i])

for i in range(2*m-1):
    for j in range(i+1,2*m):
        if dp[j][n]>=0 and dp[i][n]>=0 and \
           (j-i)*p < dp[j][n]-dp[i][n]:
            print(-1)
            exit()
mx = 0
for i in range(2*m):
    mx = max(mx, dp[i][n]-i*p)
print(mx)

Submission status: Wrong Answer

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, m, p = LI()
abc = [LI() for _ in range(m)]
edges = [[] for _ in range(n)]
for a, b, c in abc:
    edges[a-1].append((b-1, c))

dp = [-float('inf')] * n
dp[0] = 0
tmp = -1
for _ in range(n):
    flag = False
    for v in range(n):
        score = dp[v]
        for u, c in edges[v]:
            if dp[u] < score + c - p:
                dp[u] = score + c - p
                flag = True
for _ in range(1):
    flag = False
    for v in range(n):
        score = dp[v]
        for u, c in edges[v]:
            if dp[u] < score + c - p:
                dp[u] = score + c - p
                if u == n - 1:
                    flag = True
if flag:
    print(-1)
else:
    print(max(0, dp[n-1]))

Submission status: Wrong Answer

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, m, p = LI()
abc = [LI() for _ in range(m)]
edges = [[] for _ in range(n)]
for a, b, c in abc:
    edges[a-1].append((b-1, c))

dp = [-float('inf')] * n
dp[0] = 0
tmp = -1
for _ in range(n+1):
    flag = False
    for v in range(n):
        score = dp[v]
        for u, c in edges[v]:
            if dp[u] < score + c - p:
                dp[u] = score + c - p
                if u == n-1:
                    flag = True
if flag:
    print(-1)
else:
    print(max(0, dp[n-1]))