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:
N,M,P = map(int,input().split())
edge = [[]for i in range(N)]
cost = [-float('inf')]*N
cost[0] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    edge[a-1].append([b-1,c-P])

next = [0]*N
next[0] = 1
for i in range(N-1):
    nenext = [0] * N
    for j in range(N):
        if next[j] == 1:
            for b,c in edge[j]:
                cost[b] = max(cost[b],cost[j]+c)
                nenext[b] = 1
    next = nenext[:]


for j in range(N):
    for b,c in edge[j]:
        if cost[b] < cost[j]+c:
            cost[b] = float('inf')


next[0] = 1
for i in range(N-1):
    nenext = [0] * N
    for j in range(N):
        if next[j] == 1:
            for b,c in edge[j]:
                cost[b] = max(cost[b],cost[j]+c)
                nenext[b] = 1
    next = nenext[:]

if cost[-1] == float('inf'):
    print(-1)
else:
    print(max(cost[-1],0))

Submission status: Time Limit Exceeded

Solution code:
N,M,P = map(int,input().split())
edge = [[]for i in range(N)]
cost = [-float('inf')]*N
cost[0] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    edge[a-1].append([b-1,c-P])

for i in range(N-1):
    for j in range(N):
        for b,c in edge[j]:
            cost[b] = max(cost[b],cost[j]+c)


for j in range(N):
    for b,c in edge[j]:
        if cost[b] < cost[j]+c:
            cost[b] = float('inf')


for i in range(N-1):
    for j in range(N):
        for b,c in edge[j]:
            cost[b] = max(cost[b],cost[j]+c)


if cost[-1] == float('inf'):
    print(-1)
else:
    print(max(cost[-1],0))

Submission status: Time Limit Exceeded

Solution code:
import sys


def reverse_search(n, parents):
    q = [n - 1]
    visited = set()
    while q:
        v = q.pop()
        if v in visited:
            continue
        visited.add(v)
        q.extend(u for u in parents[v] if u not in visited)
    return visited


n, m, p = list(map(int, input().split()))
INF = 10 ** 12
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add((b, p - c))
    parents[b].add(a)
reachable = reverse_search(n, parents)

dist = [INF] * n
dist[0] = 0
for _ in range(len(reachable)):
    updated = False
    for v in reachable:
        d = dist[v]
        if d == INF:
            continue
        for u, c in links[v]:
            if dist[u] > d + c:
                dist[u] = d + c
                updated = True
    if not updated:
        break
else:
    print(-1)
    exit()

print(max(0, -dist[n - 1]))

Submission status: Time Limit Exceeded

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

g = [[] for i in range(N)]
revg = [[] for i in range(N)]

for a,b,_ in ABC:
    a,b = a-1, b-1
    g[a].append(b)
    revg[b].append(a)

st = set([0])
stack = [0]
while stack:
    v = stack.pop()
    for to in g[v]:
        if to in st: continue
        st.add(to)
        stack.append(to)

revst = set([N-1])
stack = [N-1]
while stack:
    v = stack.pop()
    for to in revg[v]:
        if to in revst: continue
        revst.add(to)
        stack.append(to)

use = st & revst
es = []
for a,b,c in ABC:
    a,b = a-1, b-1
    if a in use and b in use:
        es.append((a,b,c))

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in es:
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1:
                print(-1)
                exit()

print(max(0,-d[-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
N, M, P = [int(x) for x in input().split()]
forward = {}
backward = {}
for _ in range(M):
  A, B, C = [int(x) for x in input().split()]
  forward[A] = forward.get(A, {})
  if B in forward[A]:
    forward[A][B] = max(forward[A][B], C-P)
  else:
    forward[A][B] = C-P
  backward[B] = backward.get(B, {})
  if A in backward[B]:
    backward[B][A] = max(backward[B][A], C-P)
  else:
    backward[B][A] = C-P
#print(forward)
#print(backward)
reachable = set([N])
to_track = set([N])
while to_track:
  x = to_track.pop()
  if x not in backward:
    continue
  for y in backward[x]:
    if y not in reachable:
      to_track.add(y)
      reachable.add(y)
#print(reachable)
if 1 not in reachable:
  print(-1)
  sys.exit()

forward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
           for k, v in forward.items() if k in reachable}
#print(forward)
# backward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
#            for k, v in backward.items() if k in reachable}
#print(backward)

dist = {k: -float('inf') for k in reachable} 
dist[1] = 0
#print(reachable)
#print(dist)
#print(forward)
for _ in range(len(reachable)):
  renewed = False
  for x, y_dict in forward.items():
    for y in y_dict:
 #     print(x, y, forward[x][y], dist[x], dist[y])
      if dist[y] < dist[x] + forward[x][y]:
        renewed = True
        dist[y] = dist[x] + forward[x][y]
if renewed:
  # print('loop')
  print(-1)
else:
  print(max(0,dist[N]))

Submission status: Time Limit Exceeded

Solution code:
import sys, math, itertools, bisect, copy, re
from collections import Counter, deque, defaultdict

from itertools import accumulate, permutations, combinations, takewhile, compress, cycle

# from functools import reduce
# from math import ceil, floor, log10, log2, factorial
# from pprint import pprint
import heapq

INF = float('inf')
MOD = 10 ** 9 + 7
EPS = 10 ** -7
sys.setrecursionlimit(1000000)


# N = int(input())
# N,M = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]
# A = [int(input()) for _ in range(N)]
# DP = [[0] * 100 for _ in range(100)]
# DP = defaultdict(lambda: float('inf'))

def dfs(n):
    if n in to:
        return
    else:
        to.add(n)
        for a, b, c in edges:
            if a == n:
                dfs(b)


def dfs2(n):
    if n in ot:
        return
    else:
        ot.add(n)
        for a, b, c in edges:
            if b == n:
                dfs2(a)


N, M, P = [int(x) for x in input().split()]
edges = []
# 1から行けるノード
to = set()
# N-1に到達できるノード
ot = set()
for _ in range(M):
    a, b, c = [int(x) for x in input().split()]
    a, b, c = a - 1, b - 1, c - P
    edges.append((a, b, -c))

dfs(0)
dfs2(N - 1)

W = [INF] * N
W[0] = 0
for cnt in range(N + 1):
    isShusoku = True
    for a, b, c in edges:
        if b in to and b in ot:
            if W[b] > W[a] + c:
                W[b] = W[a] + c
                isShusoku = False

if isShusoku == True:
    print(max(0,-W[N - 1]))
else:
    print(-1)
pass

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque
INF = float("inf")


# 有効グラフを仮定する。
class Graph(object):
    def __init__(self, N):
        self.N = N
        self.V = list(range(N))
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        """辺を加える。edgeは(始点, 終点、重み)からなるリスト
        重みがなければ、重み1とする。
        """
        if len(edge) == 2:
            edge.append(1)
        elif len(edge) != 3:
            print("error in add_edge")
            pass

        s, t, w = edge
        self.E[s].append([t, w])

        pass


def BellmanFord(g: Graph, s):
    """ベルマンフォード法による最短経路
    """
    N = g.N
    dist = [INF]*N
    dist[s] = 0
    prev = [None]*N

    # 辺の緩和
    for _ in range(N):
        for from_ in range(N):      # ここの２重ループはO(M)
            for to_, weight in g.E[from_]:
                if dist[to_] > dist[from_] + weight:
                    dist[to_] = dist[from_] + weight
                    prev[to_] = from_
    # 負の重みの閉路がないかチェック
    for from_ in range(N):
        for to_, weight in g.E[from_]:
            if dist[from_]+weight < dist[to_]:
                return None, None

    return dist, prev


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    for i in range(M):
        C[i] = P - C[i]

    rev_g = Graph(N)
    for a, b, c in zip(A, B, C):
        rev_g.add_edge([b-1, a-1, c])

    # Nに到達できないノードは除く
    visitable = [False]*N
    visitable[N-1] = True
    q = deque()
    q.append(N-1)
    while len(q) > 0:
        curr = q.popleft()
        for t_, w in rev_g.E[curr]:
            if not visitable[t_]:
                visitable[t_] = True
                q.append(t_)

    g = Graph(N)
    for a, b, c in zip(A, B, C):
        if visitable[a-1] and visitable[b-1]:
            g.add_edge([a-1, b-1, c])

    dist, prev = BellmanFord(g, 0)
    if dist is None:
        print(-1)
    else:
        print(max(-dist[-1], 0))

    # print(longest)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, P, A, B, C)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

for i in range(m):
    A[i][2] = - (A[i][2]-p)

#import numpy as np
# A = np.full(np.inf, (n+1, n+1))

# scipy.sparse.csgraph.bellman_ford


S = [[10**10, 0, 0] for i in range(n+1)]

S[1][0]=0
S[1][1]=1
S[n][2]=1

for i in range(m):
    if A[i][0] == 1:
        S[A[i][1]][0] = A[i][2]

for j in range(n-1):
    for i in range(m):
        S[A[i][1]][0] = min(S[A[i][1]][0], S[A[i][0]][0] + A[i][2])
        S[A[i][1]][1] = max(S[A[i][1]][1], S[A[i][0]][1])
        S[A[i][0]][2] = max(S[A[i][1]][2], S[A[i][0]][2])

ANS0 = [S[i][0] for i in range(len(S))]

for j in range(n-1):
    for i in range(m):
        S[A[i][1]][0] = min(S[A[i][1]][0], S[A[i][0]][0] + A[i][2])
        # S[A[i][1]][1] = max(S[A[i][1]][1], S[A[i][0]][1])
        # S[A[i][0]][2] = max(S[A[i][1]][2], S[A[i][0]][2])

ANS1 = [S[i][0] for i in range(len(S))]

#print(ANS0, ANS1)

imp = 0

for i in range(len(S)):
    if S[i][1] == 1 and S[i][2] == 1:
        if ANS0[i] != ANS1[i]:
            imp = 1

if imp == 1:
    print(-1)
else:
    print(max(0, -ANS0[n]))

Submission status: Time Limit Exceeded

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

N, M, P = list(map(int, input().split()))

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["score"] = -1000000000000000
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

stack = [0]
tree[0]["score"] = 0

for times in range(N):
	for i in range(N):
		if tree[i]["reach"] == 1:
			for edge in tree[i]["eda"]:
				if tree[edge[1]]["reach"] == 1 and tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					tree[edge[1]]["score"] = tree[edge[0]]["score"] + edge[2] - P

for i in range(N):
	if tree[i]["reach"] == 1:
		for edge in tree[i]["eda"]:
			if tree[edge[1]]["reach"] == 1 and tree[edge[0]]["score"] > -10000000000 and tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
				print(-1)
				exit()
print(max(0,tree[N-1]["score"]))

Submission status: Time Limit Exceeded

Solution code:

N, M, P = list(map(int, input().split()))

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["score"] = -1000000000000000
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

stack = [0]
tree[0]["score"] = 0

for times in range(N):
	for i in range(N):
		if tree[i]["reach"] == 1:
			for edge in tree[i]["eda"]:
				if tree[edge[1]]["reach"] == 1 and tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					tree[edge[1]]["score"] = tree[edge[0]]["score"] + edge[2] - P

for i in range(N):
	if tree[i]["reach"] == 1:
		for edge in tree[i]["eda"]:
			if tree[edge[1]]["reach"] == 1 and tree[edge[0]]["score"] > -10000000000 and tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
				print(-1)
				exit()
print(max(0,tree[N-1]["score"]))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict


def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(M)]
    li = defaultdict(list)

    for i in range(M):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - P)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                    li_top.append(e[0])
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]
                        li_top.append(e[0])

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict


def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(M)]
    li = defaultdict(list)

    for i in range(M):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - P)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top.copy()
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                    li_top.append(e[0])
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]
                        li_top.append(e[0])

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Time Limit Exceeded

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

N, M, P = list(map(int, input().split()))

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["keiro"] = set([0])
	tree[i]["score"] = -1000000000000000
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

stack = [0]
tree[0]["keiro"].add(0)
tree[0]["score"] = 0
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda"]:
		if tree[edge[1]]["reach"] == 1:
			if edge[1] in tree[edge[0]]["keiro"]:
				if tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					print(-1)
					exit()
			else:
				if tree[edge[1]]["score"] < tree[edge[0]]["score"] + edge[2] - P:
					tree[edge[1]]["score"] = tree[edge[0]]["score"] + edge[2] - P
					stack.append(edge[1])
					tree[edge[1]]["keiro"] = copy.deepcopy(tree[edge[0]]["keiro"])
					tree[edge[1]]["keiro"].add(edge[1])
print(max(tree[N - 1]["score"],0))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bellman_ford(N: int, edges: list, src: int) -> list:
    """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

    # 頂点[ある始点からの最短距離] (経路自体を知りたい時はここに前の頂点も持たせる)
    res = [INF] * N
    res[src] = 0
    # 各辺によるコストの置き換えを頂点数N-1回繰り返す
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    # 負の閉路(いくらでもコストを減らせてしまう場所)がないかチェックする
    for i in range(N):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
                if dest == N-1:
                    # 頂点Nがそれに該当していたら空リストを返却
                    return []
    # 問題なければ頂点リストを返却
    return res

N, M, P = MAP()
edges = []
for i in range(M):
    a, b, c = MAP()
    # Pは最後に請求される、だけど、ようは動く度に支払ってると思ってもいい
    edges.append((a-1, b-1, -c+P))

res = bellman_ford(N, edges, 0)
if not len(res):
    print(-1)
else:
    # 正負を直す
    ans = -res[N-1]
    # スコアがマイナスなら0
    print(max(0, ans))

Submission status: Time Limit Exceeded

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

def BF(edges,n,s):
    inf=float("inf")
    d=[inf for i in range(n+1)]
    d[s]=0
    update=True
    for i in range(n+1):
      update=False
      for v,u,cost in edges:
        if cand[v]!=1 or cand[u]!=1:
          continue
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
          update=True
      if update==False:
        break
      if i==n:
        return inf
    return -d[-1]

def DFS_1toN(v):
  for u in to[v]:
    if toflag[u]==0:
      toflag[u]=1
      DFS_1toN(u)
      
def DFS_Nto1(v):
  for u in ot[v]:
    if otflag[u]==0:
      otflag[u]=1
      DFS_Nto1(u)
    
n,m,p=map(int,input().split())
g=[]
to=[[] for _ in range(n+1)]
ot=[[] for _ in range(n+1)]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
  to[a].append(b)
  ot[b].append(a)
toflag=[0]*(n+1)
toflag[1]=1
DFS_1toN(1)
otflag=[0]*(n+1)
otflag[n]=1
DFS_Nto1(n)
cand=[0]*(n+1)
for i in range(1,n+1):
  cand[i]=toflag[i]*otflag[i]
ans=BF(g,n,1)
if ans==float('inf'):
  print(-1)
else:
  print(max(ans,0))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

# preprocess
to = [[] for _ in range(N)]
fr = [[] for _ in range(N)]
for a, b, c in ABC:
    to[a].append(b)
    fr[b].append(a)

visitable_s = [False] * N
q = deque()
q.append(0)
visitable_s[0] = True
while len(q):
    a = q.pop()
    for b in to[a]:
        if not visitable_s[b]:
            visitable_s[b] = True
            q.append(b)

visitable_g = [False] * N
q = deque()
q.append(N - 1)
visitable_g[N - 1] = True
while len(q):
    a = q.pop()
    for b in fr[a]:
        if not visitable_g[b]:
            visitable_g[b] = True
            q.append(b)

visitable = [visitable_s[i] and visitable_g[i] for i in range(N)]
inf = float("inf")
d = [inf] * N
d[0] = 0

# Bellman-Ford
for i in range(N):
    for a, b, c in ABC:
        if not visitable[a] or not visitable[b]:
            continue
        if d[b] <= d[a] + c:
            continue
        if i == N - 1:
            print(-1)
            exit()
        d[b] = d[a] + c
ans = d[N - 1]
print(max(0, -d[N - 1]))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


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

    FORWARD = defaultdict(lambda: [])
    BACK = defaultdict(lambda: [])
    for a, b, c in ABC:
        t = FORWARD[a]
        t.append((b, c))
        FORWARD[a] = t

        t = BACK[b]
        t.append((a, c))
        BACK[b] = t

    mem = {N}
    q = [N]
    while len(q) != 0:
        t = q.pop()
        for t2, _ in BACK[t]:
            if t2 in mem:
                continue
            q.append(t2)
            mem.add(t2)

    ABC = [(a, b, P - c) for a, b, c in ABC if a in mem and b in mem]

    table = [MAX] * (N + 1)
    history_table = [set() for _ in range(N + 1)]
    table[1] = 0
    # history_table[1] = {1}
    # table2 = [-1] * N
    for _ in range(len(mem)):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                # if b in history_table[a]:
                #     print(-1)
                #     return
                table[b] = table[a] + c
                # h2 = set(history_table[a])
                # h2.add(b)
                # history_table[b] = h2
    for a, b, c in ABC:
        if table[a] == MAX:
            continue
        if table[a] + c < table[b]:
            print(-1)
            return
    print(max(0, -table[N]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    dist = [sys.maxsize] * (N + 1)

    dist[1] = 0
    for _ in range(N):
        for j in range(M):
            weight = -(C[j] - P)
            if dist[B[j]] > dist[A[j]] + weight:
                dist[B[j]] = dist[A[j]] + weight

    result = -dist[N]

    for _ in range(N + 1):
        for j in range(M):
            weight = -(C[j] - P)
            if dist[B[j]] > dist[A[j]] + weight:
                dist[B[j]] = dist[A[j]] + weight

    if result != -dist[N]:
        print(-1)
    else:
        print(max(-dist[N], 0))


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


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

    FORWARD = defaultdict(lambda: [])
    BACK = defaultdict(lambda: [])
    for a, b, c in ABC:
        t = FORWARD[a]
        t.append((b, c))
        FORWARD[a] = t

        t = BACK[b]
        t.append((a, c))
        BACK[b] = t

    mem = {N}
    q = [N]
    while len(q) != 0:
        t = q.pop()
        for t2, _ in BACK[t]:
            if t2 in mem:
                continue
            q.append(t2)
            mem.add(t2)

    ABC = [(a, b, P - c) for a, b, c in ABC if a in mem and b in mem]

    table = [MAX] * (N + 1)
    history_table = [set() for _ in range(N + 1)]
    table[1] = 0
    history_table[1] = {1}
    # table2 = [-1] * N
    for _ in range(len(mem)):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                if b in history_table[a]:
                    print(-1)
                    return
                table[b] = table[a] + c
                h2 = set(history_table[a])
                h2.add(b)
                history_table[b] = h2
    print(max(0, -table[N]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
(N,M,P),*E=[list(map(int,s.split()))for s in open(0).readlines()]
D=[0]*2+[-9e9]*N
def f():
    for _ in D:
        for (a,b,c)in E:D[b]=max(D[b],D[a]+c-P)
    return D[N]
s=f()
print([max(s,0),-1][s<f()])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]

def sp(s,n,w,es):
  d=[float("inf")]*n
  d[s]=0
  count=0
  ret=[]
  while count<n*2:
    update=False
    for i in range(w):
      e0,e1,e2=es[i]
      if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
        d[e1]=d[e0]+e2
        update=True
    if not update:
      ret=[d[-1],d[-1]]
      break
    else:
      count+=1
      if count%n==0:
        ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Time Limit Exceeded

Solution code:
#https://qiita.com/chun1182/items/ddf2b6cba932b2bb0d4e
def BF(p,n,s):
    inf=float("inf")
    d=[inf for i in range(n)]
    d[s-1]=0
    for i in range(n+1):
        for e in p:
            if e[0]!=inf and d[e[1]-1]>d[e[0]-1]+e[2]:
                d[e[1]-1] = d[e[0]-1] + e[2]
    ans1=d[-1]
    for i in range(n+1):
        for e in p:
            if e[0]!=inf and d[e[1]-1]>d[e[0]-1]+e[2]:
                d[e[1]-1] = d[e[0]-1] + e[2]
    ans2=d[-1]
    if ans1>ans2:
      return ['inf']
    else:
      return [-ans1]
n,m,p=map(int,input().split())
g=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
g.append([n,n+1,0])
ans=BF(g,n+1,1)[-1]
if ans=='inf':
  print(-1)
else:
  print(max(ans,0))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]

def sp(s,n,w,es):
  d=[float("inf")]*n
  d[s]=0
  count=0
  chk=False
  ret=[0]*(2*n)
  while count<n*2:
    update=False
    for i in range(w):
      e0,e1,e2=es[i]
      if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
        d[e1]=d[e0]+e2
        if i==-1:
          return [d[-1],d[-1]]
          chk=True
          break
    ret[count]=d[-1]
    count+=1
  if chk==False:
    return [ret[n-1],ret[2*n-1]]
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
import heapq

def solve():
    input = sys.stdin.readline
    N, M, P = map(int, input().split())
    graph = [None for i in range(M)]
    for i in range(M):
        a, b, c = map(int, input().split())
        graph[i] = (a - 1, b - 1, P - c)

    gain = [10 ** 20 for i in range(N)]
    gain[0] = 0
    
    for i in range(N):
        update = False
        for efrom, eto, ecost in graph:
            if gain[efrom] < 10 ** 20 and gain[eto] > gain[efrom] + ecost:
                gain[eto] = gain[efrom] + ecost
                update = True
        if not update:
            print(max(-gain[N-1], 0))
            break
    else:
        possible_min = gain[N-1]
        for i in range(N):
            for efrom, eto, ecost in graph:
                if gain[efrom] < 10 ** 20 and gain[eto] > gain[efrom] + ecost:
                    gain[eto] = gain[efrom] + ecost

        if gain[N-1] == possible_min: print(max(-gain[N-1], 0))
        else: print(-1)

    return 0

if __name__ == "__main__":
    solve()