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:

INF = 3000*(10**5)

def main():
    n, m, p = map(int,input().split())
    es = []
    for _ in range(m):
        e = list(map(int,input().split()))
        es.append([e[0]-1,e[1]-1,- e[2] + p])

    v_cost = [INF]*n
    v_cost[0] = 0
    for v in range(n):
        for e in es:
            frm = e[0]
            to = e[1]
            v_cost[to] = min(v_cost[to],v_cost[frm]+e[2])
    
    tmp = v_cost[-1]

    for v in range(n):
        for e in es:
            frm = e[0]
            to = e[1]
            if v_cost[to] > v_cost[frm]+e[2]:
                v_cost[to] = v_cost[frm]+e[2]
                if v >= n:
                    v_cost[to] = -INF
    if tmp != v_cost[-1]:
        return -1

    return max(0,-v_cost[-1])
   

if __name__ =="__main__":
    print (main())

Submission status: Wrong Answer

Solution code:

INF = 3000*(10**5)

def main():
    n, m, p = map(int,input().split())
    es = []
    for _ in range(m):
        e = list(map(int,input().split()))
        e[2] = - e[2] + p
        es.append(e)

    v_cost = [INF]*(n+1)
    v_cost[1] = 0
    for v in range(n):
        for e in es:
            frm = e[0]
            to = e[1]
            v_cost[to] = min(v_cost[to],v_cost[frm]+e[2])
    
    tmp = v_cost[n]

    for v in range(n):
        for e in es:
            frm = e[0]
            to = e[1]
            v_cost[to] = min(v_cost[to],v_cost[frm]+e[2])
    
    if tmp > v_cost[n]:
        return -1

    return max(0,-v_cost[n])
   

if __name__ =="__main__":
    print (main())

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c
                if i >= N:
                    dist[d] = float('inf')

            if i == N-1:
                prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N+10):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-1:
            prev = dist[-1]
        if i >= N:
            if prev != dist[-1]:
                return None, dist

    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N+10):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-1:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N+10):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N+10):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-2:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-2:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(2*N):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-1:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

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

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

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


def bellnabFord(edges, src, N):
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[src] = 0

    for i in range(N):
        for s, d, c in edges:
            if s != inf and dist[d] > dist[s]+c:
                dist[d] = dist[s]+c

        if i == N-2:
            prev = dist[-1]
    return (prev, dist[-1])


prev, dist = bellnabFord(edges, 0, N)
if prev != dist:
    ans = -1
else:
    ans = max(0, -dist)
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'
inf=float("inf")

def BF(edges,num_v,start):
  # edges: [(start_node,end_node,cost),,,], num_v: no of nodes, start: start node
  # return dist = minimum distance from start node, '-inf' when there's a negative loop in the way to the node
  dist=[inf]*num_v
  dist[start]=0
  cont_flg=False
  
  for i in range(num_v):
      for a,b,c in edges:
          if dist[a]!=inf and dist[a]+c<dist[b]:
              dist[b]=dist[a]+c
              if i==num_v-1:
                  dist[b]=-inf
                  cont_flg==True
  
  if cont_flg:
      for i in range(num_v*2):
          for a,b,c in edges:
              #if dist[a]!=inf and dist[a]+c<dist[b]:
              if dist[a]==-inf or (dist[a]!=inf and dist[a]+c<dist[b]):
                  dist[b]=-inf

  return dist
  
n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    a-=1
    b-=1
    g.append((a,b,p-c))

di=BF(g,n,0)
ans=di[n-1]

if ans==-inf:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
class WarshallFloyd():
    def __init__(self, N):
        self.N = N
        self.d = [[float("inf") for i in range(N)]
                  for i in range(N)]  # d[u][v] : 辺uvのコスト(存在しないときはinf)

    def add(self, u, v, c, directed=False):
        """
        0-indexedであることに注意
        u = from, v = to, c = cost
        directed = Trueなら、有向グラフである
        """
        if directed is False:
            self.d[u][v] = c
            self.d[v][u] = c
        else:
            self.d[u][v] = c

    def WarshallFloyd_search(self):
        # これを d[i][j]: iからjへの最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行けそう
        # d[i][i] < 0 なら、グラフは負のサイクルを持つ
        for k in range(self.N):
            for j in range(self.N):
                    self.d[0][j] = min(
                        self.d[0][j], self.d[0][k] + self.d[k][j])
        hasNegativeCycle = False
        for i in range(self.N):
            if self.d[i][i] < 0:
                hasNegativeCycle = True
                break
        for i in range(self.N):
            self.d[i][i] = 0
        return hasNegativeCycle, self.d


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


hasNegativeCycle, d = graph1.WarshallFloyd_search()
if hasNegativeCycle and d[0][N-1] < 0:
    print(-1)
    quit()

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

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'
inf=float("inf")

def BF(edges,num_v,start):
  # edges: [(start_node,end_node,cost),,,], num_v: no of nodes, start: start node
  # return dist = minimum distance from start node, '-inf' when there's a negative loop in the way to the node
  dist=[inf]*num_v
  dist[start]=0
  cont_flg=False
  
  for i in range(num_v):
      for a,b,c in edges:
          if dist[a]!=inf and dist[a]+c<dist[b]:
              dist[b]=dist[a]+c
              if i==num_v-1:
                  dist[b]=-inf
                  cont_flg==True
  
  if cont_flg:
      for i in range(num_v*2):
          for a,b,c in edges:
              #if dist[a]!=inf and dist[a]+c<dist[b]:
              if dist[a]==-inf:
                  dist[b]=-inf

  return dist
  
n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    a-=1
    b-=1
    g.append((a,b,p-c))

di=BF(g,n,0)
ans=di[n-1]

if ans==-inf:
    print(-1)
    for i in range(10**10):
        0+0
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'
inf=float("inf")

def BF(edges,num_v,start):
  # edges: [(start_node,end_node,cost),,,], num_v: no of nodes, start: start node
  # return dist = minimum distance from start node, '-inf' when there's a negative loop in the way to the node
  dist=[inf]*num_v
  dist[start]=0
  cont_flg=False
  
  for i in range(num_v):
      for a,b,c in edges:
          if dist[a]!=inf and dist[a]+c<dist[b]:
              dist[b]=dist[a]+c
              if i==num_v-1:
                  dist[b]=-inf
                  cont_flg==True
  
  if cont_flg:
      for i in range(num_v*2):
          for a,b,c in edges:
              #if dist[a]!=inf and dist[a]+c<dist[b]:
              if dist[a]==-inf:
                  dist[b]=-inf

  return dist
  
n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    a-=1
    b-=1
    g.append((a,b,p-c))

di=BF(g,n,0)
ans=di[n-1]

if ans==-inf:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'
inf=float("inf")

def BF(edges,num_v,start):
  # edges: [(start_node,end_node,cost),,,], num_v: no of nodes, start: start node
  # return dist = minimum distance from start node, '-inf' when there's a negative loop in the way to the node
  dist=[inf]*num_v
  dist[start]=0
  cont_flg=False
  
  for i in range(num_v):
      for a,b,c in edges:
          if dist[a]!=inf and dist[a]+c<dist[b]:
              dist[b]=dist[a]+c
              if i==num_v-1:
                  dist[b]=-inf
                  cont_flg==True
  
  if cont_flg:
      for i in range(num_v*2):
          for a,b,c in edges:
              if dist[a]!=inf and dist[a]+c<dist[b]:
                  dist[b]=-inf

  return dist
  
n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    a-=1
    b-=1
    g.append((a,b,p-c))

di=BF(g,n,0)
ans=di[n-1]

if ans==-inf:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'


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 and ans!=dist[n-1]:
            0#return 'neg'
    ans=dist[n-1]
  return dist

def shortest_path(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    while True:
        updata = False
        for i in range(w):
            e = es[i]
            ans=d[n-1]
            # e: 辺iについて [from,to,cost]
            if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                updata = True
        if not updata:
            break
    return d

n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    #g.append((a-1,b-1,p-c))
    g.append((a,b,p-c))
    

di=BellmanFord(g,n,1)
ans=di[n-1]
di_2=BellmanFord(g,n*2,1)

if ans!=di_2[n-1]:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
YNeos='YNeos'
mo=10**9+7
imp='IMPOSSIBLE'
inf=float("inf")

def BF(edges,num_v,start):
  # edges: [(start_node,end_node,cost),,,], num_v: no of nodes, start: start node
  # return dist = minimum distance from start node, '-inf' when there's a negative loop in the way to the node
  dist=[inf]*num_v
  dist[start]=0
  cont_flg=False
  
  for i in range(num_v):
      for a,b,c in edges:
          if dist[a]!=inf and dist[a]+c<dist[b]:
              dist[b]=dist[a]+c
              if i==num_v-1:
                  dist[b]=-inf
                  cont_flg==True
  
  if cont_flg:
      for i in range(num_v):
          for a,b,c in edges:
              if dist[a]!=inf and dist[a]+c<dist[b]:
                  dist[b]=-inf

  return dist
  
n,m,p=MI()
g=[]
for i in range(m):
    a,b,c=MI()
    a-=1
    b-=1
    g.append((a,b,p-c))

di=BF(g,n,0)
ans=di[n-1]

if ans==-inf:
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf") # sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2
max_even = N // 2
max_odd = N - max_even

def solve(pos, odd_cnt, even_cnt, num_sum):
    global cost

    if not(pos in ABC_d): return

    if odd_cnt + even_cnt > N or num_sum > max_num_sum:#  odd_cnt > max_odd or even_cnt > max_even or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            if B%2: odd_cnt += 1
            else: even_cnt += 1
            cost[B - 1] = cost[pos - 1] + C
            solve(B, odd_cnt, even_cnt, num_sum + B)


# solve(1, 1, 1)
solve(1, 1, 0, 1)

if (cost[-1] == f_inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#ABC137 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    #start → iの最短距離
    #start:始点, num_v:頂点数, edges:[辺の始点, 辺の終点, 辺のコスト]
    dist = [-float('inf') for _ in range(num_v)]
    #dist[i] := s→iの最短距離
    dist[start] = 0
    flg = 0
    for i in range(num_v):
        update = False
        for edge in edges:
            e_from, e_to, e_cost = edge
            if e_from != -float('inf') and visited[e_to] and dist[e_to] < dist[e_from] + e_cost:
                dist[e_to] = dist[e_from] + e_cost
                update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
f = defaultdict(dict)
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
    f[b-1][a-1] = 1
visited = [False]*n
def dfs(x):
    visited[x] = True
    for t in f.keys():
        if not visited[t]:
            dfs(t)
dfs(n-1)
d,f = Bellman_Ford(edge,n,0)
if d[-1] < 0:
    print(0)
elif not f:
    print(-1)
else:
    print(d[-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf") # sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2
max_even = N // 2
max_odd = N - max_even

def solve(pos, odd_cnt, even_cnt, num_sum):
    global cost

    if not(pos in ABC_d): return
    if odd_cnt > max_odd or even_cnt > max_even or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            if B%2: odd_cnt += 1
            else: even_cnt += 1
            cost[B - 1] = cost[pos - 1] + C
            solve(B, odd_cnt, even_cnt, num_sum + B)


# solve(1, 1, 1)
solve(1, 1, 0, 1)

if (cost[-1] == f_inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = N * (N + 1) // 2

def solve(pos, cnt, num_sum):
    global cost
    global pass_cnt

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        num_sum += B
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1, num_sum)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum)


solve(1, 1, 1)

if (cost[-1] == sys.maxsize):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

pass_cnt = [0] * N
pass_cnt[0] = 1
cost = [-f_inf] * N
cost[0] = 0

def solve(pos):
    global cost
    global pass_cnt

    if not(pos in ABC_d): return
    if pass_cnt[pos - 1] > 1:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        pass_cnt[B-1] += 1
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B)

solve(1)
if (cost[-1] == sys.maxsize):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt > N:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        # elif cost[pos-1] == f_inf:
        #     cost[B-1] = f_inf
        #     solve(B, cnt + 1)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)

solve(1, 1)

if (cost[-1] >= sys.maxsize):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

Solution code:
import copy
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf")

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
# cost = np.empty(N, dtype = int) - f_inf
cost[0] = 0

# def solve(pos, already):
#     global cost
#     global already2

#     if not(pos in ABC_d): return

#     for B, C in ABC_d[pos]:
#         if already[B - 1] == True:
#             if cost[B - 1] == f_inf:
#                 pass
#             elif cost[pos-1] == f_inf or cost[B - 1] < cost[pos - 1] + C:
#                 cost[B-1] = f_inf
#                 solve(B, already)
#         elif cost[B - 1] < cost[pos - 1] + C:
#             cost[B - 1] = cost[pos - 1] + C
#             already2 = already[:]
#             already2[B - 1] = True
#             solve(B, already2)

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt >= N: cost[pos-1] = f_inf;
    # print (pos, cnt, N, cost[pos - 1])
    for B, C in ABC_d[pos]:
        # print (cost[B - 1], cost[pos - 1] + C)
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)


# already = np.zeros(N, dtype = bool)
already = [False] * N
already[0] = True
solve(1, 1)

if (cost[-1] == f_inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Wrong Answer

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

INF = 1000000000000000000000000000000000

es = []
for _ in range(M):
  a,b,d = map(int, input().split())
  a-=1
  b-=1
  d = -(d-P)
  es.append((a,b,d))

ds = [INF] * N
ds[0] = 0

def update():
  for a,b,d in es:
    if ds[a] != INF:
      ds[b] = min(ds[b], ds[a] + d)

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

bf()

before = tuple(ds)
update()
after = tuple(ds)

if before == after:
  print(max(-ds[-1], 0))
else:
  print(-1)

Submission status: Wrong Answer

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

INF = 1000000000000000000000000000000000

es = []
for _ in range(M):
  a,b,d = map(int, input().split())
  a-=1
  b-=1
  d = -(d-P)
  es.append((a,b,d))

ds = [INF] * N
ds[0] = 0

def update():
  for a,b,d in es:
    if ds[a] != INF:
      ds[b] = min(ds[b], ds[a] + d)

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

bf()

before = ds[-1]
update()
after = ds[-1]

if before == after:
  print(max(-ds[-1], 0))
else:
  print(-1)