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:
import sys
input = sys.stdin.readline

def main():
    N, M, P = map(int, input().split())
    Edges = [list(map(int, input().split())) for _ in range(M)]

    graph = [[] for _ in range(N)]
    for a, b, c in Edges:
        graph[a-1].append(b-1)

    q = [0]
    Canuse = {0}
    while q:
        qq = []
        for p in q:
            for np in graph[p]:
                if not np in Canuse:
                    Canuse.add(np)
                    qq.append(np)
        q = qq

    D = [0 for _ in range(N)]
    for i in range(N+1):
        update = False
        for a, b, c in Edges:
            a -= 1
            b -= 1
            if not a in Canuse or not b in Canuse: continue
            if D[b] > D[a] + P - c:
                D[b] = D[a] + P - c
                if b == N-1: update = True


    if update:
        print(-1)
    else:
        print(max(-D[N-1], 0))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map(int, input().split())
    Edges = [list(map(int, input().split())) for _ in range(M)]

    graph = [[] for _ in range(N)]
    for a, b, c in Edges:
        graph[a-1].append(b-1)

    q = [0]
    Canuse = {0}
    while q:
        qq = []
        for p in q:
            for np in graph[p]:
                if not np in Canuse:
                    Canuse.add(np)
                    qq.append(np)
        q = qq

    D = [0 for _ in range(N)]
    for i in range(N+1):
        update = False
        for a, b, c in Edges:
            a -= 1
            b -= 1
            if not a in Canuse: continue
            if D[b] > D[a] + P - c:
                D[b] = D[a] + P - c
                if b == N-1: update = True


    if update:
        print(-1)
    else:
        print(max(-D[N-1], 0))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map(int, input().split())
    Edges = [list(map(int, input().split())) for _ in range(M)]

    graph = [[] for _ in range(N)]
    for a, b, c in Edges:
        graph[a-1].append(b-1)

    q = [0]
    Canuse = {0}
    while q:
        qq = []
        for p in q:
            for np in graph[p]:
                if not np in Canuse:
                    Canuse.add(np)
                    qq.append(np)
        q = qq

    D = [0 for _ in range(N)]
    for i in range(N+1):
        update = False
        for a, b, c in Edges:
            a -= 1
            b -= 1
            if not a in Canuse: continue
            if D[b] > D[a] + P - c:
                D[b] = D[a] + P - c
                if b == N-1: update = True


    if update:
        print(-1)
    else:
        print(-D[N-1])

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#負閉路あり最短経路(逆符号最長)
#aoj,grl1b
#負閉路検出では不十分、終点にたどり着ける閉路
#終点からたどる
import sys
n,m,p = map(int, input().split( ))
E = [[] for _ in range(n)]
E_rev = [[] for _ in range(n)]
inf = 10**12
for _ in range(m):
    a,b,c = map(int, input().split( ))
    E[a-1].append([b-1,p-c])###
    E_rev[b-1].append([b-1,p-c])


D = [inf for _ in range(n)]
D2 = [inf for _ in range(n)]
D[0] = 0
D2[n-1] = 0
for _ in range(n):
    for ve in range(n):
        for ed in E[ve]:
            D[ed[0]] = min(D[ed[0]], D[ve] + ed[1])

for _ in range(n):
    for ve in range(n):
        for ed in E_rev[ve]:
            D2[ed[0]] = min(D2[ed[0]], D2[ve] + ed[1])

for i in range(n):
    if E[i]:
        for ed in E[i]:
            if D[i] + ed[1] < D[ed[0]] and D[ed[0]]<inf//10 and D2[i] + ed[1] < D2[ed[0]] and D2[ed[0]]<inf//10:
                print(-1)
                sys.exit()

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

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!


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

el = []
for _ in range(m):
    a,b,c = map(int,input().split())
    el.append((a-1,b-1,c-p))
cost = [-float("inf") for _ in range(n)]
cost[0] = 0
for i in range(n+1):
    for j in range(m):
        e = el[j]
        if cost[e[1]] < cost[e[0]] + e[2]:
            cost[e[1]] = cost[e[0]] + e[2]
            if i == n:
                cost[e[1]] = float("inf")
              
if cost[-1] == float("inf"):
    print(-1)
else:
    print(max(cost[-1], 0))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!


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

el = []
for _ in range(m):
    a,b,c = map(int,input().split())
    el.append((a-1,b-1,c-p))
cost = [-float("inf") for _ in range(n)]
cost[0] = 0
for i in range(n):
    for j in range(m):
        e = el[j]
        if cost[e[1]] < cost[e[0]] + e[2]:
            cost[e[1]] = cost[e[0]] + e[2]
            if i == n-1:
                cost[e[1]] = float("inf")
                
if cost[n-1] == float("inf"):
    print(-1)
else:
    print(max(cost[n-1], 0))

Submission status: Wrong Answer

Solution code:
print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
N, M, P = map(int, input().split())
E1 = [[] for _ in range(N)]
E2 = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    E1[a-1].append((b-1, P-c))
    E2[b-1].append((a-1, P-c))

def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c, d in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return D

def bellman_ford(n, E, s=0):
    D = [0] * n
    for k in range(n):
        for i in range(n):
            for j, c in E[i]:
                if D[j] > D[i] + c:
                    D[j] = D[i] + c
                    if k == n-1: return (1, [])
    return (0, D)

D1 = BFS(N, E1, 0)
D2 = BFS(N, E2, N-1)
L = [i for i in range(N) if D1[i] >= 0 and D2[i] >= 0]

NN = len(L)
LL = [-1] * N
for i in range(NN):
    LL[L[i]] = i

E3 = [[(LL[a], c) for a, c in E1[i] if LL[a] >= 0] for i in range(N) if LL[i] >= 0]
BF = bellman_ford(NN, E3, 0)
if BF[0]:
    print(-1)
else:
    print(max(-BF[1][-1], 0))

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix
from math import ceil

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

adj = [list() for _ in range(N)]
inv = [list() for _ in range(N)]


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

stack = [N-1]
reachable1 = {N-1}
while stack:
    v = stack.pop()
    for u in inv[v]:
        if u not in reachable1:
            stack.append(u)
            reachable1.add(u)

stack = [0]
reachable2 = {0}
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable2:
            stack.append(u)
            reachable2.add(u)

reachable = reachable1 & reachable2


G = dok_matrix((N,N))
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P + 0.0001
        G[u,v] = w

try:
    d = -bellman_ford(G, indices=[0])[0][-1]
    print(max(0, ceil(d)))

except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix
from math import ceil

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

adj = [list() for _ in range(N)]
reachable = {N-1}


for _ in range(M):
    a,b,c = map(int,input().split())
    adj[b-1].append((a-1,c))
stack = [N-1]
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable:
            stack.append(u)
            reachable.add(u)

G = dok_matrix((N,N), dtype=float)
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P + 0.0001
        G[v,u] = w

try:
    d = -bellman_ford(G, indices=[0])[0][-1]
    print(max(0, ceil(d)))

except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix
from math import ceil

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

adj = [list() for _ in range(N)]
reachable = {N-1}


for _ in range(M):
    a,b,c = map(int,input().split())
    adj[b-1].append((a-1,c))
stack = [N-1]
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable:
            stack.append(u)
            reachable.add(u)

G = dok_matrix((N,N))
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P + 0.000001
        G[v,u] = w
try:
    d = -bellman_ford(G, indices=[0])[0][-1]
    print(max(0, ceil(d)))

except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix
from math import ceil

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

adj = [list() for _ in range(N)]
reachable = {N-1}


for _ in range(M):
    a,b,c = map(int,input().split())
    adj[b-1].append((a-1,c))
stack = [N-1]
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable:
            stack.append(u)
            reachable.add(u)

G = dok_matrix((N,N))
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P
        w = 0.0001 if w == 0 else w
        G[v,u] = w
try:
    d = -bellman_ford(G, indices=[0])[0][-1]
    print(max(0, ceil(d)))

except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix
from math import ceil

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

adj = [list() for _ in range(N)]
reachable = {N-1}


for _ in range(M):
    a,b,c = map(int,input().split())
    adj[b-1].append((a-1,c))
stack = [N-1]
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable:
            stack.append(u)
            reachable.add(u)

G = dok_matrix((N,N))
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P
        w = 0.00000001 if w == 0 else w
        G[v,u] = w
try:
    d = -bellman_ford(G, indices=[0])[0][-1]
    print(max(0, ceil(d)))

except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
from scipy.sparse import dok_matrix

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

adj = [list() for _ in range(N)]
reachable = {N-1}


for _ in range(M):
    a,b,c = map(int,input().split())
    adj[b-1].append((a-1,c))
stack = [N-1]
while stack:
    v = stack.pop()
    for u,_ in adj[v]:
        if u not in reachable:
            stack.append(u)
            reachable.add(u)

G = dok_matrix((N,N))
for u,l in enumerate(adj):
    if u not in reachable:
        continue
    for v,c in l:
        if v not in reachable:
            continue
        w = -c+P
        w = 0.00000001 if w == 0 else w
        G[v,u] = w
try:
    D = bellman_ford(G, indices=[0])
    print(max(0, int(-D[0][-1])))
except NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

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


def main():
    total_node_num, edge_num, payment = [
        int(x) for x in input().strip().split()]
    edge_list = []
    for _ in range(edge_num):
        startNode, arriveNode, coin = [int(x) for x in input().strip().split()]
        edge_list.append([startNode-1, arriveNode-1, coin-payment])

    # ベルマンフォード法によりコインの最大値を求める
    # 1Tにpayment枚コインを払う必要があるということは実質のコストはcoin-payment
    node_point_list = [-10**10 for _ in range(total_node_num)]
    node_point_list[0] = 0
    ans = 0
    for loop_num in range(total_node_num):
        update_count = 0
        for edge_idx in range(edge_num):
            start_node = edge_list[edge_idx][0]
            arraive_node = edge_list[edge_idx][1]
            point = edge_list[edge_idx][2]
            if node_point_list[start_node]+point > node_point_list[arraive_node]:
                node_point_list[arraive_node] = node_point_list[start_node]+point
                update_count += 1
        if update_count == 0:
            break
        if loop_num == total_node_num - 2:
            ans = node_point_list[-1]
        if loop_num == total_node_num - 1 and ans != node_point_list[-1]:
            print(-1)
            return
    print(max(node_point_list[-1], 0))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from scipy.sparse import lil_matrix, csr_matrix
from collections import deque

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

edges = lil_matrix((N, N), dtype=int)
edgesR = lil_matrix((N, N), dtype=int)
for _ in range(M):
    fr, to, point = map(int, input().split())
    fr -= 1
    to -= 1
    point -= P
    edges[fr, to] = -point
    edgesR[fr, to] = 1

canVisit = [False] * N
canBack = [False] * N

st = deque([0])
while st:
    now = st.pop()

    if canVisit[now]:
        continue
    canVisit[now] = True

    for _, to in edges.getrow(now).todok().keys():
        if not canVisit[to]:
            st.append(to)

st = deque([N - 1])
while st:
    now = st.pop()

    if canBack[now]:
        continue
    canBack[now] = True

    for _, to in edgesR.getrow(now).todok().keys():
        if not canBack[to]:
            st.append(to)

INF = float('inf')
minDist = [INF] * N
minDist[0] = 0

for cnt in range(N):
    for (fr, to), cost in edges.todok().items():
        d = minDist[fr] + cost
        if minDist[to] > d:
            minDist[to] = d
            if cnt == N - 1 and canVisit[to] and canBack[to]:
                print(-1)
                exit()

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

Submission status: Wrong Answer

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

INF = float("inf")

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

def Bellman_Ford(N, E, G, dist):
	for i in range(N):
		for a, b, w in G:
			if dist[b] > dist[a] + w:
				dist[b] = dist[a] + w

#処理内容
def main():
	N, M, P = getlist()
	dist = [INF] * N
	dist[0] = 0
	G = []
	for i in range(M):
		a, b, w = getlist()
		G.append([a - 1, b - 1, P - w])

	#判定、出力
	Bellman_Ford(N, M, G, dist)
	N1 = dist[N - 1]
	Bellman_Ford(N, M, G, dist)
	N2 = dist[N - 1]

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

if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,m,p=map(int,input().split())
    E=[[] for _ in range(n)]
    for _ in range(m):
        a,b,c=map(int,input().split())
        a-=1; b-=1
        E[a].append((b,p-c))
    # Bellman-Ford
    dist=[INF]*n
    dist[0]=0
    for _ in range(n-1):
        for v in range(n):
            for nv,w in E[v]:
                if(dist[nv]>dist[v]+w):
                    dist[nv]=dist[v]+w
    temp=dist[n-1]
    # Bellman-Fordを2n-1回行い、0からnに負の経路があるのかを探索
    for _ in range(n):
        for v in range(n):
            for nv,w in E[v]:
                if(dist[nv]>dist[v]+w):
                    dist[nv]=dist[v]+w
    if(temp!=dist[n-1]):
        print(-1)
    else:
        print(max(-temp,0))
resolve()

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse.csgraph import bellman_ford
input = sys.stdin.readline

n, m, p = map(int, input().split())
dist = [ [ 0 for _ in range(n) ] for _ in range(n) ]
for _ in range(m):
    a, b, c = map(int, input().split())
    c -= p
    if a!=b:
        dist[a-1][b-1] = -c

try:
    dist = bellman_ford( csgraph=dist )
    res = int(-dist[0][n-1])
    print( res if res>0 else 0 )
except:
    print(-1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(N)
Visit[N]=1
while q:
	fro=q.popleft()
	for to in rev_al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)
			
Visit1=Visit

#スタートからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(1)
Visit[1]=1
while q:
	fro=q.popleft()
	for to in al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)

Visit2=Visit

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") ]*(N+1)	#頂点１からの距離 1-indexed
D[1]=0

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
st=set()
while q:
	fro=q.popleft()
	Visit[fro]=1
	st.add(fro)
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
revst=set()
while q:
	fro=q.popleft()
	Visit[fro]=1
	revst.add(fro)
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

#1からもNからも到達可能な頂点の集合
use = st & revst

new_N=sum(use)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if a in use and b in use:
		fedge.append((a,b,c))


D=[ float("-inf") for _ in range(N+1) ]	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
cnt=0
for i in range(new_N):
	for a,b,c in fedge:
		cnt+=1
		if cnt>10**6: print -1;quit()
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") for _ in range(N+1) ]	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
cnt=0
for i in range(new_N):
	for a,b,c in fedge:
		cnt+=1
		if cnt>10**6: print -1;quit()
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") for _ in range(N+1) ]	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
cnt=0
for i in range(new_N):
	for a,b,c in fedge:
		cnt+=1
		if cnt>10**7: print -1;quit()
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
import copy

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
q=deque()
q.append(N)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in rev_al[fro]:
		if Visit[to]==0:
			q.append(to)
			
Visit1=Visit

#スタートからBFS
q=deque()
q.append(1)
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
while q:
	fro=q.popleft()
	Visit[fro]=1
	for to in al[fro]:
		if Visit[to]==0:
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") for _ in range(N+1) ]	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
for i in range(new_N):
	for a,b,c in fedge:
		if D[a]==float("-inf"): continue
		if i==N-1 and D[b]!=max( D[b],D[a]+c ):
			print -1
			quit()
		D[b]=max( D[b],D[a]+c )

print max(0,D[N])

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

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

flag = [ [False] * N for i in range(N) ]
crash = [False] * N
cost = [float("-inf")] * N
cost[0] = 0

dic = {}
for i in range(N):
    dic[i] = []

    

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    dic[A].append([B,C-P])

q = deque([0])

cnt = 0

while len(q) > 0:

    now = q.popleft()

    for bc in dic[now]:
    
        b = bc[0]
        c = bc[1]

        #print (now,b,flag[now],crash[now],flag[b],crash[b])

        if b == N-1 and crash[now]:
            print (-1)
            sys.exit()

        if cost[now] + c > cost[b] or crash[now]:


            if flag[now][b] and not crash[b]:

                crash[b] = True

                cost[b] = cost[now] + c

                flag[b] = flag[now].copy()

                for j in range(N):

                    flag[b][j] = flag[now][j]
                flag[b][b] = True
            
                q.append(b)

            elif not flag[now][b]:
                
                cost[b] = cost[now] + c
                crash[b] = crash[now]
                cost[b] = cost[now] + c
                crash[b] = crash[now]

                flag[b] = flag[now].copy()
                    
                flag[b][b] = True

                q.append(b)

            else:

                if not crash[b]:
                    crash[b] = crash[now]
                    q.append(b)
                

    cnt += 1

    if cnt > 10*N:
        print (-1)
        sys.exit()

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

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

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

flag = [ [False] * N for i in range(N) ]
crash = [False] * N
cost = [float("-inf")] * N
cost[0] = 0

dic = {}
for i in range(N):
    dic[i] = []

    

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    dic[A].append([B,C-P])

q = deque([0])

cnt = 0

while len(q) > 0:

    now = q.popleft()

    for bc in dic[now]:
    
        b = bc[0]
        c = bc[1]

        #print (now,b,flag[now],crash[now],flag[b],crash[b])

        if b == N-1 and crash[now]:
            print (-1)
            sys.exit()

        if cost[now] + c > cost[b] or crash[now]:


            if flag[now][b] and not crash[b]:

                crash[b] = True

                cost[b] = cost[now] + c

                flag[b] = flag[now].copy()

                for j in range(N):

                    flag[b][j] = flag[now][j]
                flag[b][b] = True
            
                q.append(b)

            elif not flag[now][b]:
                
                cost[b] = cost[now] + c
                crash[b] = crash[now]
                cost[b] = cost[now] + c
                crash[b] = crash[now]

                flag[b] = flag[now].copy()
                    
                flag[b][b] = True

                q.append(b)

            else:
                crash[b] = crash[now]
                q.append(b)
                

    cnt += 1

    if cnt > 10*N:
        print (-1)
        sys.exit()

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

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

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

flag = [ [False] * N for i in range(N) ]
crash = [False] * N
cost = [float("-inf")] * N
cost[0] = 0

dic = {}
for i in range(N):
    dic[i] = []

    

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    dic[A].append([B,C-P])

q = deque([0])

cnt = 0

while len(q) > 0:

    now = q.popleft()

    for bc in dic[now]:
    
        b = bc[0]
        c = bc[1]

        #print (now,b,flag[now],crash[now],flag[b],crash[b])

        if b == N-1 and crash[now]:
            print (-1)
            sys.exit()

        if cost[now] + c > cost[b] or crash[now]:


            if flag[now][b] and not crash[b]:

                crash[b] = True

                cost[b] = cost[now] + c

                flag[b] = flag[now].copy()

                for j in range(N):

                    flag[b][j] = flag[now][j]
                flag[b][b] = True
            
                q.append(b)

            elif not flag[now][b]:
                
                cost[b] = cost[now] + c
                crash[b] = crash[now]
                cost[b] = cost[now] + c
                crash[b] = crash[now]

                flag[b] = flag[now].copy()
                    
                flag[b][b] = True

                q.append(b)

    cnt += 1

    if cnt > 10*N:
        print (-1)
        sys.exit()

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