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:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


from collections import defaultdict

def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+1):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        dist[v] = -INF
                    else:
                        dist[v] = dist[u] + g[u][v]
                        pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)
    d = BellmanFord(g, 1)
    print(d)
    if -d[N] == INF:
        return -1
    return max(0, -d[N])





def main():
    N, M, P = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    print(slv(N, M, P, ABC))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
from collections import defaultdict, deque

if __name__ == '__main__':
    n, m, p = map(int, stdin.readline().rstrip().split())
    abc = [list(map(int, stdin.readline().rstrip().split())) for _ in range(m)]

    g = defaultdict(list)
    g2 = defaultdict(list)
    for a, b, c in abc:
        g[a - 1].append((b - 1, c))
        g2[b - 1].append((a - 1, c))

    # checck cycles
    def check():
        ret = set([])
        for start in range(n):
            b = False
            q = deque([(start, 0)])
            visited = set([start])
            while q:
                cur, d = q.popleft()
                for target, c in g[cur]:
                    if target not in visited:
                        visited.add(target)
                        q.append((target, d - c + p))
                    if target == start and d - c + p < 0:
                        ret.add(start)
                        b = True
                        break
                if b:
                    break
        return ret

    # reacheble from the start
    q = deque([0])
    visited1 = set([0])
    while q:
        cur = q.popleft()
        for target, _ in g[cur]:
            if target not in visited1:
                visited1.add(target)
                q.append(target)

    # reacheble from the end
    q = deque([n - 1])
    visited2 = set([n - 1])
    while q:
        cur = q.popleft()
        for target, _ in g2[cur]:
            if target not in visited2:
                visited2.add(target)
                q.append(target)

    f = False
    cycle = check()
    for cand in cycle:
        if cand in visited1 and cand in visited2:
            f = True

    if f:
        print(-1)
    else:
        d = [float("inf")] * n
        d[0] = 0

        for i in range(n):
            update = False
            for a, b, c in abc:
                u, v, w = a - 1, b - 1, -c + p
                if u not in cycle and v not in cycle and d[u] != float('inf') and d[v] > d[u] + w:
                    d[v] = d[u] + w
                    update = True

            if not update:
                break
        tmp = -1 * d[-1]
        print(max(0, tmp))

Submission status: Wrong Answer

Solution code:
n, m, p = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]

from collections import defaultdict, deque
g = defaultdict(list)
g2 = defaultdict(list)
for a, b, c in abc:
    g[a - 1].append((b - 1, c))
    g2[b - 1].append((a - 1, c))

# checck cycles
def check():
    ret1, ret2 = set([]), set([])
    for start in range(n):
        b = False
        q = deque([(start, 0)])
        visited = set([start])
        while q:
            cur, d = q.popleft()
            for target, c in g[cur]:
                if target not in visited:
                    visited.add(target)
                    q.append((target, d - c + p))
                if target == start:
                    ret2.add(start)
                    if d - c + p < 0:
                        ret1.add(start)
                        b = True
                        break
            if b:
                break
    return ret1, ret2

# reacheble from the start
q = deque([0])
visited1 = set([0])
while q:
    cur = q.popleft()
    for target, _ in g[cur]:
        if target not in visited1:
            visited1.add(target)
            q.append(target)

# reacheble from the end
q = deque([n - 1])
visited2 = set([n - 1])
while q:
    cur = q.popleft()
    for target, _ in g2[cur]:
        if target not in visited2:
            visited2.add(target)
            q.append(target)

f = False
cycle, cycle2 = check()
for cand in cycle:
    if cand in visited1 and cand in visited2:
        f = True

if f:
    print(-1)
else:
    d = [float("inf")] * n
    d[0] = 0

    while True:
        update = False
        for a, b, c in abc:
            u, v, w = a - 1, b - 1, -c + p
            if u not in cycle2 and v not in cycle2 and d[u] != float('inf') and d[v] > d[u] + w:
                d[v] = d[u] + w
                update = True

        if not update:
            break
    tmp = -1 * d[-1]
    print(max(0, tmp))

Submission status: Wrong Answer

Solution code:
n, m, p = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]

from collections import defaultdict, deque
g = defaultdict(list)
g2 = defaultdict(list)
for a, b, c in abc:
    g[a - 1].append((b - 1, c))
    g2[b - 1].append((a - 1, c))

# checck cycles
def check():
    ret = set([])
    for start in range(n):
        b = False
        q = deque([start])
        visited = set([start])
        while q:
            cur = q.popleft()
            for target, _ in g[cur]:
                if target not in visited:
                    visited.add(target)
                    q.append(target)
                if target == start:
                    ret.add(start)
                    b = True
                    break
            if b:
                break
    return ret

# reacheble from the start
q = deque([0])
visited1 = set([0])
while q:
    cur = q.popleft()
    for target, _ in g[cur]:
        if target not in visited1:
            visited1.add(target)
            q.append(target)

# reacheble from the end
q = deque([n - 1])
visited2 = set([n - 1])
while q:
    cur = q.popleft()
    for target, _ in g2[cur]:
        if target not in visited2:
            visited2.add(target)
            q.append(target)

f = False
cycle = check()
for cand in cycle:
    if cand in visited1 and cand in visited2:
        f = True

if f:
    print(-1)
else:
    d = [float("inf")] * n
    d[0] = 0


    while True:
        update = False
        for a, b, c in abc:
            u, v, w = a - 1, b - 1, -c + p
            if u not in cycle and v not in cycle and d[u] != float('inf') and d[v] > d[u] + w:
                d[v] = d[u] + w
                update = True

        if not update:
            break
    tmp = -1 * d[-1]
    print(max(0, tmp))

Submission status: Wrong Answer

Solution code:
n, m, p = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]

from collections import defaultdict, deque
g = defaultdict(list)
g2 = defaultdict(list)
for a, b, c in abc:
    g[a - 1].append((b - 1, c))
    g2[b - 1].append((a - 1, c))

# checck cycles
def check():
    ret = set([])
    for start in range(n):
        b = False
        q = deque([start])
        visited = set([start])
        while q:
            cur = q.popleft()
            for target, _ in g[cur]:
                if target not in visited:
                    visited.add(target)
                    q.append(target)
                if target == start:
                    ret.add(start)
                    b = True
                    break
            if b:
                break
    return ret

# reacheble from the start
q = deque([0])
visited1 = set([0])
while q:
    cur = q.popleft()
    for target, _ in g[cur]:
        if target not in visited1:
            visited1.add(target)
            q.append(target)

# reacheble from the end
q = deque([n - 1])
visited2 = set([n - 1])
while q:
    cur = q.popleft()
    for target, _ in g2[cur]:
        if target not in visited2:
            visited2.add(target)
            q.append(target)

f = False
cycle = check()
for cand in cycle:
    if cand in visited1 and cand in visited2:
        f = True

if f:
    print(-1)
else:
    d = [float("inf")] * n
    d[0] = 0

    for i in range(n):
        for a, b, c in abc:
            u, v, w = a - 1, b - 1, -c + p
            if d[v] > d[u] + w:
                d[v] = d[u] + w
    tmp = -1 * d[-1]
    print(max(0, tmp))

Submission status: Wrong Answer

Solution code:
n, m, p = map(int, input().split())
abc = [list(map(int, input().split())) for _ in range(m)]

from collections import defaultdict, deque
g = defaultdict(list)
for a, b, c in abc:
    g[a - 1].append((b - 1, c))

# checck cycles
def check():
    ret = set([])
    for start in range(n):
        b = False
        q = deque([start])
        visited = set([start])
        while q:
            cur = q.popleft()
            for target, _ in g[cur]:
                if target not in visited:
                    visited.add(target)
                    q.append(target)
                if target == start:
                    ret.add(start)
                    b = True
                    break
            if b:
                break
    return ret

# distance from the start
d1 = [float('inf')] * n
d1[0] = 0
for i in range(n):
    for a, b, c in abc:
        u, v, w = a - 1, b - 1, 1
        if d1[v] > d1[u] + w:
            d1[v] = d1[u] + w

# distance from the end
d2 = [float('inf')] * n
d2[n - 1] = 0
for i in range(n):
    for a, b, c in abc:
        u, v, w = b - 1, a - 1, 1
        if d2[v] > d2[u] + w:
            d2[v] = d2[u] + w

f = False
cycle = check()
for cand in cycle:
    if d1[cand] != float('inf') and d2[cand] != float('inf'):
        f = True

if f:
    print(-1)
else:
    d = [float("inf")] * n
    d[0] = 0

    for i in range(n):
        for a, b, c in abc:
            u, v, w = a - 1, b - 1, -c + p
            if d[v] > d[u] + w:
                d[v] = d[u] + w
    tmp = -1 * d[-1]
    print(max(0, tmp))

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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

min_distance = [float("inf")]*N # min_distance[i] は始点から街iまでの最短距離
min_distance[0] = 0 # 始点から始点への最短距離は0とする
negative = [False]*N

def Bellman_Ford(S,V,E,distance,negative):
    negative = [False]*N
    count = 1
    while count < V:
        count += 1
        for s,g,d in distance: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = min_distance[s] + d # 最短距離を上書きする
                negative[s],negative[g] = True,True
    return min_distance,negative

min_distance,negative = Bellman_Ford(1,N,M,line,negative)
ans = min_distance[N-1]

negative = [False]*N
min_distance,negative = Bellman_Ford(1,N,M,line,negative)

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

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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

def Bellman_Ford(S,V,E,distance):
    min_distance = [float("inf")]*V # min_distance[i] は始点から街iまでの最短距離
    min_distance[S-1] = 0 # 始点から始点への最短距離は0とする
    count = 1
    while count < 2*V:
        if count == V:
            tmp = min_distance[N-1]
        count += 1
        for s,g,d in distance: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = min_distance[s] + d # 最短距離を上書きする
    return min_distance,tmp

min_distance,tmp = Bellman_Ford(1,N,M,line)
ans = min_distance[N-1]

if ans == tmp:
    print(max(-tmp,0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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

def Bellman_Ford(S,V,E,distance):
    min_distance = [float("inf")]*V # min_distance[i] は始点から街iまでの最短距離
    min_distance[S-1] = 0 # 始点から始点への最短距離は0とする
    count = 1
    while count < 2*V:
        if count == V:
            tmp = min_distance[N-1]
        count += 1
        for s,g,d in distance: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = min_distance[s] + d # 最短距離を上書きする
                update = True # 最短距離情報が更新されたとする
    return min_distance,tmp

#True : 負の経路が存在する
def find_negative_loop(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0 
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    return True
    return False

min_distance,tmp = Bellman_Ford(1,N,M,line)
ans = min_distance[N-1]

if not find_negative_loop(N,M,line): # 負の閉路が存在しない
    print(max(-tmp,0))
else:
    if ans == tmp:
        print(max(-tmp,0))
    else:
        print(-1)

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
MOD = 10**9+7

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

def Bellman_Ford(S,V,E,distance):
    min_distance = [float("inf")]*V # min_distance[i] は始点から街iまでの最短距離
    min_distance[S-1] = 0 # 始点から始点への最短距離は0とする
    count = 1
    while count <= V:
        count += 1
        update = False
        for s,g,d in distance: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = min_distance[s] + d # 最短距離を上書きする
                update = True # 最短距離情報が更新されたとする
        if not update: # 最短距離情報が更新されていないのならば、
            break # While文を終える
    return min_distance

#True : 負の経路が存在する
def find_negative_loop(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0 
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    return True
    return False

min_distance = Bellman_Ford(1,N,M,line)
ans = min_distance[N-1]
if ans >= 0:
    print(0)
else:
    if find_negative_loop(N,M,line):
        print(-1)
    else:
        print(-ans)

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,(input().split()))
line = []
for i in range(M):
    a,b,c = map(int,(input().split()))
    line.append([a-1,b-1,-c+P])

def Bellman_Ford(S,V,E,distance):
    min_distance = [float("inf")]*V # min_distance[i] は始点から街iまでの最短距離
    min_distance[S-1] = 0 # 始点から始点への最短距離は0とする
    count = 1
    while count < V:
        count += 1
        update = False
        for s,g,d in distance: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = min_distance[s] + d # 最短距離を上書きする
                update = True # 最短距離情報が更新されたとする
        if not update: # 最短距離情報が更新されていないのならば、
            break # While文を終える
    return min_distance

#True : 負の経路が存在する
def find_negative_loop(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0 
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    return True
    return False

min_distance = Bellman_Ford(1,N,M,line)
ans = min_distance[N-1]
if ans >= 0:
    print(0)
else:
    if find_negative_loop(N,M,line):
        print(-1)
    else:
        print(-ans)

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,m,p = LI()
    abc = [LI() for _ in range(m)]
    return -1
    er = collections.defaultdict(set)
    err = collections.defaultdict(set)
    for a,b,c in abc:
        er[b].add(a)
        err[a].add(b)

    v = set([n])
    q = [n]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in er[t]:
            if b not in v:
                v.add(b)
                q.append(b)

    u = set([1])
    q = [1]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in err[t]:
            if b not in u:
                u.add(b)
                q.append(b)

    v &= u

    e = collections.defaultdict(list)
    for a,b,c in abc:
        if a not in v or b not in v:
            continue
        e[a].append((b,c-p))

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        q = []
        d[s] = 0
        heapq.heappush(q, (0, s))
        while len(q):
            mk, u = heapq.heappop(q)
            k = -mk
            if d[u] > k:
                continue

            for uv, ud in e[u]:
                vd = k + ud
                if d[uv] < vd:
                    d[uv] = vd
                    heapq.heappush(q, (-vd, uv))

        return d

    for k in list(e.keys()):
        t = [0] * (n+1)
        def f(i, c):
            for ni,nc in e[i]:
                if ni < i:
                    continue
                nd = c + nc
                if ni == k:
                    if nd > 0:
                        return True
                    continue
                if t[ni] == 1:
                    continue
                t[ni] = 1
                r = f(ni, nd)
                if r:
                    return True
                t[ni] = 0
            return False

        if f(k, 0):
            return -1

    d = search(1)
    return max(0, d[n])

print(main())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,m,p = LI()
    abc = [LI() for _ in range(m)]
    er = collections.defaultdict(set)
    err = collections.defaultdict(set)
    for a,b,c in abc:
        er[b].add(a)
        err[a].add(b)

    v = set([n])
    q = [n]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in er[t]:
            if b not in v:
                v.add(b)
                q.append(b)

    u = set([1])
    q = [1]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in err[t]:
            if b not in u:
                u.add(b)
                q.append(b)

    v &= u

    e = collections.defaultdict(list)
    for a,b,c in abc:
        if a not in v or b not in v:
            continue
        e[a].append((b,c-p))

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        q = []
        d[s] = 0
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            mk, u = heapq.heappop(q)
            k = -mk
            if v[u]:
                continue
            v[u] = True

            for uv, ud in e[u]:
                vd = k + ud
                if d[uv] < vd:
                    d[uv] = vd
                    heapq.heappush(q, (-vd, uv))

        return d

    for k in list(e.keys()):
        t = [0] * (n+1)
        def f(i, c):
            for ni,nc in e[i]:
                if ni < i:
                    continue
                nd = c + nc
                if ni == k:
                    if nd > 0:
                        return True
                    continue
                if t[ni] == 1:
                    continue
                t[ni] = 1
                r = f(ni, nd)
                if r:
                    return True
                t[ni] = 0
            return False

        if f(k, 0):
            return -1

    d = search(1)
    return max(0, d[n])

print(main())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,m,p = LI()
    abc = [LI() for _ in range(m)]
    er = collections.defaultdict(set)
    err = collections.defaultdict(set)
    for a,b,c in abc:
        er[b].add(a)
        err[a].add(b)

    v = set([n])
    q = [n]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in er[t]:
            if b not in v:
                v.add(b)
                q.append(b)

    u = set([1])
    q = [1]
    qi = 0
    while len(q) > qi:
        t = q[qi]
        qi += 1
        for b in err[t]:
            if b not in u:
                u.add(b)
                q.append(b)

    v &= u

    e = collections.defaultdict(list)
    for a,b,c in abc:
        if a not in v or b not in v:
            continue
        e[a].append((b,c-p))

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        q = []
        d[s] = 0
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            mk, u = heapq.heappop(q)
            k = -mk
            if v[u]:
                continue
            v[u] = True

            for uv, ud in e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] < vd:
                    d[uv] = vd
                    heapq.heappush(q, (-vd, uv))

        return d

    for k in list(e.keys()):
        t = [0] * (n+1)
        def f(i, c):
            for ni,nc in e[i]:
                nd = c + nc
                if ni == k:
                    if nd > 0:
                        return True
                    continue
                if t[ni] == 1:
                    continue
                t[ni] = 1
                r = f(ni, nd)
                if r:
                    return True
                t[ni] = 0
            return False

        if f(k, 0):
            return -1

    d = search(1)
    return max(0, d[n])

print(main())