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
sys.setrecursionlimit(10000000)

#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append((a,b,c))
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
edge=[[]for _ in range(n)]
ee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    edge[a].append((b,c))
    ee.append((a,b,-c))
if find_negative_loop(n,ee):print(-1);exit()
Q=[0]
ans=[0]*n
while Q:
  P=[]
  for i in Q:
    for j,c in edge[i]:
      if ans[j]:continue
      ans[j]=ans[i]+c
  Q=P
print(max(ans[n-1],0))

Submission status: Wrong Answer

Solution code:
#DAG判定
#n=頂点数 e=隣接リスト
#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append([a,b,c])
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
eee=[]
ef=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    eee.append([a,b,-c])
    ef[a].append(b)
    edge[a].append([b,c])
if find_negative_loop(n,eee):print(-1);exit()
t=find_loop(n,ef,1)
ans=[0]*n
for i in t:
  for j,c in edge[i]:
    ans[j]=max(ans[j],ans[i]+c)
print(max(ans[n-1],0))

Submission status: Wrong Answer

Solution code:
#DAG判定
#n=頂点数 e=隣接リスト
#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
  d=n*[10**20];d[0]=0
  for h in range(n):
    for i,j,k in e:
      if d[j]>d[i]+k:
        d[j]=d[i]+k
        if h==n-1:return True
  return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append([a,b,c])
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
eee=[]
ef=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:
    eee.append([a,b,-c])
    ef[a].append(b)
    edge[a].append([b,c])
if find_negative_loop(n,eee):print(-1);exit()
t=find_loop(n,ef,1)
ans=[0]*n
for i in t:
  for j,c in edge[i]:
    ans[j]=max(ans[j],ans[i]+c)
print(ans[n-1])

Submission status: Wrong Answer

Solution code:
#DAG判定
#n=頂点数 e=隣接リスト
#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
	d=n*[10**20];d[0]=0
	for h in range(n):
		for i,j,k in e:
			if d[j]>d[i]+k:
				d[j]=d[i]+k
				if h==n-1:return True
	return False

#DAG判定
#n=頂点数 e=隣接リスト
#flag=0...DAG判定　flag=1...トポロジカルソート
from collections import deque
def find_loop(n,e,flag):
  x=[0]*n
  d=deque()
  t=[]
  c=0
  for i in range(n):
    for j in e[i]:x[j]+=1
  for i in range(n):
    if x[i]==0:
      d.append(i)
      t.append(i)
      c+=1
  while d:
    i=d.popleft()
    for j in e[i]:
      x[j]-=1
      if x[j]==0:
        d.append(j)
        t.append(j)
        c+=1
  if flag==0:return c==n
  else:return t

n,m,p=map(int,input().split())
ef=[[]for _ in range(n)]
ee=[[]for _ in range(n)]
edge=[[]for _ in range(n)]
e=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c-=p
  ef[a].append(b)
  ee[b].append(a)
  edge[a].append((b,c))
  e.append([a,b,c])
eff=[0]*n
eff[0]=1
Q=[0]
visited={0}
while Q:
  P=[]
  for i in Q:
    for j in ef[i]:
      if j in visited:continue
      visited.add(j)
      eff[j]=1
      P.append(j)
  Q=P
eef=[0]*n
eef[n-1]=1
Q=[n-1]
visited={n-1}
while Q:
  P=[]
  for i in Q:
    for j in ee[i]:
      if j in visited:continue
      visited.add(j)
      eef[j]=1
      P.append(j)
  Q=P
for i in range(n):
  if not(eff[i]==1 and eef[i]==1):
    edge[i]=[]
    ef[i]=[]
eee=[]
for a,b,c in e:
  if eff[a]==1 and eef[a]==1 and eff[b]==1 and eef[b]==1:eee.append([a,b,-c])
if find_negative_loop(n,eee):print(-1);exit()
t=find_loop(n,ef,1)
ans=[0]*n
for i in t:
  for j,c in edge[i]:
    ans[j]=max(ans[j],ans[i]+c)
print(ans[n-1])

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
array = [tuple(int(x) for x in input().split()) for x in range(M)]
score = [float("inf") for x in range(N+1)]
score[1] = 0
check = 0
while(True):
    if(N < 0):
        check = score[-1]
        for i in array:
            if(score[i[0]] - i[2] + P > 0):
                score[i[1]] = 0
            else:
                score[i[1]] = score[i[0]] - i[2] + P
        if(check == score[-1]):
            print(-check)
            break
        else:
            print(-1)
            break
    now = score.copy()
    for i in array:
        if(score[i[0]] - i[2] + P < score[i[1]]):
            if(score[i[0]] - i[2] + P > 0):
                score[i[1]] = 0
            else:
                score[i[1]] = score[i[0]] - i[2] + P
    if(now == score):
        print(-score[-1])
        break
    N += -1

Submission status: Wrong Answer

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

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


dist = [float('inf')] * (N+1)
dist[1] = 0
for i in range(N-1):
    for u, v, weight in edges:
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
for i in range(N):
    for u, v, weight in edges:
        if dist[v] > dist[u] + weight:
            dist[v] = dist[u] + weight
            if v == N:
                print(-1)
                exit()
print(max(-dist[N], 0))

Submission status: Wrong Answer

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

def bellmanford(G, s, N):
    n = len(G)
    inf = float('inf')
    dist = [inf] * n
    dist[s] = 0
    for i in range(n+1):
        for v in range(n):
            for w, c in G[v]:
                if dist[w] > dist[v] + c:
                    dist[w] = dist[v] + c
                    if i == n and w == N - 1:
                        return False
    return dist


def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append((b, -c+P))
    ans = bellmanford(G, 0, N)
    if ans:
        print(max(0, -ans[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def bellmanford(G, s, N):
    n = len(G)
    inf = float('inf')
    dist = [inf] * n
    dist[s] = 0
    for i in range(n):
        for v in range(n):
            for w, c in G[v]:
                if dist[w] > dist[v] + c:
                    dist[w] = dist[v] + c
                    if i == n - 1 and w == N - 1:
                        return False
    return dist

def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append((b, -c+P))
    ans = bellmanford(G, 0, N)
    if ans:
        print(max(0, -ans[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def bellmanford(G, s):
    n = len(G)
    inf = float('inf')
    dist = [inf] * n
    dist[s] = 0
    for i in range(n):
        for v in range(n):
            for w, c in G[v]:
                if dist[w] > dist[v] + c:
                    dist[w] = dist[v] + c
                    if i == n - 1 and w == n - 1:
                        return False
    return dist

def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append((b, -c+P))
    ans = bellmanford(G, 0)
    if ans:
        print(max(0, -ans[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
INF = 10**18

edges = []
E = [[] for _ in range(N)]
R = [[] for _ in range(N)]
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    edges.append((fr, to, -(c - P)))
    E[fr].append(to)
    R[to].append(to)

def existsPath(s, edges):
    visited = [False] * N
    visited[s] = True
    st = [s]
    while st:
        now = st.pop()
        for to in edges[now]:
            if visited[to]:
                continue
            st.append(to)
            visited[to] = True
    return visited

canGoFrom1 = existsPath(0, E)
canGoFromN = existsPath(N - 1, R)

minDist = [INF] * N
minDist[0] = 0
for i in range(N + 1):
    for fr, to, c in edges:
        d = minDist[fr] + c
        if minDist[to] > d:
            if i == N and canGoFrom1[fr] and canGoFromN[to]:
                print('-1')
                exit()
            minDist[to] = d

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

Submission status: Wrong Answer

Solution code:
from collections import deque


def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

  
def bellman_ford2(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(2 * n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

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 a, b, cost in info:
    a -= 1
    b -= 1
    graph[a].append((b, -(cost - p)))

_, dist1 = bellman_ford(0, graph)
_, dist2 = bellman_ford2(0, graph)

reach = [False] * n
reach[0] = True
q = deque([0])
while q:
    pos = q.popleft()
    for next_pos, _ in graph[pos]:
        if reach[next_pos]:
            continue
        reach[next_pos] = True
        q.append(next_pos)
        

for i in range(n):
    if reach[i]:
        if max(-dist1[i], 0) != max(-dist1[i], 0):
            print(-1)
            exit()
if dist1[-1] == dist2[-1]:
    print(max(-dist1[-1], 0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
es = [[] for _ in range(N)]
rs = [[] for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    es[a].append((b,P-c))
    rs[b].append(a)

stack = [0]
govisit = set([0])
while stack:
    v = stack.pop()
    for to,_ in es[v]:
        if to in govisit: continue
        govisit.add(to)
        stack.append(to)

stack = [N-1]
backvisit = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in backvisit: continue
        backvisit.add(to)
        stack.append(to)
use = govisit & backvisit

dist = [0] * N
for i in range(N):
    for fr,e in enumerate(es):
        if fr not in use: continue
        for to,c in e:
            if to not in use: continue
            if dist[to] > dist[fr] + c:
                dist[to] = dist[fr] + c
                if i==N-1:
                    print(-1)
                    exit()
print(max(0,-dist[-1]))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]
es = [[] for _ in range(N)]
rs = [[] for _ in range(N)]
for a,b,c in ABC:
    a,b = a-1,b-1
    es[a].append((b,P-c))
    rs[b].append(a)

stack = [0]
govisit = set([0])
while stack:
    v = stack.pop()
    for to,_ in es[v]:
        if to in govisit: continue
        govisit.add(to)
        stack.append(to)

stack = [N-1]
backvisit = set([N-1])
while stack:
    v = stack.pop()
    for to in rs[v]:
        if to in backvisit: continue
        backvisit.add(to)
        stack.append(to)
use = govisit & backvisit

dist = [0] * N
for i in range(N):
    for fr,e in enumerate(es):
        if fr not in use: continue
        for to,c in e:
            if to not in use: continue
            if dist[to] > dist[fr] + c:
                dist[to] = dist[fr] + c
                if i==N-1:
                    print(-1)
                    exit()
print(-dist[-1])

Submission status: Wrong Answer

Solution code:
def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

  
def bellman_ford2(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = 10 ** 18
    n = len(graph)
    dist = [INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(2 * n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if dist[nxt_v] > dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

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 a, b, cost in info:
    a -= 1
    b -= 1
    graph[a].append((b, -(cost - p)))

_, dist1 = bellman_ford(0, graph)
_, dist2 = bellman_ford2(0, graph)
if dist1[-1] == dist2[-1]:
    print(max(-dist1[-1], 0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.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

def solve():
    def dfs(x,f):
        dx = d[x]
        for y,c in v[x]:
            if not f[y]:
                f[y] = 1
                d[y] = dx+c
                dfs(y,f)
                f[y] = 0
            else:
                nd = dx+c
                if nd > d[y]:
                    d[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        w = c-p
        v[a].append((b,w))
    d = [-float("inf")]*n
    d[0] = 0
    f = [0]*n
    f[0] = 1
    dfs(0,f)
    ans = d[n-1]
    if ans == float("inf") or ans == -float("inf"):
        print(-1)
    else:
        print(max(0,ans))
    return

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

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.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

def solve():
    n,m,p = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        w = c-p
        v[a].append((b,-w))
    d = [float("inf")]*n
    d[0] = 0
    for i in range(n):
        update = 0
        for x in range(n):
            dx = d[x]
            for y,c in v[x]:
                nd = dx+c
                if nd < d[y]:
                    d[y] = nd
                    update = 1
        if not update:
            break
    else:
        p = d[n-1]
        for x in range(n):
            dx = d[x]
            for y,c in v[x]:
                nd = dx+c
                if nd < d[y]:
                    d[y] = nd
        if p <= d[n-1]:
            print(max(0,-d[n-1]))
        else:
            print(-1)
        return
    print(max(0,-d[n-1]))
    return

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

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.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

def solve():
    n,m,p = LI()
    v = [[] for i in range(n)]
    for _ in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        w = c-p
        v[a].append((b,-w))
    d = [float("inf")]*n
    d[0] = 0
    for i in range(n):
        update = 0
        for x in range(n):
            dx = d[x]
            for y,c in v[x]:
                nd = dx+c
                if nd < d[y]:
                    d[y] = nd
                    update = 1
        if not update:
            break
    else:
        p = d[n-1]
        for x in range(n):
            dx = d[x]
            for y,c in v[x]:
                nd = dx+c
                if nd < d[y]:
                    d[y] = nd
        if p == d[n-1]:
            print(max(0,-d[n-1]))
        else:
            print(-1)
        return
    print(max(0,-d[n-1]))
    return

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

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


def BF(p, n, s):
    inf = float("inf")
    d = [inf for i in range(n)]
    d[s - 1] = 0
    for i in range(n + 1):
        for e in p:
            if e[0] != inf and d[e[1] - 1] > d[e[0] - 1] + e[2]:
                d[e[1] - 1] = d[e[0] - 1] + e[2]
        if i == n - 1:
            t = d[-1]
        if i == n and t != d[-1]:
            return [0, 'inf']
    return list(map(lambda x: -x, d))


n, m, p = map(int, readline().split())
abc = [list(map(int, readline().split())) for i in range(m)]
a = []
memo = -float('inf')
for x, y, z in abc:
    a.append([x, y, p - z])
    memo = max(memo, p - z)
ans = BF(a, n, 1)[-1]
if ans == 'inf':
    print(-1)
else:
    if memo >= 0:
        print(0)
    else:
        print(max(int(ans), 0))

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)


def BF(p, n, s):
    inf = float("inf")
    d = [inf for i in range(n)]
    d[s - 1] = 0
    for i in range(n + 1):
        for e in p:
            if e[0] != inf and d[e[1] - 1] > d[e[0] - 1] + e[2]:
                d[e[1] - 1] = d[e[0] - 1] + e[2]
        if i == n - 1:
            t = d[-1]
        if i == n and t != d[-1]:
            return [0, 'inf']
    return list(map(lambda x: -x, d))


n, m, p = map(int, readline().split())
abc = [list(map(int, readline().split())) for i in range(m)]
a = [[x, y, -z + p] for x, y, z in abc]
ans = BF(a, n, 1)[-1]
if ans == 'inf':
    print(-1)
else:
    print(max(int(ans), 0))

Submission status: Wrong Answer

Solution code:
import queue as qu
def BFS(connectinons:list,N):
    bfs_connections=[[] for _ in range(N)]
    reverse_connections=[[] for _ in range(N)]


    for A,B,_ in connectinons:
        bfs_connections[A].append(B)
        reverse_connections[B].append(A)
    
    reachable= [False]*N
    rev_reachable=[False]*N

    q = qu.Queue()
    q.put(0)

    while not q.empty():
        node = q.get()
        if reachable[node]:
            continue
        reachable[node]=True

        for B in bfs_connections[node]:
            q.put(B)
    
    q = qu.Queue()
    q.put(N-1)

    while not q.empty():
        node = q.get()
        if rev_reachable[node]:
            continue
        rev_reachable[node]=True

        for B in reverse_connections[node]:
            q.put(B)

    use=set()
    for i in range(N):
        if reachable[i] and rev_reachable[i]:
            use.add(i)
        
    return [[a,b,c] for a,b,c in connectinons if a in use and b in use]









def b_ford(connections:list,N):
    inf=float('inf')
    cost =[inf]*N
    cost[0]=0
    newchanged = set()
    oldchanged = set()

    for i in range(N):
        oldchanged=newchanged
        newchanged= set()
        for A,B,C in connections:
            if cost[A]+C < cost[B]:
                newchanged.add(B)
                cost[B]=cost[A]+C
        
        if N-1 in oldchanged and not N-1 in newchanged:
            if cost[-1] > 0:
                print(0)
            else:
                print(-cost[-1])
            return
    print(-1)







def resolve():
    N,M,P = map(int,input().split())
    
    connections = []
    for i in range(M):
        A,B,C = map(int,input().split())
        
        connections.append([A-1,B-1,P-C])
    #print(connections)
    connections = BFS(connections,N)
    #print(connections)
    b_ford(connections,N)







resolve()

Submission status: Wrong Answer

Solution code:
import queue as qu
def BFS(connectinons:list,N):
    bfs_connections=[[] for _ in range(N)]
    reverse_connections=[[] for _ in range(N)]


    for A,B,_ in connectinons:
        bfs_connections[A].append(B)
        reverse_connections[B].append(A)
    
    reachable= [False]*N
    rev_reachable=[False]*N

    q = qu.Queue()
    q.put(0)

    while not q.empty():
        node = q.get()
        if reachable[node]:
            continue
        reachable[node]=True

        for B in bfs_connections[node]:
            q.put(B)
    
    q = qu.Queue()
    q.put(N-1)

    while not q.empty():
        node = q.get()
        if rev_reachable[node]:
            continue
        rev_reachable[node]=True

        for B in reverse_connections[node]:
            q.put(B)

    use=set()
    for i in range(N):
        if reachable[i] and rev_reachable[i]:
            use.add(i)
        
    return [[a,b,c] for a,b,c in connectinons if a in use and b in use]









def b_ford(connections:list,N):
    inf=float('inf')
    cost =[inf]*N
    cost[0]=0
    newchanged = set()
    oldchanged = set()

    for i in range(N):
        oldchanged=newchanged
        newchanged= set()
        for A,B,C in connections:
            if cost[A]+C < cost[B]:
                newchanged.add(B)
                cost[B]=cost[A]+C
        
        if N-1 in oldchanged and not N-1 in newchanged:
            if cost[-1] > 0:
                print(0)
            else:
                print(-cost[-1])
            return
    print(-1)







def resolve():
    N,M,P = map(int,input().split())
    
    connections = []
    for i in range(M):
        A,B,C = map(int,input().split())
        
        connections.append([A-1,B-1,P-C])
    print(connections)
    connections = BFS(connections,N)
    print(connections)
    b_ford(connections,N)







resolve()