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
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    inf = 10**9
    l = np.zeros((n, n))
    tree_forth = [[] for _ in range(n)]
    tree_back = [[] for _ in range(n)]
    for i in range(m):
        a, b, c =map(int, input().split())
        tree_forth[a-1].append(b-1)
        tree_back[b-1].append(a-1)
        c = p-c
        if c == 0:
            c = 10**(-7.9)
        if l[a-1][b-1] == 0:
            l[a-1][b-1] = c
        else:
            l[a-1][b-1] = min(l[a-1][b-1], c)
    x = l[-1, 0]
    l[-1][0] = 10**(-7.9)
    n, labels = connected_components(l, connection="strong")
    l = l[labels == labels[0]][:, labels == labels[0]]
    l[-1, 0] = x
    
    try:
        print(max(0, int(bellman_ford(csr_matrix(l))[0][-1])*(-1)))
    except:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse import csr_matrix
from collections import deque
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    inf = 10**9
    l = np.zeros((n, n))
    tree_forth = [[] for _ in range(n)]
    tree_back = [[] for _ in range(n)]
    for i in range(m):
        a, b, c =map(int, input().split())
        tree_forth[a-1].append(b-1)
        tree_back[b-1].append(a-1)
        c = p-c
        if c == 0:
            c = 10**(-8)
        if l[a-1][b-1] == 0:
            l[a-1][b-1] = c
        else:
            l[a-1][b-1] = min(l[a-1][b-1], c)
    
    already1, already2 = [True]*n, [True]*n
    for already, tree, start in zip([already1, already2], [tree_forth, tree_back], [0, n-1]):
        not_yet = deque([start])
        already[start] = False
        while not_yet:
            key = not_yet.pop()
            for v in tree[key]:
                if already[v] == False:
                    continue
                already[v] = False
                not_yet.append(v)
    
    for i in range(n):
        if already1[i] or already2[i]:
            for j in range(n):
                l[i][j] = 0
                l[j][i] = 0
            
    
    try:
        print(max(0, int(bellman_ford(csr_matrix(l))[0][-1])*(-1)))
    except:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)

N,M,P=map(int,input().split())
ways=[[] for _ in range(N)]
Rways=[[] for _ in range(N)]

for i in range(M):
  A,B,C=map(int,input().split())
  ways[A-1].append([B-1,C-P])
  Rways[B-1].append(A-1)
  
  
visited=[-float("inf")]*N
visited[0]=0

blacklist=[True]*N
blacklist[-1]=False
"""
for c in range(M):
  for i in range(N):
    if blacklist[i]==True:
      continue
    for to in Rways[i]:
      blacklist[to]=False
"""
def b_update(nord):
  global blacklist
  for to in Rways[nord]:
    if blacklist[to]==True:
      blacklist[to]=False
      b_update(to)
      
b_update(N-1)

for c in range(M+1):
  flag=False
  for i in range(N):
    debit=visited[i]
    if debit==-float("inf"):
      continue
    for to,cost in ways[i]:
      if visited[to]<debit+cost and not blacklist[to]:
        visited[to]=debit+cost
        flag=True
        
  if not flag:
    break
  if c==M:
    print(-1)
    exit()
      
ans=visited[-1]
if ans==-float("inf"):
  print(-1)
else:
  print(max(ans,0))

Submission status: Time Limit Exceeded

Solution code:
N,M,P=map(int,input().split())
ways=[[] for _ in range(N)]
Rways=[[] for _ in range(N)]

for i in range(M):
  A,B,C=map(int,input().split())
  ways[A-1].append([B-1,C-P])
  Rways[B-1].append(A-1)
  
  
visited=[-float("inf")]*N
visited[0]=0

blacklist=[True]*N
blacklist[-1]=False

for c in range(M):
  for i in range(N):
    if blacklist[i]==True:
      continue
    for to in Rways[i]:
      blacklist[to]=False

for c in range(M+1):
  flag=False
  for i in range(N):
    debit=visited[i]
    if debit==-float("inf"):
      continue
    for to,cost in ways[i]:
      if visited[to]<debit+cost and not blacklist[to]:
        visited[to]=debit+cost
        flag=True
        
  if not flag:
    break
  if c==M:
    print(-1)
    exit()
      
ans=visited[-1]
if ans==-float("inf"):
  print(-1)
else:
  print(max(ans,0))

Submission status: Time Limit Exceeded

Solution code:
import sys

input=sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()


def II(): return int(input())


def MI(): return map(int,input().split())


def MF(): return map(float,input().split())


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


def LF(): return list(map(float,input().split()))


def TI(): return tuple(map(int,input().split()))


# rstrip().decode('utf-8')


def main():
	n,m,p=MI()
	G=[[] for _ in range(n+1)]
	
	for _ in range(m):
		a,b,c=MI()
		G[a].append([b,c-p])
	#print(G)
	
	coin=[-10**18]*(n+1)
	coin[1]=0
	
	for _ in range(n):
		for i in range(1,n+1):
			for b,c in G[i]:
				coin[b]=max(coin[b],coin[i]+c)
	#print(coin)
	ans=coin[-1]
	
	check=[False]*(n+1)
	for i in range(1,n+1):
		for b,c in G[i]:
			if coin[b]<coin[i]+c and coin[b]>-10**10:
				check[b]=True
	
	for _ in range(n):
		for i in range(1,n+1):
			for b,c in G[i]:
				check[b]=check[i] or check[b]
	#print(check)
	
	if check[n]==True:
		ans=-1
	else:
		ans=max(ans,0)
	
	print(ans)
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

if __name__=="__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
INF=10**30
def Belman_Ford(s,N,Edge):
    dist=[INF]*N
    neg=[False]*N
    dist[s]=0
    for i in range(N-1):
        for f,t,c in Edge:
            if dist[t]>dist[f]+c and dist[f]!=INF:
                dist[t]=min(dist[t],dist[f]+c)
    for i in range(N):
        for f,t,c in Edge:
            if dist[t]>dist[f]+c and dist[f]!=INF:
                dist[t]=dist[f]+c
                neg[t]=True
            if neg[f]:
                neg[t]=True
    return dist,neg
                
N,M,P=map(int,input().split())
Edge=[]
for i in range(M):
    a,b,c=map(int,input().split())
    Edge.append((a-1,b-1,-(c-P)))
dist,neg=Belman_Ford(0,N,Edge)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)
INF = 10 ** 10

class edge:
    def __init__(self, fr, to, cost): self.fr, self.to, self.cost = fr, to, cost

def input(): return sys.stdin.readline().strip()
def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N, M, P = ZZ()
    es = []
    for _ in range(M):
        a, b, c = ZZ()
        a -= 1
        b -= 1
        es.append(edge(a, b, -(c-P)))

    d = [INF] * N
    d[0] = 0
    for i in range(N-1):
        for e in es:
            if d[e.fr] != INF and d[e.to] > d[e.fr] + e.cost:
                d[e.to] = d[e.fr] + e.cost
    n = [False] * N
    for i in range(N):
        for e in es:
            if d[e.fr] != INF and d[e.to] > d[e.fr] + e.cost:
                d[e.to] = d[e.fr] + e.cost
                n[e.to] = True
            if n[e.fr] == True: n[e.to] = True
    print(-1 if n[N-1] else max(0, -d[N-1]))

    return

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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, N):
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(N):
        for u in range(1, N+1):
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    dist[v] = dist[u] + g[u][v]
    for i in range(N):
        for u in range(1, N+1):
            if dist[u] == INF:
                continue
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if dist[v] != INF:
                        dist[v] = -INF
    return dist


@mt
def slv(N, M, P, ABC):
    g = defaultdict(dict)
    for a, b, c in ABC:
        if a in g and b in g[a]:
            g[a][b] = min(g[a][b], -(c - P))
        else:
            g[a][b] = -(c - P)

    d = BellmanFord(g, 1, N)
    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: Time Limit Exceeded

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))

    # 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)

    # checck cycles
    cycle = set([])
    for start in range(n):
        if start in cycle:
            continue

        b = False
        q = deque([(start, 0)])
        visited = set([start])
        prev = dict()
        prev[start] = None
        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))
                    prev[target] = cur
                if target == start and d - c + p < 0:
                    b = True
                    cycle.add(target)
                    tmp = cur
                    while prev[tmp] != None:
                        cycle.add(tmp)
                        tmp = prev[tmp]
                    break
            if b:
                break

    f = False
    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: Time Limit Exceeded

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

        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: Time Limit Exceeded

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, 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

    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: Time Limit Exceeded

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

def Bellman_Ford2(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:
        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)
min_distance2 = Bellman_Ford2(1,N,M,line)
ans = min_distance[N-1]
ans2 = min_distance2[N-1]

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

Submission status: Time Limit Exceeded

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():
    start = time.time()
    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))

    en = len(e)
    km = sum(map(lambda x: x[2], abc))
    def search(s):
        d = collections.defaultdict(lambda: -inf)
        vc = collections.defaultdict(int)
        q = []
        d[s] = 0
        heapq.heappush(q, (0, s))
        ttt = 0
        while len(q):
            ttt += 1
            if ttt % 1024 == 0:
                if time.time() - start > 1.9:
                    return
            mk, u = heapq.heappop(q)
            k = -mk
            if d[u] > k:
                continue
            if k > km or vc[u] > en:
                return
            vc[u] += 1

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

        return d

    d = search(1)
    if d is None:
        return -1
    return max(0, d[n])

print(main())

Submission status: Time Limit Exceeded

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))

    en = len(e)
    km = sum(map(lambda x: x[2], abc))
    def search(s):
        d = collections.defaultdict(lambda: -inf)
        vc = collections.defaultdict(int)
        q = []
        d[s] = 0
        heapq.heappush(q, (0, s))
        while len(q):
            mk, u = heapq.heappop(q)
            k = -mk
            if d[u] > k:
                continue
            if k > km or vc[u] > en:
                return
            vc[u] += 1

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

        return d

    d = search(1)
    if d is None:
        return -1
    return max(0, d[n])

print(main())

Submission status: Time Limit Exceeded

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))

    km = 10**5 * (n+1)
    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 k > km:
                return
            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

    d = search(1)
    if d is None:
        return -1
    return max(0, d[n])

print(main())

Submission status: Time Limit Exceeded

Solution code:
def bellman_ford(s, n, G, st):
    d = [float('inf')]*n
    d[s] = 0
    for i in range(n):
        update = False
        for x, y, z in G:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if y in st:
                    update = True
        if not update:
            break
        if i == n - 1:
            return None
    return d

def main():
    n, m, p = map(int, input().split())
    G = []
    U = [[] for _ in range(n)]
    dic = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        if (a-1, b-1) in dic:
            if dic[(a-1, b-1)] > -c+p:
                dic[(a-1, b-1)] = -c+p
        else:
            dic[(a-1, b-1)] = -c+p
    for v in dic.keys():
        G.append([v[0], v[1], dic[v]])
        U[v[1]].append(v[0])
    st = set()
    st.add(n-1)
    q = [n-1]
    while len(q) > 0:
        t = q.pop(-1)
        for v in U[t]:
            if not v in st:
                q.append(v)
                st.add(v)
    ans = bellman_ford(0, n, G, st)
    if ans is None:
        print(-1)
    else:
        print(max(0, -ans[n-1]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def bellman_ford(s, n, G, st):
    d = [float('inf')]*n
    d[s] = 0
    for i in range(n):
        update = False
        for x, y, z in G:
            if not y in st:
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
        if not update:
            break
        if i == n - 1:
            return None
    return d

def main():
    n, m, p = map(int, input().split())
    G = []
    U = [[] for _ in range(n)]
    dic = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        if (a-1, b-1) in dic:
            if dic[(a-1, b-1)] > -c+p:
                dic[(a-1, b-1)] = -c+p
        else:
            dic[(a-1, b-1)] = -c+p
    for v in dic.keys():
        G.append([v[0], v[1], dic[v]])
        U[v[1]].append(v[0])
    st = set()
    st.add(n-1)
    q = [n-1]
    while len(q) > 0:
        t = q.pop(-1)
        for v in U[t]:
            if not v in st:
                q.append(v)
                st.add(v)
    ans = bellman_ford(0, n, G, st)
    if ans is None:
        print(-1)
    else:
        print(max(0, -ans[n-1]))

if __name__ == "__main__":
    main()