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 collections import defaultdict

inf = 10 ** 9
to = defaultdict(list)
fr = defaultdict(list)
n, m, p = map(int, input().split())
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append([b, c])
    fr[b].append([a, c])
dp = [[-inf] * n for _ in range(2 * n)]
dp[0][0] = 0
for i in range(1, n+2):
    for node in range(n):
        if fr[node]:
            dp[i][node] = max(c + dp[i - 1][k] for k, c in fr[node])
#print(dp)
if dp[-1][-1]>0:
    print(-1)
else:
    print(max(0,max(k[-1] - p * i for i, k in enumerate(dp))))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*M]

Ef = [{} for _ in [0]*N]
Eb = [{} for _ in [0]*N]

for a,b,c in ABC:
    Ef[a-1][b-1] = P-c
    Eb[b-1][a-1] = P-c

#pre process

d = [-1]*N
d[0] = 0
q = [0]
while q:
    i = q.pop()
    di = d[i]
    for j in Ef[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Ef[i]:
        Eb[j].pop(i)
    Ef[i] = {}

d = [-1]*N
d[N-1] = 0
q = [N-1]
while q:
    i = q.pop()
    di = d[i]
    for j in Eb[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Eb[i]:
        Ef[j].pop(i)
    Eb[i] = {}

#main process
ans = 0
d = [None]*N
d[0] = 0
for _ in [0]*N:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

ans = d[-1]
check = d[:]

#check
for _ in [0]:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

#if check!=d: ans = -1
#else: ans = -min(0,ans)

ans = -1
print(ans)

Submission status: Wrong Answer

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

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

abc = [tuple(map(int, input().split())) for _ in range(m)]

data, row_ind, col_ind = [], [], []
for a, b, c in abc:
    data.append(0)
    row_ind.append(a - 1)
    col_ind.append(b - 1)

g = csr_matrix((data, (row_ind, col_ind)), shape=(n, n))

dist_matrix = bellman_ford(g)

ignores = []
for i in range(n):
    if (dist_matrix[0, i] == float("inf")) | (dist_matrix[i, -1] == float("inf")):
        ignores.append(i)
ignores = set(ignores)

data, row_ind, col_ind = [], [], []
for a, b, c in abc:
    if (a - 1 not in ignores) & (b - 1 not in ignores):
        data.append(p - c)
        row_ind.append(a - 1)
        col_ind.append(b - 1)

g = csr_matrix((data, (row_ind, col_ind)), shape=(n, n))

try:
    dist_matrix = bellman_ford(g, indices=[0])
    ans = max(0, -int(dist_matrix[0][-1]))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*M]

Ef = [{} for _ in [0]*N]
Eb = [{} for _ in [0]*N]

for a,b,c in ABC:
    Ef[a-1][b-1] = P-c
    Eb[b-1][a-1] = P-c

#pre process

d = [-1]*N
d[0] = 0
q = [0]
while q:
    i = q.pop()
    di = d[i]
    for j in Ef[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Ef[i]:
        Eb[j].pop(i)
    Ef[i] = {}

d = [-1]*N
d[N-1] = 0
q = [N-1]
while q:
    i = q.pop()
    di = d[i]
    for j in Eb[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Eb[i]:
        Ef[j].pop(i)
    Eb[i] = {}

#main process
ans = 0
d = [None]*N
d[0] = 0
for _ in [0]*N:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

ans = d[-1]
check = d[:]

#check
for _ in [0]:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

if check!=d: ans = -1
else: ans = -min(0,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]
d=[float("inf")]*n
d[0]=0
def f(d):
  for _ in range(n):
    for i in range(m):
      e0,e1,e2=edge[i]
      d[e1]=min(d[e1],d[e0]+e2)
  return d[-1]
ans1=f(d)
ans2=f(d)
print(-1 if ans1!=ans2 else max(0,-ans2))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*M]

Ef = [{} for _ in [0]*N]
Eb = [{} for _ in [0]*N]

for a,b,c in ABC:
    Ef[a-1][b-1] = P-c
    Eb[b-1][a-1] = P-c

#pre process

d = [-1]*N
d[0] = 0
q = [0]
while q:
    i = q.pop()
    di = d[i]
    for j in Ef[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Ef[i]:
        Eb[j].pop(i)
    Ef[i] = {}

d = [-1]*N
d[N-1] = 0
q = [N-1]
while q:
    i = q.pop()
    di = d[i]
    for j in Eb[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Eb[i]:
        Ef[j].pop(i)
    Eb[i] = {}

#main process
ans = 0
d = [None]*N
d[0] = 0
for _ in [0]*N:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

ans = d[-1]

#check
for _ in [0]:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

if ans != d[-1]: ans = -1
else: ans = -min(0,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]
d=[float("inf")]*n
d[0]=0
for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
      d[e1]=d[e0]+e2
ans1=d[-1]
for _ in range(n):
  for i in range(m):
    e0,e1,e2=edge[i]
    if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
      d[e1]=d[e0]+e2
ans2=d[-1]
print(-1 if ans1!=ans2 else max(0,-ans2))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import sys
input = sys.stdin.readline
inpl = lambda: list(map(int,input().split()))
INF = 10**12
N, M, P = inpl()
edges = [ [] for _ in range(N) ]
for i in range(M):
    a, b, c = inpl()
    a -= 1
    b -= 1
    edges[a].append([b,c-P])

cur = defaultdict(lambda: -INF)
cur[0] = 0
ans = [-INF, -INF]
for k in range(2):
    for i in range(N):
        prev = cur
        cur = defaultdict(lambda: -INF)
        for f in prev.keys():
            coin = prev[f]
            for t, v in edges[f]:
                cur[t] = max(cur[t], coin + v)
        if N-1 in cur:
            ans[k] = max(ans[k],cur[N-1])
if ans[1] > ans[0]:
    print(-1)
else:
    print(max(ans[0],0))

Submission status: Wrong Answer

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

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N*2):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1:
                d[to] = INF
            elif i == N*2-1 and to == N-1:
                print(-1)
                exit()

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

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
INF = float("inf")


# 有効グラフを仮定する。
class Graph(object):
    def __init__(self, N):
        self.N = N
        self.V = list(range(N))
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        """辺を加える。edgeは(始点, 終点、重み)からなるリスト
        重みがなければ、重み1とする。
        """
        if len(edge) == 2:
            edge.append(1)
        elif len(edge) != 3:
            print("error in add_edge")
            pass

        s, t, w = edge
        self.E[s].append([t, w])

        pass


def BellmanFord(g: Graph, s):
    """ベルマンフォード法による最短経路
    """
    N = g.N
    dist = [INF]*N
    dist[s] = 0
    prev = [None]*N

    # 辺の緩和
    for _ in range(N):
        for from_ in range(N):      # ここの２重ループはO(M)
            for to_, weight in g.E[from_]:
                if dist[to_] > dist[from_] + weight:
                    dist[to_] = dist[from_] + weight
                    prev[to_] = from_
    # 負の重みの閉路がないかチェック
    for from_ in range(N):
        for to_, weight in g.E[from_]:
            if dist[from_]+weight < dist[to_]:
                dist[from_] = -INF
                dist[to_] = -INF
    return dist, prev


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    for i in range(M):
        C[i] = P - C[i]

    g = Graph(N)
    for a, b, c in zip(A, B, C):
        g.add_edge([a-1, b-1, c])

    dist, prev = BellmanFord(g, 0)
    if -dist[-1] == INF:
        print(-1)
    else:
        print(max(-dist[-1], 0))

    # print(longest)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, P, A, B, C)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]

    for e in d:
        s, t = e
        if V[s] == None:
            continue
        if V[t] == None:
            V[t] = V[s] + d[e]
            continue
        if V[s] + d[e] < V[t]:
            V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = -10**14*2
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10**14:
        print(-1)
    else:
        print(max(-V[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    for i in range(N-1):
        if V[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = -10**14*2
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10**14:
        print(-1)
    else:
        print(max(-V[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]
    for _ in range(1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = -10**14*2
    for _ in range(1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10**14:
        print(-1)
    else:
        print(max(-V[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    INF = 10**14*2
    V = [INF]*N
    V[0] = 0
    for _ in range(N*2):
        for e in d:
            s, t = e
            if V[s] + d[e] < V[t]:
                if V[t] <= 10*14:
                    V[t] = -10*14
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10*14:
        print(-1)
    else:
        print(max(-V[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

n,m,p = map(int,input().split())
graph = [[] for _ in range(n)]
INF = float("inf")
dist = [INF]*n
dist[0] = 0

for _ in range(m):
	f,t,c = map(int,input().split())
	graph[f-1].append((t-1,p-c))
#print(graph)

for _ in range(n):
	update = False
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if not update:
		break
else:
	eff = deque()
	det = []
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				eff.append(f)
				det.append(f)
	while eff:
		v = eff.popleft()
		for u,c in graph[v]:
			if u not in det and c < 0:
				eff.append(u)
				det.append(u)
	if n-1 in det:
		print(-1)
		exit()
#print(dist)

print(max(0,dist[-1]*(-1)))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int,input().split())
graph = [[] for _ in range(n)]
INF = float("inf")
dist = [INF]*n
dist[0] = 0

for _ in range(m):
	f,t,c = map(int,input().split())
	graph[f-1].append((t-1,p-c))
#print(graph)

for _ in range(n):
	update = False
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if not update:
		break
else:
	prev = dist[-1]
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = -INF
	if dist[-1] != prev:
		print(-1)
		exit()
#print(dist)

print(max(0,dist[-1]*(-1)))

Submission status: Wrong Answer

Solution code:
def e_coins_respawn(N, M, P, Edges, INF=float('inf')):
    edges = [(a, b, P - c) for a, b, c in Edges]

    # ベルマン-フォード法
    dist = [INF] * N
    dist[0] = 0
    for i in range(N):
        for a, b, cost in edges:
            u, v, c = a - 1, b - 1, cost
            if dist[u] != INF and dist[u] + c < dist[v]:
                dist[v] = dist[u] + c
                if i == N - 1 and v == N - 1:
                    # この条件が満たされたとき、頂点1と頂点Nのパスの中に負閉路があった
                    # このループを使ってスコアをいくらでも大きくできる
                    return -1
    return max(-dist[-1], 0)

N, M, P = [int(i) for i in input().split()]
Edges = [[int(i) for i in input().split()] for j in range(M)]
print(e_coins_respawn(N, M, P, Edges))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int,input().split())
graph = [[] for _ in range(n)]
INF = float("inf")
dist = [INF]*n
dist[0] = 0

for _ in range(m):
	f,t,c = map(int,input().split())
	graph[f-1].append((t-1,p-c))
#print(graph)

for _ in range(2*n):
	update = False
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if not update:
		break
else:
	prev = dist[-1]
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
	if dist[-1] != prev:
		print(-1)
		exit()
#print(dist)

print(max(0,dist[-1]*(-1)))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
# keyword: BFS, Bellman-Ford, directed Graph
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] = -1 * (edge[2] - p)

start = 0
goal = n - 1

# dist: cost from start
dist = [float("inf")] * n
dist[start] = 0

# relaxing
negative_cycle = False

for i in range(n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
            if i == n - 1:
                negative_cycle = True

print(-1 if negative_cycle else max(-1 * dist[goal], 0))

Submission status: Wrong Answer

Solution code:
n,m,p = map(int,input().split())
graph = [[] for _ in range(n)]
INF = float("inf")
dist = [INF]*n
dist[0] = 0

for _ in range(m):
	f,t,c = map(int,input().split())
	graph[f-1].append((t-1,p-c))
#print(graph)

for _ in range(n):
	update = False
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if not update:
		break
else:
	prev = dist[-1]
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if dist[-1] != prev:
		print(-1)
		exit()
#print(dist)

print(max(0,dist[-1]*(-1)))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
# keyword: BFS, Bellman-Ford, directed Graph
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] = -1 * (edge[2] - p)

start = 0
goal = n - 1

# dist: cost from start
dist = [float("inf")] * n
dist[start] = 0

# relaxing
past_dist_goal = 0
negative_cycle = False

for i in range(2 * n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
    if i == 2 * n - 1 and dist[goal] != past_dist_goal:
        negative_cycle = True
    past_dist_goal = dist[goal]

print(-1 if negative_cycle else max(-1 * dist[goal], 0))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
# keyword: BFS, Bellman-Ford, directed Graph
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] = -1 * (edge[2] - p)

start = 0
goal = n - 1

# dist: cost from start
dist = [float("inf")] * n
dist[start] = 0

# relaxing
past_dist_goal = 0
negative_cycle = False
for i in range(2 * n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
    if i == 2 * n and dist[goal] != past_dist_goal:
        negative_cycle = True
    past_dist_goal = dist[goal]

print(-1 if negative_cycle else max(-1 * dist[goal], 0))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
# keyword: BFS, Bellman-Ford, directed Graph
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] = -1 * (edge[2] - p)

start = 0
goal = n - 1

# dist: cost from start
dist = [float("inf")] * n
dist[start] = 0

# breath first order
# cut edges
# reachable = [False] * n
# reachable[goal] = True
# d = deque()

# d.append(goal)
# reachable[goal] = True
# d.append(goal)
# reachable[goal] = True
# while len(d) > 0:
#     x = d.popleft()
#     for edge in edges:
#         if edge[1] == x and not reachable[edge[0]] and x != start:
#             d.append(edge[0])
#             reachable[edge[0]] = True

# cant_reach = []
# for i in range(n):
#     if not reachable[i]:
#         cant_reach.append(i)

# for edge in edges:
#     if edge[0] in cant_reach or edge[1] in cant_reach:
#         edge[2] = LARGE

# bellman-ford

# relaxing
past_dist_goal = 0
negative_cycle = False
for i in range(2 * n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
    if i == n - 1 and dist[goal] != past_dist_goal:
        negative_cycle = True
    past_dist_goal = dist[goal]

print(-1 if negative_cycle else max(-1 * dist[goal], 0))

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
# keyword: BFS, Bellman-Ford, directed Graph
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] = -1 * (edge[2] - p)

start = 0
goal = n - 1

# dist: cost from start
dist = [float("inf")] * n
dist[start] = 0

# breath first order
# cut edges
# reachable = [False] * n
# reachable[goal] = True
# d = deque()

# d.append(goal)
# reachable[goal] = True
# d.append(goal)
# reachable[goal] = True
# while len(d) > 0:
#     x = d.popleft()
#     for edge in edges:
#         if edge[1] == x and not reachable[edge[0]] and x != start:
#             d.append(edge[0])
#             reachable[edge[0]] = True

# cant_reach = []
# for i in range(n):
#     if not reachable[i]:
#         cant_reach.append(i)

# for edge in edges:
#     if edge[0] in cant_reach or edge[1] in cant_reach:
#         edge[2] = LARGE

# bellman-ford

# relaxing
past_dist_goal = 0
negative_cycle = False
for i in range(n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
    if i == n - 1 and dist[goal] != past_dist_goal:
        negative_cycle = True
    past_dist_goal = dist[goal]

print(-1 if negative_cycle else max(-1 * dist[goal], 0))

Submission status: Wrong Answer

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

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

ans = d[V-1]

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

if loop or ans==inf:
    print(-1)

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

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e
# created: 20190811
# author: machikane
from collections import deque

LARGE = 2 * 10 ** 9

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

# edge: from, to, cost
edges = [list(map(int, input().split())) for i in range(m)]
for edge in edges:
    edge[0] -= 1
    edge[1] -= 1
    edge[2] -= p

start = 0
goal = n - 1

# dist: cost from start
dist = [-float("inf")] * n
dist[start] = 0

# breath first order
# cut edges
reachable = [False] * n
reachable[goal] = True
d = deque()
d.append(goal)
reachable[goal] = True
while len(d) > 0:
    x = d.popleft()
    for edge in edges:
        if edge[1] == x and not reachable[edge[0]] and x != start:
            d.append(edge[0])
            reachable[edge[0]] = True

cant_reach = []
for i in range(n):
    if not reachable[i]:
        cant_reach.append(i)

for edge in edges:
    if edge[0] in cant_reach or edge[1] in cant_reach:
        edge[2] = -LARGE

# bellman-ford

# relaxing
negative_cycle = False
for i in range(n):
    # 各辺操作
    for edge in edges:
        if dist[edge[0]] != -float("inf") and dist[edge[1]] < dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]] + edge[2]
            if i == n - 1:
                negative_cycle = True

print(-1 if negative_cycle else max(dist[n - 1], 0))