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:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def solve():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        to[a - 1].append(b - 1)
        reverse_to[b - 1].append(a - 1)

    reachable_from_zero = set()
    cur = {0}
    while cur:
        reachable_from_zero |= cur
        cur = set().union(*(to[node] for node in cur)) - reachable_from_zero
    reachable_to_N = set()
    cur = {N - 1}
    while cur:
        reachable_to_N |= cur
        cur = set().union(*(reverse_to[node] for node in cur)) - reachable_to_N
    reachable = reachable_from_zero & reachable_to_N
    
    AA, BB, CC = [], [], []
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            AA.append(a)
            BB.append(b)
            CC.append(c)
    
    graph = csr_matrix((CC, (AA, BB)), shape=(N, N))
    try:
        bf = bellman_ford(graph, indices=[0])
        print(max(0, -int(bf[0][N - 1])))
    except NegativeCycleError:
        print(-1)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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


def reachable_nodes(s, edges):
    reachable = set()
    reachable.add(s)
    nodes = [s]
    
    while nodes:
        node = nodes.pop()
        for edge in edges[node]:
            if edge not in reachable:
                nodes.append(edge)
                reachable.add(edge)
    return reachable


def solve():
    N, M, P = map(int, input().split())
    graph = []
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    
    for i in range(M):
        ai, bi, ci = map(int, input().split())
        ai, bi = ai - 1, bi - 1
        to[ai].append(bi)
        reverse_to[bi].append(ai)
        graph.append((ai, bi, -(ci - P)))
    
    reachable_from_zero = reachable_nodes(0, to)
    reachable_to_N = reachable_nodes(N - 1, reverse_to)
    can_use = reachable_from_zero & reachable_to_N
    
    A, B, C = [], [], []
    for u, v, cost in graph:
        if u in can_use and v in can_use:
            A.append(u)
            B.append(v)
            C.append(cost)

    bf_matrix = csr_matrix((C, (A, B)), shape=(N, N))
    try:
        bf = bellman_ford(bf_matrix)
        print(-int(bf[0][N - 1]) if bf[0][N - 1] <= 0 else 0)
    except NegativeCycleError:
        print(-1)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def reachable_nodes(s, edges):
    reachable = set()
    reachable.add(s)
    nodes = deque([s])
    
    while nodes:
        node = nodes.popleft()
        for edge in edges[node]:
            if edge not in reachable:
                nodes.append(edge)
                reachable.add(edge)
    return reachable


def solve():
    N, M, P = map(int, input().split())
    graph = []
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    
    for i in range(M):
        ai, bi, ci = map(int, input().split())
        ai, bi = ai - 1, bi - 1
        to[ai].append(bi)
        reverse_to[bi].append(ai)
        graph.append((ai, bi, -(ci - P)))
    
    reachable_from_zero = reachable_nodes(0, to)
    reachable_to_N = reachable_nodes(N - 1, reverse_to)
    can_use = reachable_from_zero & reachable_to_N
    
    bf_matrix = [[0] * N for _ in range(N)]
    for u, v, cost in graph:
        if u in can_use and v in can_use:
            bf_matrix[u][v] = cost
    
    try:
        bf = bellman_ford(csr_matrix(bf_matrix))
        print(-int(bf[0][N - 1]) if bf[0][N - 1] <= 0 else 0)
    except NegativeCycleError:
        print(-1)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def reachable_nodes(s, edges):
    reachable = set()
    reachable.add(s)
    nodes = deque([s])
    
    while nodes:
        node = nodes.popleft()
        for edge in edges[node]:
            if edge not in reachable:
                nodes.append(edge)
                reachable.add(edge)
    return reachable


def solve():
    N, M, P = map(int, input().split())
    graph = [[] for _ in range(N)]
    to = [[] for _ in range(N)]
    reverse_to = [[] for _ in range(N)]
    
    for i in range(M):
        ai, bi, ci = map(int, input().split())
        ai, bi = ai - 1, bi - 1
        to[ai].append(bi)
        reverse_to[bi].append(ai)
        graph[ai].append([bi, -(ci - P)])
    
    reachable_from_zero = reachable_nodes(0, to)
    reachable_to_N = reachable_nodes(N - 1, reverse_to)
    can_use = reachable_from_zero & reachable_to_N
    
    bf_matrix = [[0] * N for _ in range(N)]
    for i in range(N):
        if i not in can_use:
            continue
        for j, cost in graph[i]:
            if j in can_use:
                bf_matrix[i][j] = cost
    
    try:
        bf = bellman_ford(csr_matrix(bf_matrix))
        print(-int(bf[0][N - 1]) if bf[0][N - 1] <= 0 else 0)
    except NegativeCycleError:
        print(-1)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
class Graph(): #directed
    def __init__(self,n,edge):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.deg = [0 for _ in range(n)]
        for e in edge:
            self.graph[e[0]-1].append((e[1]-1,e[2]))
            self.deg[e[1]-1] += 1
    def bellman_ford(self,s,INF=10**18):
        dist = [INF for _ in range(self.n)]
        dist[s] = 0
        update = True
        for i in range(self.n):
            update = False
            for node, g in enumerate(self.graph):
                for adj,adjcost in g:
                    if dist[node] != INF and dist[node]+adjcost < dist[adj]:
                        dist[adj] = dist[node]+adjcost
                        update = True
                        if i == self.n-1:
                            tmp = adj
            if not update:
                return dist
        visited = [0 for _ in range(self.n)]
        visited[tmp] = 1
        stack = [tmp]
        while stack:
            node = stack.pop()
            for adj,c in self.graph[node]:
                if not visited[adj]:
                    visited[adj] = 1
                    stack.append(adj)
        if visited[-1]:
            return -1
        else:
            return dist

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

G = Graph(N,edge)
A = G.bellman_ford(0)

print(max(-A[-1],0) if A!=-1 else -1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford


N, M, P = map(int, input().split())
abc = []
for i in range(M):
  a, b, c = map(int, input().split())
  abc.append([a-1, b-1, P-c])

tree = dict(zip(range(N), [[] for i in range(N)]))
for a, b, c in abc:
  tree[a].append(b)

s = set()
d = [0]
while d:
  node = d[-1]
  if tree[node]:
    child = tree[node].pop()
    if child in d:
      d.pop()
    else:
      d.append(child)
      if child == N-1:
        s = s | set(d)
  else:
    d.pop()


idx = [0]*N
c = 0
for _s in s:
  idx[_s] = c
  c += 1

D = [[float('inf')]*len(s) for i in range(len(s))]
for a, b, c in abc:
  if a in s and b in s:
    D[idx[a]][idx[b]] = c

try:
  dist = bellman_ford(D)
  ans = max(-int(dist[0][-1]), 0)
except:
  ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
#12:27
n,m,tax = map(int,input().split())
raw = []
pre = [[] for _ in range(n)]
for _ in range(m):
  a,b,c = map(int,input().split())
  a -= 1
  b -= 1
  c -= tax
  raw.append([a,b,c])
  pre[b].append(a)
#print(pre)
seen = [0 for _ in range(n)]
now = [n-1]
seen[-1] = 1
while now:
  last = now
  now = []
  for x in last:
    for y in pre[x]:
      if seen[y] == 0:
        seen[y] = 1
        now.append(y)
#print(raw)
#print(seen)
pst = [[] for _ in range(n)]
for x in raw:
  a,b,c = x
  if seen[b] == 1:
    pst[a].append([-c,b])
#print(pst)
import heapq
cost = [10**18 for _ in range(n)]
cost[0]  = 0
now = pst[0]
heapq.heapify(now)
while now:
  c,b = heapq.heappop(now)
  if c >= cost[b]:
    continue
  if cost[b] != 10**18:
    print(-1)
    break
  seen[b] = 1
  cost[b] = c
  for x in pst[b]:
    heapq.heappush(now,[c+x[0],x[1]])
else:
  print(max(0,-cost[-1]))

Submission status: Wrong Answer

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

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


dist = [-float('inf')]*N
dist[0] = 0
for i in range(N):
  for a, b, c in abc:
    dist[b] = max(dist[b], dist[a] + c)

ans = dist[-1]
for i in range(N):
  for a, b, c in abc:
    dist[b] = max(dist[b], dist[a] + c)

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

Submission status: Wrong Answer

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

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


dist = [-float('inf')]*N
dist[0] = 0
for i in range(N):
  for a, b, c in abc:
    dist[b] = max(dist[b], dist[a] + c)

ans = dist[-1]
for a, b, c in abc:
  dist[b] = max(dist[b], dist[a] + c)

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

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
tree1 = dict(zip(range(N), [[] for i in range(N)]))
tree2 = dict(zip(range(N), [[] for i in range(N)]))

for i in range(M):
  a, b, c = map(int, input().split())
  tree1[a-1].append([b-1, c-P])
  tree2[a-1].append([b-1, c-P])


dist = [-float('inf')]*N
dist[0] = 0
def update_dist(d, tree):
  global dist
  while d:
    node = d[-1]
    if tree[node]:
      child, coin = tree[node].pop()
      if child in d:
        if dist[child] < dist[node] + coin:
          dist[child] = float('inf')
      else:
        dist[child] = max(dist[child], dist[node] + coin)
        d.append(child)
    else:
      d.pop()


update_dist([0], tree1)
update_dist([0], tree2)
if dist[-1] < float('inf'):
  ans = max(0, dist[-1])
else:
  ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
tree = dict(zip(range(N), [[] for i in range(N)]))

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


dist = [-float('inf')]*N
dist[0] = 0
d = [0]
while d:
  node = d[-1]
  if tree[node]:
    child, coin = tree[node].pop()
    if child in d:
      if dist[child] < dist[node] + coin:
        dist[child] = float('inf')
        is_after = False
        for _node in d:
          if is_after:
            dist[_node] = float('inf')
            continue
          if _node == child:
            is_after = True            
    else:
      dist[child] = max(dist[child], dist[node] + coin)
      d.append(child)
  else:
    d.pop()

if dist[-1] < float('inf'):
  ans = max(0, dist[-1])
else:
  ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
tree = dict(zip(range(N), [[] for i in range(N)]))

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


dist = [-float('inf')]*N
dist[0] = 0
d = [0]
while d:
  node = d[-1]
  if tree[node]:
    child, coin = tree[node].pop()
    if child in d:
      if dist[child] < dist[node] + coin:
        dist[child] = float('inf')
        is_after = False
        for _node in d:
          if is_after:
            dist[_node] = float('inf')
            continue
          if _node == child:
            is_after = True            
    else:
      dist[child] = max(dist[child], dist[node] + coin)
      d.append(child)
  else:
    d.pop()

if dist[-1] < float('inf'):
  ans = max(0, dist[-1])
else:
  ans = -1

print(dist)
print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
tree = dict(zip(range(N), [[] for i in range(N)]))

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


dist = [-float('inf')]*N
dist[0] = 0
d = [0]
while d:
  node = d[-1]
  if tree[node]:
    child, coin = tree[node].pop()
    if child in d:
      if dist[child] < dist[node] + coin:
        dist[child] = float('inf')
    else:
      dist[child] = max(dist[child], dist[node] + coin)
      d.append(child)
  else:
    d.pop()

if dist[-1] < float('inf'):
  ans = max(0, dist[-1])
else:
  ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
def bell(edges, n, p):
    count = 0
    dist = [float('inf') for i in range(n)]
    dist[0] = 0
 
 
    for i in range(n):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2] + p and edge[0] != float('inf'):
                if  dist[edge[0]] + edge[2] + p < 0:
                    dist[edge[1]] = dist[edge[0]] + edge[2] + p
                else:
                    dist[edge[1]] = 0
                if (i == n - 1) & (edge[1] == n - 1):
                    print('-1')
                    exit()
                
    return dist
 
 
n,m,p = map(int,input().split())
edges = []
for _ in range(m):
    a, b, c = (int(x) for x in input().split())
    edges.append([a-1, b-1, -c])
 
res = bell(edges, n, p)
 
print(-res[-1])

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
for i in range(2*N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dist[t]>dist[f]+c:
      if i>N:
        flag = True
        break
      dist[t] = dist[f]+c
  if flag:
    break
dics = [float('inf')]*N
dics[N-1] = 0
for i in range(2*N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dics[t]>dics[f]+c:
      dics[t] = dics[f]+c
      if i>N:
        flag = True
        break
  if flag:
    print(-1)
    break
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
flag = False
for i in range(3*N+100):
  for j in range(M):
    f, t, c = es[j]
    if dist[t]>dist[f]+c:
      if i>N and t==N-1:
        flag = True
      dist[t] = dist[f]+c
if flag:
  print(-1)
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
flag = False
for i in range(2*N+100):
  for j in range(M):
    f, t, c = es[j]
    if dist[t]>dist[f]+c:
      if i>N and t==N-1:
        flag = True
      dist[t] = dist[f]+c
if flag:
  print(-1)
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
flag = False
for i in range(2*N+100):
  for j in range(M):
    f, t, c = es[j]
    if dist[t]>dist[f]+c:
      if i==N and t==N-1:
        flag = True
      dist[t] = dist[f]+c
if flag:
  print(-1)
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
for i in range(2*N+100):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dist[t]>dist[f]+c:
      if i==N and t==N-1:
        flag = True
      dist[t] = dist[f]+c
if flag:
  print(-1)
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
for i in range(N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dist[f]!=float('inf') and dist[t]>dist[f]+c:
      if i==N:
        flag = True
        break
      dist[t] = dist[f]+c
  if flag:
    break
dics = [float('inf')]*N
dics[N-1] = 0
for i in range(N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dist[t]!=float('inf') and dics[t]>dics[f]+c:
      dics[t] = dics[f]+c
      if i==N:
        flag = True
        break
  if flag:
    print(-1)
    break
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
cnt = 0
while True:
  if cnt == N+20:
    break
  update = True
  for i in range(M):
    a, b, c = es[i]
    if dist[a]!=float('inf') and dist[b]>dist[a] + c:
      dist[b] = dist[a]+c
      update = False
  if update:
    break
  cnt += 1
cnt = 0
dics = [float('inf')]*N
dics[N-1] = 0
ans = True
while True:
  if cnt == N+20:
    print(-1)
    ans = False
    break
  update = True
  for i in range(M):
    a, b, c = es[i]
    if dics[a]!=float('inf') and dics[b]>dics[a]+c:
      dics[b] = dics[a]+c
      update = False
  if update:
    break
  cnt += 1

if ans:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
cnt = 0
while True:
  if cnt == N:
    break
  update = True
  for i in range(M):
    a, b, c = es[i]
    if dist[a]!=float('inf') and dist[b]>dist[a] + c:
      dist[b] = dist[a]+c
      update = False
  if update:
    break
  cnt += 1
cnt = 0
dics = [float('inf')]*N
dics[N-1] = 0
ans = True
while True:
  if cnt == N:
    print(-1)
    ans = False
    break
  update = True
  for i in range(M):
    a, b, c = es[i]
    if dics[a]!=float('inf') and dics[b]>dics[a]+c:
      dics[b] = dics[a]+c
      update = False
  if update:
    break
  cnt += 1

if ans:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

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

dist = [float('inf')]*N
dist[0] = 0
for i in range(N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dist[t]>dist[f]+c:
      if i==N-1:
        flag = True
        break
      dist[t] = dist[f]+c
  if flag:
    break
dics = [float('inf')]*N
dics[N-1] = 0
for i in range(N):
  for j in range(M):
    f, t, c = es[j]
    flag = False
    if dics[t]>dics[f]+c:
      dics[t] = dics[f]+c
      if i==N-1:
        flag = True
        break
  if flag:
    print(-1)
    break
else:
  print(max(0,-dist[N-1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	#edgesは有向グラフの辺集合で辺は(始点,終点,コスト)
  #グラフの初期化
  dist=[inf for i in range(n)]
  dist[s]=0
  
  #辺の緩和
  for i in range(n+10000):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n+5000: dist[v]=inf
        update = True
  return dist
  #   if i==n-2: data=dist[n-1]
  # return -1 if dist[n-1] < data else dist

dist = BellmanFord(E,n,0)
if dist == inf:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	#edgesは有向グラフの辺集合で辺は(始点,終点,コスト)
  #グラフの初期化
  dist=[inf for i in range(n)]
  dist[s]=0
  
  #辺の緩和
  for i in range(n+10000):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n+5000: dist[v]=inf
        update = True
    if i==n-2: data=dist[n-1]
  return -1 if dist[n-1] < data else dist

dist = BellmanFord(E,n,0)
if dist == -1:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	#edgesは有向グラフの辺集合で辺は(始点,終点,コスト)
  #グラフの初期化
  dist=[inf for i in range(n)]
  dist[s]=0
  
  #辺の緩和
  for i in range(n+10000):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        update = True
    if i==n-2: data=dist[n-1]
  return -1 if dist[n-1] < data else dist

dist = BellmanFord(E,n,0)
if dist == -1:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	#edgesは有向グラフの辺集合で辺は(始点,終点,コスト)
  #グラフの初期化
  dist=[inf for i in range(n)]
  dist[s]=0
  
  #辺の緩和
  for i in range(n+5010):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        update = True
    if i==n-2: data=dist[n-1]
  return -1 if dist[n-1] < data else dist

dist = BellmanFord(E,n,0)
if dist == -1:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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

def BellmanFord(edges,n,s):
	#edgesは有向グラフの辺集合で辺は(始点,終点,コスト)
  #グラフの初期化
  dist=[inf for i in range(n)]
  dist[s]=0
  
  #辺の緩和
  for i in range(2*n):
    update = False
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        update = True
    if i==n-2: data=dist[n-1]
  return -1 if dist[n-1] < data else dist

dist = BellmanFord(E,n,0)
if dist == -1:
	print(-1)
else:
	print(max(0,-dist[n-1]))

Submission status: Wrong Answer

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

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

for i in range(2 * N):
    for fr, to, cost in Edges:
        if (dist[fr] != float('inf')) and (dist[to] > dist[fr] + cost):
            dist[to] = dist[fr] + cost
            if (i == N - 1) & (to == N - 1):
                dist[to] = -float('inf')

print(max(0, -dist[N - 1]) if -dist[N - 1] != float('inf') else -1)

Submission status: Wrong Answer

Solution code:
INF = 10 ** 10
N, M, P = map(int, input().split())
edge = []
edge_self = [0] * N
for i in range(M):
    a, b, c = map(int, input().split())
    if a != b:
        edge.append((a - 1, b - 1, c - P))
    elif a == b and c - P > 0:
        edge_self[a - 1] = 1


d = [-INF] * N
pre = [-1] * N
d[0] = 0
pre[0] = 0

for i in range(N):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = d[a] + c
            pre[b] = a
            if i == N - 1:
                print(-1)
                exit()


path = [0] * N
i = N - 1
path[i] = 1
isLoop = 0 if edge_self[i] == 0 else 1
while i != 0:
    i = pre[i]
    path[i] = 1
    isLoop |= edge_self[i]

if isLoop:
    print(-1)
else:
    print(max(0, d[N - 1]))

Submission status: Wrong Answer

Solution code:
INF = 10 ** 10
N, M, P = map(int, input().split())
edge = []
edge_self = [0] * N
for i in range(M):
    a, b, c = map(int, input().split())
    if a != b:
        edge.append((a - 1, b - 1, c - P))
    elif a == b and c > 0:
        edge_self[a - 1] = 1


d = [-INF] * N
pre = [-1] * N
d[0] = 0
pre[0] = 0

for i in range(N):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = d[a] + c
            pre[b] = a
            if i == N - 1:
                print(-1)
                exit()


path = [0] * N
i = N - 1
path[i] = 1
isLoop = 0 if edge_self[i] == 0 else 1
while i != 0:
    i = pre[i]
    path[i] = 1
    isLoop |= edge_self[i]

if isLoop:
    print(-1)
else:
    print(max(0, d[N - 1]))

Submission status: Wrong Answer

Solution code:
INF = 10 ** 10
N, M, P = map(int, input().split())
edge = []
for i in range(M):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c - P))

d = [-INF] * N
pre = [-1] * N
d[0] = 0
pre[0] = 0

for i in range(N):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = d[a] + c
            pre[b] = a
            if i == N - 1:
                print(-1)
                exit()


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

Submission status: Wrong Answer

Solution code:
INF = 10 ** 10
N, M, P = map(int, input().split())
edge = []
for i in range(M):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c - P))

d = [-INF] * N
pre = [-1] * N
d[0] = 0
pre[0] = 0

for i in range(N):
    for a, b, c in edge:
        if d[a] != -INF and d[b] < d[a] + c:
            d[b] = d[a] + c
            pre[b] = a


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

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def dfs1(n):
    global N
    isGoal = False
    score = -INF
    for ne, c in edge[n]:
        if ne == N - 1:
            path[ne] = 1
            isGoal |= True
            score = max(score, c)
        elif status[ne] == 0:
            status[ne] = 1
            isGoal_, score_ = dfs1(ne)
            isGoal |= isGoal_
            score = max(score, score_)
    if isGoal:
        path[n] = 1
    return isGoal, score


def dfs2(n, goal, score):
    rst = True
    for ne, c in edge[n]:
        if ne == goal and score + c > 0:
            rst &= False
        elif status[ne] == 0:
            status[ne] = 1
            rst &= dfs2(ne, goal, score + c)
    return rst


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

status = [0] * N
path = [0] * N
isGoal, score = dfs1(0)

if isGoal:
    for n in [idx for idx, x in enumerate(path) if x]:
        status = [0] * N
        status[n] = 1
        if not dfs2(n, n, 0):
            print(-1)
            exit()
    print(max(0, score))
else:
    print(-1)