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:
def main():
    INF = float("inf")

    N, M, P, *ABC = map(int, open(0).read().split())

    F = [[] for _ in range(N)]
    B = [[] for _ in range(N)]
    E = [(a - 1, b - 1, P - c) for a, b, c in zip(*[iter(ABC)] * 3)]

    for a, b, c in E:
        F[a].append(b)
        B[b].append(a)

    S = {0}
    stack = [0]
    while stack:
        s = stack.pop()
        for v in F[s]:
            if v not in S:
                stack.append(v)
                S.add(v)

    T = {N - 1}
    stack = [N - 1]
    while stack:
        s = stack.pop()
        for v in B[s]:
            if v not in T:
                stack.append(v)
                T.add(v)

    ok = S & T

    D = [INF] * N
    D[0] = 0

    def bellman_ford(N):
        for _ in range(N):
            update = False
            for a, b, c in E:
                if a in ok and b in ok and D[b] > D[a] + c:
                    D[b] = D[a] + c
                    update = True
            if not update:
                return False
        return True

    bellman_ford(N)

    print(-1 if bellman_ford(1) else max(-D[-1], 0))



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
INF = float("inf")

N, M, P, *ABC = map(int, open(0).read().split())

F = [[] for _ in range(N)]
B = [[] for _ in range(N)]
E = [(a - 1, b - 1, P - c) for a, b, c in zip(*[iter(ABC)] * 3)]

for a, b, c in E:
    F[a].append(b)
    B[b].append(a)

S = {0}
stack = [0]
while stack:
    s = stack.pop()
    for v in F[s]:
        if v not in S:
            stack.append(v)
            S.add(v)

T = {N - 1}
stack = [N - 1]
while stack:
    s = stack.pop()
    for v in B[s]:
        if v not in T:
            stack.append(v)
            T.add(v)

ok = S & T

D = [INF] * N
D[0] = 0

def bellman_ford(N):
    for _ in range(N):
        update = False
        for a, b, c in E:
            if a in ok and b in ok and D[b] > D[a] + c:
                D[b] = D[a] + c
                update = True
        if not update:
            return False
    return True

bellman_ford(N)

print(-1 if bellman_ford(1) else max(-D[-1], 0))

Submission status: Time Limit Exceeded

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

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

def bellmanford():
    rep = 0
    while rep < n:
        update = False
        for edge in lst:
            a,b,c = edge
            if d[a] != 10**100 and d[b] > d[a]+ c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        rep += 1
    return False if rep != n else True

not_N_reach_list = []
not_1_reach_list = []
for i in range(1, n):
    d = [10**100] * (n+1)
    d[i] = 0
    bellmanford()
    if i == 1:
        for j in range(2, n):
            if d[j] == 10**100:
                not_1_reach_list.append(j)
    else:
        if d[n] == 10**100:
            not_N_reach_list.append(i)
        
exclude_lst = set(not_N_reach_list + not_1_reach_list)

new_lst = []
for edge in lst:
    a, b, c = edge
    if a not in exclude_lst and b not in exclude_lst:
        new_lst.append(edge)
        
lst = new_lst

d = [10**100] * (n+1)
d[1] = 0
a = bellmanford()
if a:
    print(-1)
else:
    print(0) if -d[n] < 0 else print(-d[n])

Submission status: Time Limit Exceeded

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

def main():
    N, M, P = map(int, input().split())
    abc = [list(map(int, input().split())) for i in range(M)]
    INF = int(1e10)
    cost = [INF] * (N + 1)

    cost[1] = 0
    count = 0
    fin = False
    while True:
        no_change = True
        for i in range(M):
            a, b, c = abc[i]
            tmp = cost[a] - (c - P)
            if cost[b] > tmp:
                cost[b] = tmp
                no_change = False
        count += 1
        if no_change:
            fin = True
            break
        
        if count == N:
            pre = cost[N]
        elif count > 2 * N:
            break
        elif count > N:
            if pre != cost[N]:
                break
    
    if fin:
        print(max(0, -cost[N]))
    else:
        if pre != cost[N]:
            print(-1)
        else:
            print(max(0, -cost[N]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    N, M, P = map(int, input().split())
    abc = [list(map(int, input().split())) for i in range(M)]
    INF = int(1e10)
    cost = [INF] * (N + 1)

    cost[1] = 0
    count = 0
    fin = False
    while True:
        no_change = True
        for i in range(M):
            a, b, c = abc[i]
            tmp = cost[a] - (c - P)
            if cost[b] > tmp:
                cost[b] = tmp
                no_change = False
        count += 1
        if no_change:
            fin = True
            break
        if count > 2 * N:
            break
        elif count > N:
            pre = cost[N]
    
    if fin:
        print(max(0, -cost[N]))
    else:
        if pre != cost[N]:
            print(-1)
        else:
            print(max(0, -cost[N]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

def main():
    N, M, P = mis()
    
    to = [[] for _ in range(N)]
    ot = [[] for _ in range(N)]
    edges = []

    for i in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        c = -(c-P)
        #
        to[a].append(b)
        ot[b].append(a)
        edges.append((a,b,c))

    reachableFrom0 = set()
    reachableToN = set()

    # dfs
    reachableFrom0.add(0)
    nodes = [0]
    while nodes:
        node = nodes.pop()
        for i in to[node]:
            if i not in reachableFrom0:
                nodes.append(i)
                reachableFrom0.add(i)

    #rdfs
    reachableToN.add(N-1)
    nodes = [N-1]
    while nodes:
        node = nodes.pop()
        for i in ot[node]:
            if i not in reachableToN:
                nodes.append(i)
                reachableToN.add(i)


    ok = reachableFrom0 & reachableToN

    edges = tuple((a, b, c) for a, b, c in edges if a in ok and b in ok)

    V = [float('inf')] * N
    V[0] = 0

    def bf(n):
        for _ in range(n):
            for a, b, c in edges:
                V[b] = min(V[b], V[a] + c)

    bf(N)

    Vb = tuple(V)
    bf(1)

    if tuple(V) == Vb:
        print(max(-V[-1], 0))
    else:
        print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)

def main():
    ii = lambda: int(input())
    mis = lambda: map(int, input().split())
    lmis = lambda: list(mis())

    N, M, P = mis()

    to = [[] for _ in range(N)]
    ot = [[] for _ in range(N)]
    edges = []

    for i in range(M):
        a,b,c = mis()
        a -= 1
        b -= 1
        c = -(c-P)
        #
        to[a].append(b)
        ot[b].append(a)
        edges.append((a,b,c))

    reachableFrom0 = set()
    reachableToN = set()

    # dfs
    reachableFrom0.add(0)
    nodes = [0]
    while nodes:
        node = nodes.pop()
        for i in to[node]:
            if i not in reachableFrom0:
                nodes.append(i)
                reachableFrom0.add(i)

    #rdfs
    reachableToN.add(N-1)
    nodes = [N-1]
    while nodes:
        node = nodes.pop()
        for i in ot[node]:
            if i not in reachableToN:
                nodes.append(i)
                reachableToN.add(i)


    ok = reachableFrom0 & reachableToN

    edges = [(a, b, c) for a, b, c in edges if a in ok and b in ok]

    V = [float('inf')] * N
    V[0] = 0

    def bf_step():
        for a, b, c in edges:
            V[b] = min(V[b], V[a] + c)

    def bf():
        for _ in range(N):
            bf_step()

    bf()

    Vb = tuple(V)
    bf_step()

    if tuple(V) == Vb:
        print(max(-V[-1], 0))
    else:
        print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)

ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

N, M, P = mis()

to = [[] for _ in range(N)]
ot = [[] for _ in range(N)]
edges = []

for i in range(M):
    a,b,c = mis()
    a -= 1
    b -= 1
    c = -(c-P)
    #
    to[a].append(b)
    ot[b].append(a)
    edges.append((a,b,c))

reachableFrom0 = set()
reachableToN = set()

# dfs
reachableFrom0.add(0)
nodes = [0]
while nodes:
    node = nodes.pop()
    for i in to[node]:
        if i not in reachableFrom0:
            nodes.append(i)
            reachableFrom0.add(i)

#rdfs
reachableToN.add(N-1)
nodes = [N-1]
while nodes:
    node = nodes.pop()
    for i in ot[node]:
        if i not in reachableToN:
            nodes.append(i)
            reachableToN.add(i)


ok = reachableFrom0 & reachableToN

edges = [(a, b, c) for a, b, c in edges if a in ok and b in ok]

V = [float('inf')] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)

ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

N, M, P = mis()

to = [[] for _ in range(N)]
ot = [[] for _ in range(N)]
edges = []

for i in range(M):
    a,b,c = mis()
    a -= 1
    b -= 1
    c = -(c-P)
    #
    to[a].append(b)
    ot[b].append(a)
    edges.append((a,b,c))

reachableFrom0 = [False] * N
reachableToN = [False] * N

def dfs(n):
    reachableFrom0[0] = True
    nodes = [n]
    while nodes:
        node = nodes.pop()
        for i in to[node]:
            if not reachableFrom0[i]:
                nodes.append(i)
                reachableFrom0[i] = True


def rdfs(n):
    reachableToN[n] = True
    nodes = [n]
    while nodes:
        node = nodes.pop()
        for i in ot[node]:
            if not reachableToN[i]:
                nodes.append(i)
                reachableToN[i] = True

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]

edges = [(a, b, c) for a, b, c in edges if ok[a] and ok[b]]

V = [float('inf')] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)

ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())

N, M, P = mis()

to = [[] for _ in range(N)]
ot = [[] for _ in range(N)]
edges = []

for i in range(M):
    a,b,c = mis()
    a -= 1
    b -= 1
    c = -(c-P)
    #
    to[a].append(b)
    ot[b].append(a)
    edges.append((a,b,c))

reachableFrom0 = [False] * N
reachableToN = [False] * N

def dfs(n):
    if reachableFrom0[n]:
        return
    reachableFrom0[n] = True
    for i in to[n]:
        dfs(i)

def rdfs(n):
    if reachableToN[n]:
        return
    reachableToN[n] = True
    for i in ot[n]:
        rdfs(i)

dfs(0)
rdfs(N-1)

ok = [a and b for a, b in zip(reachableFrom0, reachableToN)]

edges = [(a, b, c) for a, b, c in edges if ok[a] and ok[b]]

V = [float('inf')] * N
V[0] = 0

def bf_step():
    for a, b, c in edges:
        V[b] = min(V[b], V[a] + c)

def bf():
    for _ in range(N):
        bf_step()

bf()

Vb = tuple(V)
bf_step()

if tuple(V) == Vb:
    print(max(-V[-1], 0))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
n,m,p = map(int, input().split())
edge = []
e1 = [list() for _ in range(n+1)]
for _ in range(m):
  a,b,c = map(int, input().split())
  edge.append((a,b,p-c))
  e1[a].append(b)
dis = [float("inf")]*(n+1)
dis[1] = 0
t = []
for i in range(n):
  for a,b,c in edge:
    if dis[b] > dis[a] + c:
      dis[b] = dis[a] + c
      if i == n-1:
        t.append(b)
s = set(t)
while t:
  v = t.pop()
  for x in e1[v]:
    if x == n:
      print(-1)
      exit(0)
    if x in s:
      continue
    s.add(x)
    t.append(x)
print(max(0,-dis[n]))

Submission status: Time Limit Exceeded

Solution code:
n,m,p = map(int, input().split())
edge = []
for _ in range(m):
  a,b,c = map(int, input().split())
  edge.append((a,b,p-c))
dis = [float("inf")]*(n+1)
dis[1] = 0
for i in range(n-1):
  for a,b,c in edge:
    if dis[b] > dis[a] + c:
      dis[b] = dis[a] + c
ant1 = max(-dis[n],0)
for i in range(n):
  for a,b,c in edge:
    if dis[b] > dis[a] + c:
      dis[b] = dis[a] + c
ant2 = max(-dis[n],0)
if ant1 != ant2:
  print(-1)
else:
  print(ant1)

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10000000)

N,M,P=map(int,input().split())
INF = 1000000000
edge = []
to = [[] for _ in range(N)]
rto = [[] for _ in range(N)]
reachable_from1 = [False]*N
reachable_fromN = [False]*N
for i in range(M):
    a,b,c = map(int,input().split())
    a-=1
    b-=1
    c=-c
    to[a].append(b)
    rto[b].append(a)
    edge.append([a,b,c])

def dfs(v):
    if reachable_from1[v] == True:
        return
    reachable_from1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    if reachable_fromN[v] == True:
        return
    reachable_fromN[v] = True
    for u in rto[v]:
        rdfs(u)

dfs(0)
rdfs(N-1)
ok = [False]*N
for i in range(N):
    ok[i] = reachable_from1[i]&reachable_fromN[i]

d = [INF]*N
d[0] = 0
update = True
step=0
while update:
    update = False
    for i in range(M):
        a,b,c=edge[i]
        if not(ok[a]): continue
        newD = d[a]+c+P
        if newD < d[b]:
            d[b] = newD
            update = True
    step+=1
    if step > N:
        print(-1)
        sys.exit()
print(max(0,-d[N-1]))

Submission status: Time Limit Exceeded

Solution code:
n,m,p = map(int, input().split())
edge = []
ren = [set([i]) for i in range(n+1)]
for _ in range(m):
  a,b,c = map(int, input().split())
  edge.append((a,b,p-c))
dis = [float("inf")]*(n+1)
dis[1] = 0
t = []
for i in range(n):
  for a,b,c in edge:
    ren[b] |= ren[a]
    if dis[b] > dis[a] + c:
      dis[b] = dis[a] + c
      if i == n-1:
        t.append(b)
for v in t:
  if v in ren[n]:
    print(-1)
    break
else:
  print(max(0,-dis[n]))

Submission status: Time Limit Exceeded

Solution code:
#57 ABC137E
#ベルマンフォード

n,m,p=map(int,input().split())

abc=[list(map(int,input().split())) for _ in range(m)]
abc=[[a,b,p-c] for a,b,c in abc]
def BF(edges,num_v,source):
    #グラフの初期化
    inf=float("inf")
    dist=[inf for i in range(num_v)]
    dist[source-1]=0
  
    #辺の緩和
    neg=[False for _ in range(num_v)]
    for i in range(num_v-1):
        for edge in edges:
            if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
                dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
    for i in range(num_v):
        for edge in edges:
            if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
                dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
                neg[edge[1]-1]=True
            if neg[edge[0]-1]==True:
                neg[edge[1]-1]=True
    return dist,neg
dis,neg=BF(abc,n,1)
print(-1 if neg[-1] else max(0,-dis[-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys


def solve(n, links, parents, costs):
    q = [n - 1]
    reachable = set()
    while q:
        v = q.pop()
        if v in reachable:
            continue
        reachable.add(v)
        q.extend(u for u in parents[v] if u not in reachable)

    for v in reachable:
        links[v] &= reachable

    INF = 10 ** 12
    dist = [INF] * n
    dist[0] = 0
    for _ in range(len(reachable)):
        updated = False
        for v in reachable:
            d = dist[v]
            if d == INF:
                continue
            cv = costs[v]
            for u in links[v]:
                if dist[u] > d + cv[u]:
                    dist[u] = d + cv[u]
                    updated = True
        if not updated:
            break
    else:
        return -1

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


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

print(solve(n, links, parents, costs))

Submission status: Time Limit Exceeded

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

edges = []
for _ in range(N):
    a,b,c = map(int, input().split())
    edges.append((a,b,c))

neg_inf = float("-Inf")
no_answer = False

start = 1
end = M

distance = {}
distance[start] = 0
previous = {}

for i in range(M-1):
    for f,t,w in edges:
        if distance.get(f,neg_inf) + w - P > distance.get(t,neg_inf):
            distance[t] = distance[f] + w - P
            previous[t] = f

path = []
node = end
if node in previous:
    while node != start:
        path.append(node)
        node = previous[node]
        if len(path) > M:
            no_answer = True
            break
    path.append(start)

for f,t,w in edges:
    if distance.get(f,neg_inf) + w - P > distance.get(t,neg_inf) and t in path:
        no_answer = True
        break

if no_answer:
    print(-1)
else:
    print(max(0,distance[end]))

Submission status: Time Limit Exceeded

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')

#edgeは1次元ですべて(始点,終点,重み)を格納
def bellmanford(edge,N):
    costs = [inf] * N
    costs[0] = 0
    exist_minus_cycle = False
    for i in range(N):
        update = False
        for from_, to, cost in edge:
            cost_to = costs[from_] + cost
            if cost_to < costs[to]:
                update = True
                costs[to] = cost_to
                
        if not update:
            break
        elif i==N-1:
            exist_minus_cycle = True

    #どこで無限に更新されるか判定
    minus_cycle = set()
    if exist_minus_cycle:
        for i in range(N+1):
            for from_, to, cost in edge:
                cost_to = costs[from_] + cost
                if from_ in minus_cycle:
                    minus_cycle.add(to)
                if cost_to < costs[to]:
                    minus_cycle.add(from_)
                    minus_cycle.add(to)
                    costs[to] = cost_to
    return costs, minus_cycle


def main():
    N,M,P = MI()
    edges = []
    for _ in range(M):
        A,B,C = MI_()
        cost = P - (C+1)
        edges.append((A,B,cost))

    
    costs,minus_cycle = bellmanford(edges,N)

    if N-1 in minus_cycle :
        print(-1)
    else:
        print(max(0,-costs[-1]))



if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
class BellmanFord():
    def __init__(self, N):
        self.N = N
        self.edges = []
        self.to = [[] for _ in [0]*self.N]
        self.rev = [[] for _ in range(self.N)]

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges.append([u, v, d])
            self.edges.append([v, u, d])
            self.to[u].append(v)
            self.rev[v].append(u)
        else:
            self.edges.append([u, v, d])
            self.to[u].append(v)
            self.rev[v].append(u)

    def BellmanFord_search(self, s):
        """
        :param s: 始点
        :return: d[i] 始点sから各点iまでの最短経路
        """
        d = [float('inf') for i in range(self.N)]
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def check_reachable(self, start, to=True):
        if to:
            edges = self.to
        else:
            edges = self.rev
        visited = [0 for _ in range(self.N)]
        visited[start] = 1
        reachable = set()
        dq = deque([start])
        popleft, append = dq.popleft, dq.append

        while dq:
            current = popleft()
            reachable.add(current)
            for dest in edges[current]:
                if not visited[dest]:
                    visited[dest] = 1
                    append(dest)

        return reachable

    def BellmanFord_negative_bool(self, start, numNodes):
        # 負の閉路の検出, Trueなら負の閉路が存在する
        d = [float('inf') for _ in range(self.N)]
        d[start] = 0
        numEdges = len(self.edges)
        for i in range(numNodes):
            for j in range(numEdges):
                e = self.edges[j]
                if d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    if i == numNodes-1:
                        return True, d
        return False, d


N, M, P = map(int, input().split())
graph = BellmanFord(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, -(c-P), True)

v_set = graph.check_reachable(0) & graph.check_reachable(N-1, False)
graph.edges = [edge for edge in graph.edges if edge[0] in v_set and edge[1] in v_set]
hasNegatibeCycle, dists = graph.BellmanFord_negative_bool(0, N)
if hasNegatibeCycle:
    print(-1)
else:
    print(max(0, -dists[-1]))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def bellman_ford(start: int, goal: int, graph: list) -> list:
    '''bellman-ford法: 始点startから終点goalへの最小コストを求める
    重み付きグラフgraphは隣接リストで与えられる
    辺のコストは負でも良い
    計算量: O(|E||V|)
    '''
    INF = float("inf")
    n = len(graph)

    # スタートからゴールに到着可能かどうか判定する
    is_reachable = [False] * n
    is_reachable[start] = True
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, _ in graph[pos]:
            if is_reachable[next_pos]:
                continue
            is_reachable[next_pos] = True
            q.append(next_pos)

    # 逆辺で構築したグラフでゴールからスタートに到着可能かどうか判定する
    reverse_graph = [[] for i in range(n)]
    for pos, edge in enumerate(graph):
        for next_pos, cost in edge:
            reverse_graph[next_pos].append((pos, cost))
    is_rev_reachable = [False] * n
    is_rev_reachable[goal] = True
    q = deque([goal])
    while q:
        pos = q.popleft()
        for next_pos, _ in reverse_graph[pos]:
            if is_rev_reachable[next_pos]:
                continue
            is_rev_reachable[next_pos] = True
            q.append(next_pos)            

    need = [False] * n
    for i in range(n):
        need[i] = is_reachable[i] and is_rev_reachable[i]

    distance = [INF] * n
    distance[start] = 0
    for _ in range(n):
        is_updated = False
        for pos, edge in enumerate(graph):
            for next_pos, cost in edge:
                if not need[pos]:
                    continue
                if distance[pos] != INF and distance[pos] + cost < distance[next_pos]:
                    distance[next_pos] = distance[pos] + cost
                    is_updated = True
        if not is_updated:
            return distance
    # 負閉路が存在する
    return [-INF]


n, m, p = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
for i in range(m):
    a, b, c = info[i]
    graph[a - 1].append((b - 1, -(c - p)))
ans = bellman_ford(0, n-1, graph)[-1]
if ans == -float("inf"):
    print(-1)
else:
    print(max(-ans, 0))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

def find_negative_loop(s,n,w,es):
  # s: start
  # n: number of nodes
  # w: number of edges
  # es[i]: from, to, cost
  
  # d: shortest dist of s -> i
  d = [float('inf')]*n
  d[s] = 0
  for i in range(2*n):
    for j in range(w):
      p, q, r = es[j]
      if d[p] != float('inf') and (d[q] > d[p] + r):
        d[q] = d[p] + r
        if i >= n:
          d[q] = -float('inf')
    if i == n-1:
      temp = d[-1]
  return temp, d[-1]
         

n, w, p = map(int, input().split())
es = []
for i in range(w):
  x, y, z = map(int, input().split())
  es.append([x-1, y-1, (z-p)*(-1)])
  
temp, d = find_negative_loop(0, n, w ,es)
if temp == d:
  print(min(0, d)*(-1))
else:
  print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

def find_negative_loop(s,n,w,es):
  # s: start
  # n: number of nodes
  # w: number of edges
  # es[i]: from, to, cost
  
  # d: shortest dist of s -> i
  d = [float('inf')]*n
  d[s] = 0
  for i in range(2*n):
    for j in range(w):
      p, q, r = es[j]
      if d[p] != float('inf') and (d[q] > d[p] + r):
        d[q] = d[p] + r
        if i >= n:
          d[q] = -float('inf')
      if i == n-1:
        temp = d[-1]
  return temp, d[-1]
         

n, w, p = map(int, input().split())
es = []
for i in range(w):
  x, y, z = map(int, input().split())
  es.append([x-1, y-1, (z-p)*(-1)])
  
temp, d = find_negative_loop(0, n, w ,es)
if temp == d:
  print(min(0, d)*(-1))
else:
  print('-1')

Submission status: Time Limit Exceeded

Solution code:
def find_negative_loop(s,n,w,es):
  # s: start
  # n: number of nodes
  # w: number of edges
  # es[i]: from, to, cost
  
  # d: shortest dist of s -> i
  d = [float('inf')]*n
  d[s] = 0
  for i in range(2*n):
    for j in range(w):
      p, q, r = es[j]
      if d[p] != float('inf') and (d[q] > d[p] + r):
        d[q] = d[p] + r
        if i >= n:
          d[q] = -float('inf')
      if i == n-1:
        temp = d[-1]
  return temp, d[-1]
         

n, w, p = map(int, input().split())
es = []
for i in range(w):
  x, y, z = map(int, input().split())
  x, y = x-1, y-1
  z = (z-p)*(-1)
  es.append([x, y, z])
  
temp, d = find_negative_loop(0, n, w ,es)
if temp == d:
  print(min(0, d)*(-1))
else:
  print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys


def input():
    return sys.stdin.readline()[:-1]


n, m, p = map(int, input().split())
edge0 = []
d = [[] for i in range(n)]
r = [[] for i in range(n)]
for i in range(m):
    ai, bi, ci = map(int, input().split())
    edge0.append((bi-1,ai-1,-ci+p))
    d[ai-1] += [bi-1]
    r[bi-1] += [ai-1]

p0 = [False for i in range(n)]
p0[0] = True
from collections import deque
q = deque([0])
while len(q)>0:
    x = q.popleft()
    for y in d[x]:
        if not p0[y]:
            p0[y] = True
            q.append(y)
pn = [False for i in range(n)]
pn[n-1] = True
q = deque([n-1])
while len(q) > 0:
    x = q.popleft()
    for y in r[x]:
        if not pn[y] and p0[y]:
            pn[y] = True
            q.append(y)

edge = []
for e in edge0:
    if pn[e[1]] and pn[e[0]]:
        edge += [e]


dist = [float("inf") for i in range(n)]
dist[n-1] = 0
h = False
for i in range(n):
    updated = False
    for e in edge:
        if dist[e[1]] > dist[e[0]] + e[2] and p0[e[1]] and p0[e[0]]:
            dist[e[1]] = dist[e[0]] + e[2]
            updated = True
    if not updated:
        break
else:
    h = True

if h:
    print(-1)
else:
    print(max(0, -dist[0]))