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:
import math, heapq
from operator import itemgetter as ig
from collections import defaultdict as dd
# 定数
INF = float("inf")
MOD = int(1e9 + 7)
# データ構造：ヒープ
class heapque:
    def __init__(self, *args):
        self.que = []
        for arg in args:
            self.push(arg)
    def push(self, v):
        heapq.heappush(self.que, v)
    def pop(self):
        return heapq.heappop(self.que)
# 最大公約数 / 最小公倍数
def gcd(v1, v2):
    if v2 == 0:
        return v1
    return gcd(v2, v1 % v2)
def lcm(v1, v2):
    return (v1 // gcd(v1, v2)) * v2
# 二分探索
def bsr(a, v, lo=0, hi=None):
    if hi == None:
        hi = len(a) - 1
    if hi < lo:
        return lo
    mi = (lo + hi) // 2
    if v < a[mi]:
        return bsr(a, v, lo, mi - 1)
    else:
        return bsr(a, v, mi + 1, hi)
# Union-Find木
class uft:
    def __init__(self, n):
        self.height = [1] * n
        self.group = [-1] * n
    def root(self, v):
        if self.group[v] < 0:
            return v
        self.group[v] = self.root(self.group[v])
        return self.group[v]
    def size(self, v):
        return - self.group[self.root(v)]
    def merge(self, v1, v2):
        v1, v2 = self.root(v1), self.root(v2)
        if v1 == v2:
            return
        if self.height[v1] < self.height[v2]:
            self.group[v2] += self.group[v1]
            self.group[v1] = v2
            self.height[v2] = max(self.height[v1] + 1, self.height[v2])
        else:
            self.group[v1] += self.group[v2]
            self.group[v2] = v1
            self.height[v1] = max(self.height[v1] , self.height[v2] + 1)
# グラフ
class graph:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
    def append(self, v1, v2, cost=1):
        self.graph[v1].append((v2, cost))
    # ダイクストラ法(Dijkstra's Algorithm)
    def dks(self, v):
        costs = [INF] * self.n
        costs[v] = 0
        done = [False] * self.n
        heap = heapque((0, v))
        while heap.que:
            c_cost, c_index = heap.pop()
            if done[c_index]:
                continue
            done[c_index] = True
            for n_index, n_cost in self.graph[c_index]:
                if c_cost + n_cost < costs[n_index]:
                    costs[n_index] = c_cost + n_cost
                    heap.push((costs[n_index], n_index))
        return costs
    # ベルマン－フォード法(Bellman-Ford Algorithm)
    def bf(self, v, edges):
        costs = [INF] * self.n
        costs[v] = 0
        for _ in range(self.n):
            flag = False
            for a, b, c in edges:
                if costs[a] == INF: continue
                cost = costs[a] + c
                if cost < costs[b]:
                    costs[b] = cost
                    flag = True
            if not flag:
                break
        else:
            return None
        return costs

def main():
    N, M, P = map(int, input().split())
    ABC = [list(map(int, input().split())) for _ in range(M)]

    def dfs(g, v):
        act = {v}
        que = [v]
        for n in g[v]:
            if n[0] in act: continue
            act |= {n[0]}
            que.append(n[0])
        return act
    g = graph(N)
    for a, b, c in ABC:
        a, b, c = a - 1, b - 1, c - P
        g.append(b, a, c)
    act = dfs(g.graph, N - 1)
    abc = [(a - 1, b - 1, -(c - P)) for a, b, c in ABC if (a - 1 in act) and (b - 1 in act)]
    bf = g.bf(0, abc)
    if bf:
        print(max(0, -bf[-1]))
    else:
        print(-1)

main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
E = [list(map(int, input().split())) for _ in range(M)]
A = [-float("inf")] * (N + 1)
A[1] = 0

def run():
	for v in range(N):
		for a, b, c in E:
			A[b] = max(A[b], A[a] + c - P)

run()
res = A[N]
run()
res = -1 if res != A[N] else max(0, res)
print(res)

Submission status: Wrong Answer

Solution code:
from scipy.sparse import*
m=csr_matrix
n,_,p,*t=map(int,open(0).read().split())
s=[n+1]*2
r,c,d=t[::3],t[1::3],[p-c for c in t[2::3]]
u=set(csgraph.depth_first_order(m((d,(c,r)),s),n,1,0))
r,c,d=zip(*[(r,c,d)for r,c,d in zip(r,c,d)if r in u and c in u])
try:print(max(0,-int(csgraph.bellman_ford(m((d,(r,c)),s),1,[1])[0,n])))
except:print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse import*
m=csr_matrix
n,_,p,*t=map(int,open(0).read().split())
s=[n+1]*2
r,c,d=t[::3],t[1::3],[p-c for c in t[2::3]]
u=set(csgraph.depth_first_order(m((d,(c,r)),s),n,1,0))
r,c,d=zip(*[(r,c,d)for r,c,d in zip(r,c,d)if r in u and c in u])
try:print(max(0,-int(csgraph.bellman_ford(m((d,(r,c)),s),1,[1])[0,n])))
except:print('inf')

Submission status: Wrong Answer

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

routes = dict()
coins = dict()

for i in range(M):
    a, b, c = map(int, input().split())
    if not a in routes.keys():
        routes[a] = [b]
    else:
        routes[a].append(b)

    if not a in coins.keys():
        coins[a] = [[b,c]]
    else:
        coins[a].append([b,c])

# search loop way
ways = [[1]]
loop_points = []
goal_ways = []
while ways:
    for way in ways:
        current_point = way[-1]
        ways.remove(way)
        if current_point in routes.keys():
            for next_point in routes[current_point]:
                pre_way = way.copy()
                if next_point in loop_points:
                    pass
                elif not next_point in pre_way:
                    pre_way.extend([next_point])
                    ways.append(pre_way)
                else:
                    loop_points.append(next_point)
                    continue
                if next_point == N:
                    goal_ways.append(pre_way)

max_score = -1
for way in goal_ways:
    pre_point = -1
    score = 0
    for point in way:
        if pre_point == -1:
            pre_point = point
            continue
        add_score = [x[1] for x in coins[pre_point] if x[0] == point][0] - P
        if point in loop_points and add_score > 0:
            score = float('inf')
            break
        score += add_score
        pre_point = point
    if score == float('inf'):
        score = -1
    elif score < 0:
        score = 0
    if score > max_score:
        max_score = score

print(max_score)

Submission status: Wrong Answer

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

routes = dict()
coins = dict()

for i in range(M):
    a, b, c = map(int, input().split())
    if not a in routes.keys():
        routes[a] = [b]
    else:
        routes[a].append(b)

    if not a in coins.keys():
        coins[a] = [[b,c]]
    else:
        coins[a].append([b,c])

# search loop way
ways = [[1]]
loop_points = []
goal_ways = []
while ways:
    for way in ways:
        current_point = way[-1]
        ways.remove(way)
        if current_point in routes.keys():
            for next_point in routes[current_point]:
                pre_way = way.copy()
                if next_point in loop_points:
                    pass
                elif not next_point in pre_way:
                    pre_way.extend([next_point])
                    ways.append(pre_way)
                else:
                    loop_points.append(next_point)
                    continue
                if next_point == N:
                    goal_ways.append(pre_way)

max_score = -1
for way in goal_ways:
    pre_point = -1
    score = 0
    for point in way:
        if pre_point == -1:
            pre_point = point
            continue
        add_score = [x[1] for x in coins[pre_point] if x[0] == point][0] - P
        if point in loop_points and add_score > 0:
            score = -1
            break
        score += add_score
        if score < 0:
            score = 0
        pre_point = point
    if score > max_score:
        max_score = score

print(max_score)

Submission status: Wrong Answer

Solution code:
import sys
def main():
    N, M, P = map( int, input().split())
    INF = 1e18
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c
    V = [INF]*N
    V[0] = 0
    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != INF:
                V[t] = min(V[t], V[s] + cost)

    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != INF:
                if V[t] > V[s] + cost:
                    V[t]=-INF

    if V[-1] == -INF:
        print(-1)
    else:
        print( max(-V[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
def main():
    N, M, P = map( int, input().split())
    INF = 1e18
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c
    V = [INF]*N
    V[0] = 0
    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != INF:
                V[t] = min(V[t], V[s] + cost)

    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != INF:
                if V[t] > V[s] + cost:
                    V[t]=-INF

    if V[-1] == -INF:
        print(-1)
    else:
        print( max(-V[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
def main():
    N, M, P = map( int, input().split())
    INF = 1e9
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c
    V = [INF]*N
    V[0] = 0
    for _ in range(N-1):
        for (s,t), cost in d.items():
            if V[s] != INF:
                V[t] = min(V[t], V[s] + cost)

    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != INF:
                if V[t] > V[s] + cost:
                    V[t]=-INF

    if V[-1] == -INF:
        print(-1)
    else:
        print( max(-V[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
    V = [-1e9]*N
    V[0] = 0
    for _ in range(N-1):
        for (s,t), cost in d.items():
            if V[s] != -1e9:
                V[t] = max(V[t], V[s] + cost)

    for _ in range(N):
        for (s,t), cost in d.items():
            if V[s] != -1e9:
                if V[t] < V[s] + cost:
                    V[t]=1e9

    if V[-1] == 1e9:
        print(-1)
    else:
        print( max(V[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = N
    for _ in range(I-1):
        for (s,t), cost in d.items():
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for (s,t), cost in d.items(): #d.keys()
        if V[s] == None or G[t] == False:
            continue
        if V[t] == None:
            V[t] = V[s] + cost
            continue
        if V[s] + cost > V[t]:
            V[t] = V[s] + cost

    for i in range(N):
        if W[i] == None or G[i] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for (s,t), cost in d.items():
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for (s,t), cost in d.items(): #d.keys()
        if V[s] == None or G[t] == False:
            continue
        if V[t] == None:
            V[t] = V[s] + cost
            continue
        if V[s] + cost > V[t]:
            V[t] = V[s] + cost

    for i in range(N):
        if W[i] == None or G[i] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def e():
    n, m, p = map(int, input().split())

    edges = []
    for i in range(m):
        edges.append(tuple(map(int, input().split())))

    edges.sort(key=lambda x: x[1])
    dist = [float('inf') for i in range(n)]
    dist[0] = 0

    for i in range(n):
        for e in edges:
            if dist[e[1]-1] > dist[e[0]-1] - (e[2] - p):
                dist[e[1]-1] = dist[e[0]-1] - (e[2] - p)
                if i == n - 1 and e[1] == n:
                    print(-1)
                    return

    print(-dist[n-1] if -dist[n-1] >= 0 else 0)


if __name__ == '__main__':
    e()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    # 頂点Nに到達する頂点
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    # Bellman-Ford
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for (s,t), cost in d.items():
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for _ in range(I-1):
        for (s,t), cost in d.items(): #d.keys()
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    for i in range(N):
        if W[i] == None or G[i] == False:
            continue
        if V[i] > W[i]: # 頂点iは、頂点Nに到達するので、負（正？）閉路は伝播する
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for (s,t), cost in d.items():
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for _ in range(I-1):
        for (s,t), cost in d.items(): #d.keys()
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + cost
                continue
            if V[s] + cost > V[t]:
                V[t] = V[s] + cost
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for e in d:
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

routes = dict()
coins = dict()

for i in range(M):
    a, b, c = map(int, input().split())
    if not a in routes.keys():
        routes[a] = [b]
    else:
        routes[a].append(b)

    if not a in coins.keys():
        coins[a] = [[b,c]]
    else:
        coins[a].append([b,c])

# search loop way
ways = [[1]]
loop_points = []
goal_ways = []
while ways:
    for way in ways:
        current_point = way[-1]
        ways.remove(way)
        if current_point in routes.keys():
            for next_point in routes[current_point]:
                pre_way = way.copy()
                if next_point in loop_points:
                    pass
                elif not next_point in pre_way:
                    pre_way.extend([next_point])
                    ways.append(pre_way)
                else:
                    loop_points.append(next_point)
                    continue
                if next_point == N:
                    goal_ways.append(pre_way)

max_score = -1
for way in goal_ways:
    pre_point = -1
    score = 0
    for point in way:
        if point in loop_points:
            score = -1
            break
        if pre_point == -1:
            pre_point = point
            continue
        score += [x[1] for x in coins[pre_point] if x[0] == point][0]
        score -= P
        if score < 0:
            score = 0
        pre_point = point
    if score > max_score:
        max_score = score

print(max_score)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = deepcopy(V) #[ V[i] for i in range(N)]
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]


cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[pos - 1] == np.inf: continue
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = np.inf
                solve(B, already)
        else:
            if cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = cost[pos - 1] + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, already2)


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(I*2):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
# ABC = [list(map(int, input().split())) for _ in range(M)]
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

# print (ABC_d)

cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0
already2 = np.empty(N, dtype = bool)

def solve(pos, already):
    global cost
    global already2

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = np.inf
                solve(B, already)
        else:
            if cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = cost[pos - 1] + C
                already2[:] = already[:]
                already2[B - 1] = True
                solve(B, already2)


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
def main():
    N, M, P = map( int, input().split())
    d = dict()
    E = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = c-P
        E[b].append(a)
    G = [False]*N
    G[N-1] = True
    q = deque([N-1])
    while q:
        v = q.popleft()
        for w in E[v]:
            if G[w] == False:
                G[w] = True
                q.append(w)
    V = [None]*N
    V[0] = 0
    I = sum([1 for i in range(N) if G[i] == True])
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    W = [ V[i] for i in range(N)]
    for _ in range(I-1):
        for e in d.keys():
            s, t = e
            if V[s] == None or G[t] == False:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] > V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if W[i] == None or G[t] == False:
            continue
        if V[i] > W[i]:
            print(-1)
            return

    print( max(W[-1], 0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
# ABC = [list(map(int, input().split())) for _ in range(M)]
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

# print (ABC_d)

cost = np.empty(N, dtype = int) - np.inf

def solve(pos, c_cost, already):
    global cost

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < c_cost + C:
                # looped = True
                cost[B - 1] = np.inf
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, c_cost + C, already2)
            # else:
            #     pass
        else:
            if cost[B - 1] < c_cost + C:
                cost[B - 1] = c_cost + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, c_cost + C, already2)
            # else:
            #     pass


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, 0, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))