Problem:


Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Time Limit Exceeded

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

N, M, P = [int(item) for item in input().split()]

from collections import defaultdict
next_b = defaultdict(lambda: [])

for i in range(M):
    a, b, c = [int(item) for item in input().split()]
    next_b[a].append([b, c - P])

max_sc = [0] + [-int(1e10)] * (N - 1)
prev_sc = [0] + [-int(1e10) - 1] * (N - 1)

for loop in range(2 * N):
    if max_sc == prev_sc:
        print(max(max_sc[N - 1], 0))
        break
    prev_sc = copy.deepcopy(max_sc)
    for i in range(N):
        for d, scr in next_b[i + 1]:
            max_sc[d - 1] = max(prev_sc[i] + scr, max_sc[d - 1])
    if loop == N - 1:
        max_sc_n = copy.deepcopy(max_sc)
else:
    if max_sc_n[N - 1] == max_sc[N - 1]:
        print(max(0, max_sc[N - 1]))
    else:
        print(-1)

Submission status: Time Limit Exceeded

Solution code:
def main(sample_file = ''):

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    # Graph: https://en.wikipedia.org/wiki/Directed_graph
    # Bellman-Ford: O(|V||E|). Use this if there exists an edge with negative length in the graph
    # After N steps, the shortest path has converded if there doesn't exist an cycle of edges with negative
    # Watch out: d[N] == d[2*N] doesn't necessarily mean the graph doesn't have negative cycle
    # ref: https://www.youtube.com/watch?v=1Z6ofKN03_Y

    # 

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions to read input
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)
        
    # ----------------------------------
    # main

    N, M, P = R()
    ABC = [R() for _ in range(M)]
    ABC = [(a-1, b-1, c-P) for a, b, c in ABC]

    def BellmanFord(N, M, ABC, vertex_start=0, vertex_end = N-1, return_if_indefinite = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm
        
        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci 
            vertex_start (int, optional): start vertex. Defaults to 0.
            vertex_end (int, optional): end vertex. Defaults to N-1.
            return_if_indefinite (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.
        
        Returns:
            int or string: normally int (but can be str if you set return_if_indefinite to str)
        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides
        
        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)
        
        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]
        
        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return return_if_indefinite
            if not updated:
                break
        return dist[vertex_end]

    ans = BellmanFord(N, M, ABC, return_if_indefinite = 'inf')
    if ans == 'inf':
        print(-1)
    else:
        print(max(ans, 0))

    # N, M, P = R()
    # ABC = [R() for _ in range(M)]
    # ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
    
    # vertex_start, vertex_end = 0, N-1
    # reachable_from_start = [False] * N
    # reachable_to_end = [False] * N
    # reachable_from_start[vertex_start] = True
    # reachable_to_end[vertex_end] = True
    # reachable_from_both_sides = [False] * N

    # dfs_from_start = []
    # dfs_to_end = []
    # reachable_to_direct = defaultdict(list)
    # reachable_from_direct = defaultdict(list)

    # for a, b, c in ABC:
    #     reachable_to_direct[a].append(b)
    #     reachable_from_direct[b].append(a)
    #     if a == vertex_start:
    #         dfs_from_start.append(b)
    #         reachable_from_start[b] = True
    #     if b == vertex_end:
    #         dfs_to_end.append(a)
    #         reachable_to_end[a] = True
    
    # while dfs_from_start:
    #     v = dfs_from_start.pop()
    #     for i in reachable_to_direct[v]:
    #         if not reachable_from_start[i]:
    #             reachable_from_start[i] = True
    #             dfs_from_start.append(i)

    # while dfs_to_end:
    #     v = dfs_to_end.pop()
    #     for i in reachable_from_direct[v]:
    #         if not reachable_to_end[i]:
    #             reachable_to_end[i] = True
    #             dfs_to_end.append(i)
    
    # for i in range(N):
    #     reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
    
    # dist = [-INF for i in range(N)]
    # dist[vertex_start] = 0
    # for i in range(N):
    #     updated = False
    #     for a, b, c in ABC:
    #         if not reachable_from_both_sides[a]:
    #             continue
    #         if dist[a] != INF and dist[a] + c > dist[b]:
    #             dist[b] = dist[a] + c
    #             updated = True
    #             if i == N-1:
    #                 print(-1)
    #                 return
    #     if not updated:
    #         break
    # print(max(dist[vertex_end], 0))
                
    # to finish code, use return instead of exit()
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def bellman_ford(N, adj, start):
    ans = [float("inf")] * N
    q = deque()
    q.append((start, 0, 0))
    while len(q):
        i, cost, path = q.popleft()
        if cost >= ans[i]:
            continue
        ans[i] = cost
        for j in adj[i]:
            ncost = cost + adj[i][j]
            if path > N:
                ncost = -float("inf")
            q.append((j, ncost, path+1))
    return ans


def main():
    N, M, P = map(int, input().split())
    adj = [{} for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        if B-1 in adj[A-1]:
            adj[A-1][B-1] = min(P-C, adj[A-1][B-1])
        else:
            adj[A-1][B-1] = P-C
    costs = bellman_ford(N, adj, 0)
    ans = -costs[N-1]
    if ans < 0:
        print(0)
    elif ans == float("inf"):
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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


def bellman_ford(N, adj, start):
    ans = [float("inf")] * N
    q = deque()
    q.append((start, 0, {}))
    while len(q):
        i, cost, history = q.popleft()
        if cost >= ans[i]:
            continue
        ans[i] = cost
        history = {k: history[k] for k in history}
        history[i] = cost
        for j in adj[i]:
            ncost = cost + adj[i][j]
            if j in history and history[j] > ncost:
                ncost = -float("inf")
            q.append((j, ncost, history))
    return ans


def main():
    N, M, P = map(int, input().split())
    adj = [{} for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        if B-1 in adj[A-1]:
            adj[A-1][B-1] = min(P-C, adj[A-1][B-1])
        else:
            adj[A-1][B-1] = P-C
    costs = bellman_ford(N, adj, 0)
    ans = -costs[N-1]
    if ans < 0:
        print(0)
    elif ans == float("inf"):
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

def inpl(): return list(map(int, input().split()))

N, M, P = inpl()
INF = 10**12
G = [[] for _ in range(N)]
E = []
G2 = [[] for _ in range(N)]
rG2 = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = inpl()
    G[a-1].append([b-1, -c+P])
    G2[a-1].append(b-1)
    rG2[b-1].append(a-1)
    E.append([a-1, b-1, -c+P])


def SCC(G, rG):
    N = len(G)
    def dfs(i):
        nonlocal t, rorder, searched
        searched[i] = True
        for j in G[i]:
            if not searched[j]:
                dfs(j)
        rorder[t] = i
        t += 1

    def rdfs(i):
        nonlocal t, group, g
        group[i] = g
        for j in rG[i]:
            if group[j] == -1:
                rdfs(j)

    t = 0
    rorder = [-1]*N
    searched = [0]*N
    group = [-1]*N

    for i in range(N):
        if not searched[i]:
            dfs(i)
    g = 0
    for i in range(N-1, -1, -1):
        if group[rorder[i]] == -1:
            rdfs(rorder[i])
            g += 1
    return group, g


def belman_ford(V, edges, r):
    "If glaph contains negative cycles then return True"
    D = [INF]*(V)
    D[r] = 0
    if V == 1:
        return False, [0]
    OK = True
    for _ in range(V-1):
        update = False
        for s, t, d in edges:
            if D[t] > D[s] + d:
                D[t] = D[s] + d
                update = True
        if not update:
            OK = False
    return OK, D

group, gsize = SCC(G2, rG2)
groups = [[] for _ in range(gsize)]
for i in range(N):
    groups[group[i]].append(i)

score = [10**12 for _ in range(N)]
negative_groups = [0]*N


for g in range(gsize):
    ggs = set(groups[g])
    s = groups[g][0]
    score[s] = 0
    Q = deque([s])
    while Q:
        p = Q.popleft()
        for q, c in G[p]:
            if not q in ggs:
                continue
            if score[p] + c < score[q]:
                score[q] = score[p] + c
                Q.append(q)
        if score[s] < 0:
            for g in ggs:
                negative_groups[g] = 1
            break

s = 0
Q = deque([s])
reach1 = [0]*N
reach1[0] = 1

while Q:
    p = Q.popleft()
    for q in G2[p]:
        if not reach1[q]:
            reach1[q] = 1
            Q.append(q)

s = N-1
Q = deque([s])
reachN = [0]*N
reachN[-1] = 1

while Q:
    p = Q.popleft()
    for q in rG2[p]:
        if not reachN[q]:
            reachN[q] = 1
            Q.append(q)

NEGATIVE, D = belman_ford(N, E, 0)

if any([reach1[i]&reachN[i]&negative_groups[i] for i in range(N)]) or reach1[-1]==0:
    print(-1)
else:
    print(max(0, -D[-1]))

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int,input().split())
dist = [0] + [float('inf')] * (N - 1)

a = []
b = []
c = []

for i in range(M):
    i,j,k = map(int,input().split())
    a.append(i)
    b.append(j)
    c.append(-1*(k - P))

INF = float('inf')

for i in range(N-1):
    for j in range(M):
        if dist[a[j] - 1] == INF: continue
        if dist[b[j] - 1] > dist[a[j] - 1] + c[j]:
            dist[b[j] - 1] = dist[a[j] - 1] + c[j]
        
ans = dist[N -1]

negative = [False] * N

for i in range(N):
    for j in range(M):
        if dist[a[j] - 1] == INF: continue
        if dist[b[j] - 1] > dist[a[j] - 1] + c[j]:
            dist[b[j] - 1] = dist[a[j] - 1] + c[j]
            negative[b[j] - 1] = True

        if negative[a[j] - 1] == True:
            negative[b[j] - 1] = True

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

Submission status: Time Limit Exceeded

Solution code:
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))

Submission status: Time Limit Exceeded

Solution code:
# YouTube
from collections import defaultdict
import sys

sys.setrecursionlimit(10 ** 6)

def main():
    def dfs(u):
        ok[u] = 1
        for v in to[u]:
            if ok[v]: continue
            dfs(v)

    def rdfs(u):
        ok[u] += 2
        for v in fr[u]:
            if ok[v] > 1: continue
            rdfs(v)

    inf = 10 ** 9
    to = defaultdict(list)
    fr = defaultdict(list)
    abc = []
    n, m, p = map(int, input().split())
    ok = [0] * n
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        c = -(c - p)
        to[a].append(b)
        fr[b].append(a)
        abc.append([a, b, c])
    dfs(0)
    rdfs(n - 1)
    score = [inf] * n
    score[0] = 0
    for i in range(n):
        stop = True
        for a, b, c in abc:
            if ok[a] < 3 or ok[b] < 3: continue
            tmp = score[a] + c
            if tmp < score[b]:
                score[b] = tmp
                stop = False
        if stop:
            print(max(0, -score[n - 1]))
            break
    else:
        print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
# YouTube
from collections import defaultdict
import sys

sys.setrecursionlimit(10 ** 6)

def dfs(u):
    ok[u] = 1
    for v in to[u]:
        if ok[v]: continue
        dfs(v)

def rdfs(u):
    ok[u] += 2
    for v in fr[u]:
        if ok[v] > 1: continue
        rdfs(v)

inf = 10 ** 9
to = defaultdict(list)
fr = defaultdict(list)
abc = []
n, m, p = map(int, input().split())
ok = [0] * n
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = -(c - p)
    to[a].append(b)
    fr[b].append(a)
    abc.append([a, b, c])
dfs(0)
rdfs(n - 1)
score = [inf] * n
score[0] = 0
for i in range(n):
    stop = True
    for a, b, c in abc:
        if ok[a] < 3 or ok[b] < 3: continue
        tmp = score[a] + c
        if tmp < score[b]:
            score[b] = tmp
            stop = False
    if stop:
        print(max(0, -score[n - 1]))
        break
else:
    print(-1)