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: Wrong Answer

Solution code:
#単一始点最短経路問題
#負の辺があっても動作する

#最短経路を求める
#計算量O(N * M)

INF = 10 ** 9
#入力
# N = int(input()) #頂点の数
# M = int(input()) #辺の数
N, M, P = map(int, input().split())

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    l, r, s = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[l-1, r-1, -(s-P)]] #有向グラフのときはここだけ
    # G += [[r-1, l-1, s]] #無向グラフのときはこの行も必要


#メイン文
d = [0] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                prev[e[1]] = e[0]
        if not update: #更新が終わったとき
            return True
        if count == N - 1: #永遠に更新が起きているとき
            tmp = d[N -1]
        if count == N:
            if d[N - 1] == tmp:
                return True
            else:
                return False

#呼び出しスタート地点を入れる
if not shortest_path(1):
    print (-1)
    exit()
# print (d)

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

Submission status: Wrong Answer

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

Edgeinv = [[] for _ in range(N+1)]
inf = 2*10**9
Edgenum = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
for a, b, c in Edgenum:
    Edgeinv[b].append(a)

used = set([N])
stack = [N]
while stack:
    vn = stack.pop()
    for vf in Edgeinv[vn]:
        if vf not in used:
            used.add(vf)
            stack.append(vf)

dp = [-inf]*(N+1)
dp[1] = 0
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp = [max(0, d) for d in dp]
for i in range(N):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp2 = [max(0, d) for d in dp]
if any(Dp[i] < Dp2[i] for i in used):
    print(-1)
else:
    print(Dp[N])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 0))
G_rev = defaultdict(lambda: defaultdict(lambda: 0))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = C
    G_rev[B][A] = 1

reachable = [0] * (N + 1)
reachable[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable[q] == 0:
            reachable[q] = 1
            queue.append(q)

# print(reachable)

max_score = [-1000000000] * (N + 1)
res = 0
max_score[1] = 0
queue = deque([1])
cnt = 0
while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if not reachable[q]:
            continue
        if max_score[p] + G[p][q] - 10 > max_score[q]:
            max_score[q] = max_score[p] + G[p][q] - 10
            queue.append(q)
            cnt += 1
    if cnt > 1000000:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, max_score[N]))

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    a,b = LI()
    print(max(a+b,a-b,a*b))
    return

#B
def B():
    k,x = LI()
    ans = []
    for i in range(x-k+1,x+k):
        ans.append(i)
    print(*ans)
    return

#C
def C():
    def f(s):
        res = [0]*m
        for i in s:
            res[alp.index(i)] += 1
        return res
    alp = list("abcdefghijklmnopqrstuvwxyz")
    m = len(alp)
    n = I()
    s = [input() for i in range(n)]
    d = defaultdict(lambda : 0)
    for i in s:
        d[tuple(f(i))] += 1
    ans = 0
    for i in d.values():
        ans += (i*(i-1))//2
    print(ans)
    return

#D
def D():
    n,m = LI()
    g = LIR(n)
    g.sort(key = lambda x:x[0])
    ans = 0
    f = [1]*n
    j = 0
    q = []
    for i in range(m)[::-1]:
        while j < n and m-g[j][0] >= i:
            a,b = g[j]
            heappush(q,(-b,a))
            j += 1
        if q:
            x,a = heappop(q)
            if i+a <= m:
                ans -= x
    print(ans)
    return

#E
def E():
    def dfs(x,f):
        for y,w in v[x]:
            if f[y]:
                f[y] = 0
                dp[y] = dp[x]+w
                dfs(y,f)
                f[y] = 1
            else:
                if dp[y] < dp[x]+w:
                    dp[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        v[a].append((b,c-p))
    f = [1]*n
    dp = [-float("inf")]*n
    dp[0] = 0
    f[0] = 0
    dfs(0,f)
    ans = dp[n-1]
    if ans == float("inf"):
        print(-1)
    elif ans < 0:
        print(0)
    else:
        print(ans)
    return

#F
def F():

    return

#Solve
if __name__ == "__main__":
    E()

Submission status: Wrong Answer

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

Edgeinv = [[] for _ in range(N+1)]
inf = 2*10**9
Edgenum = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
for a, b, c in Edgenum:
    Edgeinv[b].append(a)

used = set([N])
stack = [N]
while stack:
    vn = stack.pop()
    for vf in Edgeinv[vn]:
        if vf not in used:
            used.add(vf)
            stack.append(vf)

dp = [-inf]*(N+1)
dp[1] = 0
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp = dp[:]
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp2 = dp[:]
if any(Dp[i] < Dp2[i] and Dp2[i] > 0 for i in used):
    print(-1)
else:
    print(max(0, dp[N]))

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


n, m, p = li()

# グラフを作る
graph = [[] for _ in range(n)]
for _ in range(m):
    ai, bi, ci = li()
    ai -= 1
    bi -= 1
    graph[bi].append((ai, ci - p))

# ベルマンフォード
INF = float('inf')
dist = [[-INF]*n for _ in range(n+2)]
dist[0][0] = 0
for i in range(n+1):
    for j in range(n):
        dist[i+1][j] = dist[i][j]
        for (k, cost) in graph[j]:
            if dist[i][k] != -INF:
                dist[i+1][j] = max(dist[i+1][j],  dist[i][k] + cost)


# n回目の遷移とn+1回目の遷移で差があるとNG
if dist[n][n-1] < dist[n+1][n-1]:
    print(-1)
else:
    print(max(0, dist[n+1][n-1]))

Submission status: Wrong Answer

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

def BellmanFord(edges,num_v,start):
    inf=float('inf')
    dist=[inf for _ in range(num_v)] #グラフの初期化
    dist[start]=0
    #辺の和
    for i in range(num_v):
        for edge in edges: #edge: [始点,終点,コスト]
            if dist[edge[0]]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                dist[edge[1]]=dist[edge[0]]+edge[2]
                #負閉経路かつそれがゴールを通るものがある
                #i==num_v-1だけだと、負閉経路の検出だけになる
                if i==num_v-1 and edge[1]==num_v-1:
                    return -1
    return dist

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    c-=p
    Edges.append((a,b,-c))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
inf = float('inf')
V,E,P = map(int,input().split())
edge = []
for i in range(E):
    A,B,C = map(int,input().split())
    edge.append([A-1,B-1,P-C])

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break
ans = d[V-1]
for j in range(E):
    From,To,cost = edge[j]
    if d[From] != inf and d[To]>d[From]+cost:
        d[To]=d[From]+cost
loop = ans != d[V-1]

if loop:
    print(-1)

else:
    ans = -d[-1]
    print(max(0,ans))

Submission status: Wrong Answer

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

for i in range(M):
    A, B, C = map(int, input().split())
    edge.append((A, B, P-C))

inf = float('inf')
cost = [inf] * (N+1)
cost[1] = 0
for i in range(N-1):
    for e in edge:
        a, b, c = e
        if cost[a] + c < cost[b]:
            cost[b] = cost[a] + c

for e in edge:
    a, b, c = e
    if cost[a] + c < cost[b] and b == N:
        print(-1)
        exit()
        
print(max(-cost[N], 0))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
A, B, C = (
    zip(*(map(int, input().split()) for _ in range(M))) if M else
    ((), ())
)

G = [{} for _ in range(N + 1)]
for x, y, w in zip(A, B, C):
    G[x][y] = -(w - P)
INF = 10**20


def bellman_ford(G, s):
    dp = [INF for _ in range(len(G))]
    dp[s] = 0
    for k in range(2 * len(G)):
        for i in range(len(G)):
            for j, w in G[i].items():
                if dp[i] != INF and dp[j] > dp[i] + w:
                    dp[j] = dp[i] + w
                    if k >= N - 1:
                        dp[j] = -INF
    return dp


dp = bellman_ford(G, 1)
ans = max(0, -dp[N])
if ans == INF:
    ans = -1
print(ans)

Submission status: Wrong Answer

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

N,M,P=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(M)]

for i in range(M):
    EDGE[i][2]-=P

ELIST=[[] for i in range(N+1)]

for a,b,p in EDGE:
    ELIST[a].append([b,p])


from collections import deque


Q=deque([1])

ANS=[-float("inf")]*(N+1)
ANS[1]=0
count=0

while Q:
    x=Q.pop()
    count+=1

    for to,p in ELIST[x]:
        if ANS[to]<ANS[x]+p:
            if count>7*10**6:
                ANS[to]=float("inf")
            else:
                ANS[to]=ANS[x]+p
                Q.appendleft(to)

if ANS[N]==float("inf"):
    print(-1)
else:
    print(max(ANS[N],0))

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


n, m, p = li()

# グラフを作る
graph = [[] for _ in range(n)]
for _ in range(m):
    ai, bi, ci = li()
    ai -= 1
    bi -= 1
    graph[bi].append((ai, ci - p))

# ベルマンフォード
INF = float('inf')
dist = [[-INF]*n for _ in range(n+2)]
dist[0][0] = 0
for i in range(n+1):
    for j in range(n):
        dist[i+1][j] = dist[i][j]
        for (k, cost) in graph[j]:
            if dist[i][k] != -INF:
                dist[i+1][j] = max(dist[i+1][j],  dist[i][k] + cost)


# n回目の遷移とn+1回目の遷移で差があるとNG
if dist[n][n-1] != dist[n+1][n-1]:
    print(-1)
else:
    print(max(0, dist[n+1][n-1]))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
g = [[] for _ in range(N+1)]
data = [list(map(int, input().split())) for i in range(M)]

INF = 2 ** 63 - 1
d = [(-1)*INF for i in range(N+1)]
d[1] = 0
for i in range(N):
    d_N = d[N]
    for j in range(M):
        a = data[j][0]
        b = data[j][1]
        c = data[j][2]
        d[b] = max(d[b], d[a]+c-P)
    if i == N-1:
        if d_N != d[N]:
            ans = -1
        else:
            ans = d[N]

if ans == -1:
    print(-1)
else:
    print(max(0, ans))

Submission status: Wrong Answer

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

inf = float('inf')

def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    dist = [inf] * N
    dist[0] = 0
    loop = [False] * N

    for count in range(N):
        for u, v, c in zip(A, B, C):
            if dist[u] + c < dist[v]:
                dist[v] = dist[u] + c
                if count == v-1:
                    loop[v] = True
    
    if loop[N-1]:
        print(-1)
        return
    print(max(-dist[N-1], 0))
    return


# 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))-1
        B[i] = int(next(tokens))-1
        C[i] = -(int(next(tokens))-P)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
g = [[] for _ in range(N+1)]
data = [list(map(int, input().split())) for i in range(M)]

INF = 2 ** 63 - 1
d = [(-1)*INF for i in range(N+1)]
d[1] = 0
for i in range(N):
    d_N = d[N]
    for j in range(M):
        a = data[j][0]
        b = data[j][1]
        c = data[j][2]
        d[b] = max(d[b], d[a]+c-P)
    if i == N-1:
        if d_N != d[N]:
            ans = -1
        else:
            ans = d[N]

print(max(ans,0))

Submission status: Wrong Answer

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

N,M,P=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(M)]

for i in range(M):
    EDGE[i][2]-=P

ELIST=[[] for i in range(N+1)]

for a,b,p in EDGE:
    ELIST[a].append([b,p])


from collections import deque

Q=deque([1])

ANS=[0]*(N+1)
count=0

while Q:
    x=Q.pop()
    count+=1

    for to,p in ELIST[x]:
        if ANS[to]<ANS[x]+p:
            if count>10**7:
                ANS[to]=float("inf")
            else:
                ANS[to]=ANS[x]+p
                Q.appendleft(to)

if ANS[N]==float("inf"):
    print(-1)
else:
    print(ANS[N])

Submission status: Wrong Answer

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

inf = float('inf')

def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    dist = [inf] * N
    dist[0] = 0
    loop = [False] * N

    for count in range(N):
        for u, v, c in zip(A, B, C):
            if dist[u] + c < dist[v]:
                dist[v] = dist[u] + c
                if count == v-1:
                    loop[v] = True
    
    if loop[N-1]:
        print(-1)
        return
    print(max(-dist[N-1], 0))
    return


# 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))-1
        B[i] = int(next(tokens))-1
        C[i] = -(int(next(tokens))-10)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
edges = []
for i in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, P - C])


def BellmanFord(edges, num_v, source):
    # グラフの初期化
    inf = float("inf")
    dist = [inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    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]
                if i == num_v - 1:
                    dist.append(-1)
                    return dist

    return dist


ans = BellmanFord(edges, N, 1)
if ans[N-1] >= 0:
    print(0)
elif len(ans) != N:
    print(-1)
else:
    print(ans[-1] * (-1))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int, input().split())
G = [[] for i in range(n)]
for i in range(m):
    a,b,c = map(int, input().split())
    a,b = a-1, b-1
    G[a].append((b, p-c))


INF = 10**18
dist = [INF] * n
dist[0] = 0
for i in range(n+1):
    for v, e in enumerate(G):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                # 頂点Nに向かう辺に負閉路があったとき
                if i == n and t == n-1:
                    print(-1)
                    exit()
print(max(0, -dist[-1]))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m, p = map(int, input().split())
graph = [[] for _ in range(n+1)]
edge = []
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append((b, c))
    edge.append((a, b, -c+p))

q = deque([])
coins = [0] * (n+1)
ban = [False] * (n+1)

for i in range(1, n+1):
    q.append(i)
    time = [-1] * (n + 1)
    time[i] = 0
    while q:
        now = q.pop()
        for node, coin in graph[now]:
            if time[node] != -1:
                continue
            time[node] = time[now] + 1
            q.append(node)
    if i != 1:
        if time[n] == -1:
            ban[i] = True
    else:
        for j in range(2, n+1):
            if time[j] == -1:
                ban[j] = True


def bellman_ford(v, e_list, start, end):
    inf = 10**9
    dist = [inf] * (v+1)
    dist[start] = 0
    for j in range(v):
        for e in e_list:
            if ban[e[1]]:
                continue
            if dist[e[1]] > e[2] + dist[e[0]]:
                dist[e[1]] = e[2] + dist[e[0]]
                if j == v-1:
                    return -1, 0
    return dist[end], 1


ans, st = bellman_ford(n, edge, 1, n)
if st:
    print(max(-ans, 0))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces
 
n, m, p = na()
 
def bf(es, n, start):
    d = [999999999999] * n
    d[start] = 0
 
    for r in range(n-1):
        updated = False
        for e in es:
            if d[e[0]] == 999999999999:
                continue
            if d[e[0]] + e[2] < d[e[1]]:
                d[e[1]] = d[e[0]] + e[2]
                updated = True
        if not updated:
            break
 
    for e in es:
        if d[e[0]] < 999999999999 and d[e[0]] + e[2] < d[e[1]]:
            return None
 
    return d
 
es = []
for i in range(m):
    a, b, c = na()
    es.append((a-1, b-1, -(c-p)))
 
import collections
q = collections.deque()
q.append(n-1)
 
valid = [False] * n
valid[n-1] = True
while len(q) > 0:
    cur = q.popleft()
    for e in es:
        if e[1] == cur and not valid[e[0]]:
            valid[e[0]] = True
            q.append(e[0])
 
nes = []
for e in es:
    if valid[e[0]] and valid[e[1]]:
        nes.append(e)
es = nes
 
d = bf(es, n, 0)
if not d:
    print(-1)
else:
    print(max(0, -d[n-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
N,M,P = map(int, input().split())
ABC = []
Adake = [[] for _ in range(N)]
Bdake = [[] for _ in range(N)]
for _ in range(M):
    A,B,C = map(int, input().split())
    ABC.append((A-1,B-1,C-P))
    Adake[A-1].append(B-1)
    Bdake[B-1].append(A-1)
    
def dfs(x,s):
    used = {s}
    search = deque([s])
    while search:
        ss = search.pop()
        for sss in x[ss]:
            if sss in used:
                continue
            used.add(sss)
            search.append(sss)
    return used

U = dfs(Adake,0) & dfs(Bdake,N-1)
ABC = [(a,b,c) for (a,b,c) in ABC if a in U and b in U]

dist = [-float("inf")]*N
dist[0]=0
    
for i in range(N):
    ju = True
    for a,b,c in ABC:
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            ju = False
    if ju:
        print(max(0,dist[-1]))
        sys.exit()
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M,P = map(int,input().split())
INF = 10**18
edge = []
rev_edge = [[] for _ in range(N+1)]
dis = [INF]*(N+1)
dis[1] = 0
for i in range(M):
    A,B,C = map(int,input().split())
    edge.append((A,B,P-C))
    rev_edge[B].append(A)
d = deque()
can_arrive = set()
d.append(N)
while d:
    x = d.popleft()
    can_arrive.add(x)
    for y in rev_edge[x]:
        if not y in can_arrive:
            d.append(y)

for i in range(N):
    update = False
    for j in range(M):
        A,B,cost = edge[j]
        if dis[A] != INF and dis[B] > dis[A]+cost:
            dis[B] = dis[A]+cost
            if B in can_arrive:
                update = True
ans = dis[N]
if update:
    print(-1)
else:
    print(max(0,-ans))

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(N)]
for i in range(M):
    a,b,c = map(int,(input().split()))
    line[a-1].append([b-1,-c+P])

min_distance = [float("inf")]*N # min_distance[i] は始点から街iまでの最短距離
min_distance[0] = 0 # 始点から始点への最短距離は0とする

def Bellman_Ford(S,V,E,distance):
    update = False
    flag = 0
    for _ in range(V):
      for s in range(N):
        for g,d in line[s]: # [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:
            flag = 1
            break
    return min_distance,flag

def Bellman_Ford2(S,V,E,distance):
    for _ in range(V):
      for s in range(N):
        for g,d in line[s]: # [s,g,d] = [道路の始点,道路の終点,道路の長さ] について、すべての道路を見る
            if min_distance[s] != float("inf") and min_distance[s] + d < min_distance[g]: # 最短経路が確立されている街から伸びる道路を通ることで、距離を短くできるならば、
                min_distance[g] = -float("inf")
                if g == N-1:
                    break
        else:
            continue
        break
    return min_distance

min_distance,flag = Bellman_Ford(1,N,M,line)

if flag == 1:
    ans = min_distance[N-1]
    print(max(-ans,0))
else:
    min_distance = Bellman_Ford2(1,N,M,line)
    ans = min_distance[N-1]
    if ans == -float("inf"):
        print(-1)
    else:
        print(max(-ans,0))

#print(min_distance)

Submission status: Time Limit Exceeded

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [-10**18] * n
ok1 = [False] * n
ok2 = [False] * n
d[0] = 0
ok1[0] = True
ok2[-1] = True

for _ in range(n):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True
aa = d[:]

for _ in range(1):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True

bb = d[:]

ok = False
for i in range(n):
    if ok1[i] and ok2[i]:
        if aa[i] != bb[i]:
            ok = True
if ok:
    print("-1")
else:
    print(max(aa[-1], 0))

Submission status: Time Limit Exceeded

Solution code:
# 両方から到達出来ないものに関する辺を無視してベルマンフォード
import sys
sys.setrecursionlimit(10**6)
n, m, p = map(int, input().split())
edges = []
to = [[] for _ in range(n)]
ot = [[] for _ in range(n)]
reachable_from_1 = [False] * n
reachable_to_n = [False] * n
ok = [False] * n
INF = float('inf')


def dfs(v):
    if reachable_from_1[v]:
        return
    reachable_from_1[v] = True
    for nv in to[v]:
        dfs(nv)


def rdfs(v):
    if reachable_to_n[v]:
        return
    reachable_to_n[v] = True
    for nv in ot[v]:
        rdfs(nv)


for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c -= p
    c = -c
    edges.append((a, b, c))
    to[a].append(b)
    ot[b].append(a)
dfs(0)
rdfs(n - 1)
for i in range(n):
    ok[i] = reachable_from_1[i] and reachable_to_n[i]
d = [INF] * n
d[0] = 0
upd = True
step = 0
while upd:
    upd = False
    for e in edges:
        frm, to, cost = e
        if not ok[frm]:
            continue
        if not ok[to]:
            continue
        nd = d[frm] + cost
        if nd < d[to]:
            d[to] = nd
            upd = True
    step += 1
    if step > n:
        print(-1)
        exit()
ans = -d[n - 1]
ans = max(0, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
input = sys.stdin.readline


n, m, p = map(int, input().split())
l = np.zeros((n, n))
for i in range(m):
    a, b, c =map(int, input().split())
    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(l)[0][-1])*(-1)))
except:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import bellman_ford, connected_components
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    l = np.zeros((n, n))
    for i in range(m):
        a, b, c =map(int, input().split())
        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(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, connected_components
from scipy.sparse import csr_matrix
input = sys.stdin.readline


def main():
    n, m, p = map(int, input().split())
    
    l = np.zeros((n, n))
    for i in range(m):
        a, b, c =map(int, input().split())
        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()