Buggy python submission (verdict: Time Limit Exceeded):
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

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


def bellman_ford(graph, from_v, to_v):
    """
    到達できないなら INF、負閉路があったら -INF
    :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
    :param int from_v:
    :param int to_v:
    :rtype: int
    """

    def reachable(graph, from_v):
        """
        graph 上で from_v から到達できるかどうかのリスト
        :param graph:
        :param from_v:
        """
        ret = [False] * len(graph)
        ret[from_v] = True
        stack = [from_v]
        while stack:
            v = stack.pop()
            for u, _ in graph[v]:
                if not ret[u]:
                    ret[u] = True
                    stack.append(u)
        return ret

    # from_v から到達でき、かつ to_v へ到達できる頂点のみ考える
    # これら以外には負閉路があっても関係ない
    vertices = []
    revs = [[] for _ in range(len(graph))]
    for v, ud in enumerate(graph):
        for u, d in ud:
            revs[u].append((v, d))
    for v, (r1, r2) in enumerate(zip(reachable(graph, from_v), reachable(revs, to_v))):
        if r1 & r2:
            vertices.append(v)

    dist = [float('inf')] * len(graph)
    dist[from_v] = 0
    updated = True
    for _ in range(len(graph) + 1):
        updated = False
        for v in vertices:
            for u, d in graph[v]:
                if dist[v] + d < dist[u]:
                    dist[u] = dist[v] + d
                    updated = True
        if not updated:
            break
    return -float('inf') if updated else dist[to_v]


ans = -bellman_ford(graph, 0, N - 1)
if ans == INF or ans == -INF:
    print(-1)
else:
    print(max(0, ans))


Fixed submission:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

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


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


vertices = []
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    if v1 & v2:
        vertices.append(i)

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for v in vertices:
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in vertices:
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for v in vertices:
    updated |= prev[v] != dist[v]

if updated or dist[N - 1] == INF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Buggy python submission (verdict: Time Limit Exceeded):
import os
import sys
from collections import deque

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class Dinic:
    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap in graph[v]:
                rev = [v, 0]
                edge = [u, cap, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def _dist(self, s):
        """
        :param int s:
        :rtype: list of int
        :return: s からの距離。残余グラフ上で到達できない場合は -1
        """
        ret = [-1] * len(self.graph)
        ret[s] = 0
        que = deque([(s, 0)])
        while que:
            v, d = que.popleft()
            for u, cap, _ in self.graph[v]:
                if ret[u] < 0 < cap:
                    ret[u] = d + 1
                    que.append((u, d + 1))
        return ret

    def _dfs(self, s, t, dist, iter, flow=float('inf')):
        """
        :param int s:
        :param int t:
        :param list of int dist:
        :param list of int iter:
        :param int flow:
        """
        if s == t:
            return flow
        while iter[s] < len(self.graph[s]):
            edge = self.graph[s][iter[s]]
            to, cap, rev = edge
            if dist[s] < dist[to] and cap > 0:
                f = self._dfs(to, t, dist, iter, min(flow, cap))
                if f > 0:
                    edge[1] -= f
                    rev[1] += f
                    return f
            iter[s] += 1
        return 0

    def maximum_flow(self, from_v, to_v):
        """
        :param int from_v:
        :param int to_v:
        :return: from_v から to_v への最大流
        """
        ret = 0
        while True:
            dist = self._dist(from_v)
            if dist[to_v] < 0:
                break
            iter = [0] * len(self.graph)
            while True:
                flow = self._dfs(from_v, to_v, dist, iter)
                if flow == 0:
                    break
                ret += flow
        return ret


class MinCostFlow:
    """
    最小費用流 ベルマンフォード版
    """

    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, cost, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, cost, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap, cost in graph[v]:
                rev = [v, 0, -cost]
                edge = [u, cap, cost, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def solve(self, from_v, to_v, flow):
        """
        :param int from_v:
        :param int to_v:
        :param int flow:
        :rtype: int
        """
        remains = flow
        total_cost = 0

        prev = total_cost
        while remains > 0:
            # 最短路
            dist = [float('inf')] * len(self.graph)
            preve = [None] * len(self.graph)
            prevv = [None] * len(self.graph)
            dist[from_v] = 0
            stop = False
            cnt = 0
            while not stop:
                stop = True
                for v, edges in enumerate(self.graph):
                    for edge in edges:
                        u, cap, cost, rev = edge
                        if cap > 0 and dist[v] + cost < dist[u]:
                            dist[u] = dist[v] + cost
                            prevv[u] = v
                            preve[u] = edge
                            stop = False
                cnt += 1
                if cnt > len(self.graph) + 100:
                    if prevdist != dist[to_v]:
                        return IINF
                    else:
                        break
                prevdist = dist[to_v]
            flow = remains
            if dist[to_v] == float('inf'):
                total_cost = -1
                break

            v = to_v
            while v != from_v:
                cap = preve[v][1]
                v = prevv[v]
                flow = min(cap, flow)

            # path に沿って flow 流す
            cost = 0
            v = to_v
            while v != from_v:
                cost += preve[v][2] * flow
                preve[v][1] -= flow
                preve[v][3][1] += flow
                v = prevv[v]

            remains -= flow
            total_cost += cost

            if total_cost == prev:
                return total_cost
            prev = total_cost
        return total_cost


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

S = 0
T = N + 1
graph = [[] for _ in range(N + 2)]
graph[S].append((1, 1, 0))
graph[N].append((T, 1, 0))
for a, b, c in ABC:
    graph[a].append((b, IINF, -c + P))

ans = MinCostFlow(graph).solve(S, T, 1)
if ans == IINF:
    print(-1)
elif ans > 0:
    print(0)
else:

    print(-ans)


Fixed submission:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

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


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


vertices = []
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    if v1 & v2:
        vertices.append(i)

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for v in vertices:
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in vertices:
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for v in vertices:
    updated |= prev[v] != dist[v]

if updated or dist[N - 1] == INF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))

Buggy python submission (verdict: Time Limit Exceeded):
import os
import sys
from collections import deque

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class Dinic:
    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap in graph[v]:
                rev = [v, 0]
                edge = [u, cap, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def _dist(self, s):
        """
        :param int s:
        :rtype: list of int
        :return: s からの距離。残余グラフ上で到達できない場合は -1
        """
        ret = [-1] * len(self.graph)
        ret[s] = 0
        que = deque([(s, 0)])
        while que:
            v, d = que.popleft()
            for u, cap, _ in self.graph[v]:
                if ret[u] < 0 < cap:
                    ret[u] = d + 1
                    que.append((u, d + 1))
        return ret

    def _dfs(self, s, t, dist, iter, flow=float('inf')):
        """
        :param int s:
        :param int t:
        :param list of int dist:
        :param list of int iter:
        :param int flow:
        """
        if s == t:
            return flow
        while iter[s] < len(self.graph[s]):
            edge = self.graph[s][iter[s]]
            to, cap, rev = edge
            if dist[s] < dist[to] and cap > 0:
                f = self._dfs(to, t, dist, iter, min(flow, cap))
                if f > 0:
                    edge[1] -= f
                    rev[1] += f
                    return f
            iter[s] += 1
        return 0

    def maximum_flow(self, from_v, to_v):
        """
        :param int from_v:
        :param int to_v:
        :return: from_v から to_v への最大流
        """
        ret = 0
        while True:
            dist = self._dist(from_v)
            if dist[to_v] < 0:
                break
            iter = [0] * len(self.graph)
            while True:
                flow = self._dfs(from_v, to_v, dist, iter)
                if flow == 0:
                    break
                ret += flow
        return ret


class MinCostFlow:
    """
    最小費用流 ベルマンフォード版
    """

    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, cost, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, cost, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap, cost in graph[v]:
                rev = [v, 0, -cost]
                edge = [u, cap, cost, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def solve(self, from_v, to_v, flow):
        """
        :param int from_v:
        :param int to_v:
        :param int flow:
        :rtype: int
        """
        remains = flow
        total_cost = 0

        while remains > 0:
            # 最短路
            dist = [float('inf')] * len(self.graph)
            preve = [None] * len(self.graph)
            prevv = [None] * len(self.graph)
            dist[from_v] = 0
            stop = False
            cnt = 0
            while not stop:
                stop = True
                for v, edges in enumerate(self.graph):
                    for edge in edges:
                        u, cap, cost, rev = edge
                        if cap > 0 and dist[v] + cost < dist[u]:
                            dist[u] = dist[v] + cost
                            prevv[u] = v
                            preve[u] = edge
                            stop = False
                cnt += 1
                if cnt > len(self.graph) + 100:
                    if prevdist != dist[to_v]:
                        return IINF
                    else:
                        break
                prevdist = dist[to_v]
            flow = remains
            if dist[to_v] == float('inf'):
                total_cost = -1
                break

            v = to_v
            while v != from_v:
                cap = preve[v][1]
                v = prevv[v]
                flow = min(cap, flow)

            # path に沿って flow 流す
            cost = 0
            v = to_v
            while v != from_v:
                cost += preve[v][2] * flow
                preve[v][1] -= flow
                preve[v][3][1] += flow
                v = prevv[v]

            remains -= flow
            total_cost += cost
        return total_cost


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

S = 0
T = N + 1
graph = [[] for _ in range(N + 2)]
graph[S].append((1, 1, 0))
graph[N].append((T, 1, 0))
for a, b, c in ABC:
    graph[a].append((b, IINF, -c + P))

ans = MinCostFlow(graph).solve(S, T, 1)
if ans == IINF:
    print(-1)
elif ans > 0:
    print(0)
else:

    print(-ans)


Fixed submission:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

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

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


def can_go_from_0():
    # 1 からのパスがある
    ret = [False] * N

    stack = [0]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u, _ in graph[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


def can_go_to_n():
    revs = [[] for _ in range(N)]
    for a, b, c in ABC:
        revs[b - 1].append(a - 1)

    # n へのパスがある
    ret = [False] * N
    stack = [N - 1]
    while stack:
        v = stack.pop()
        ret[v] = True
        for u in revs[v]:
            if not ret[u]:
                ret[u] = True
                stack.append(u)
    return ret


vertices = []
for i, (v1, v2) in enumerate(zip(can_go_from_0(), can_go_to_n())):
    if v1 & v2:
        vertices.append(i)

# bellman-ford
dist = [INF] * N
dist[0] = 0
for i in range(N):
    for v in vertices:
        for u, d in graph[v]:
            dist[u] = min(dist[v] + d, dist[u])

# 使う頂点がまだアップデートされたらダメ
prev = dist[:]
for v in vertices:
    for u, d in graph[v]:
        dist[u] = min(dist[v] + d, dist[u])
updated = False
for v in vertices:
    updated |= prev[v] != dist[v]

if updated or dist[N - 1] == INF:
    print(-1)
else:
    print(max(-dist[N - 1], 0))