Problem:


Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Wrong Answer

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

def main():
    N,M,P = map(int,input().split())
    edges = []


    for _ in range(M):
        A,B,C = map(int,input().split())
        edges.append([A-1,B-1,P-C])

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N-1):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
    ans = -1*dist[N-1]
    
    for i in range(N-1):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]]+edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
    ans2 = -1*dist[N-1]

    if ans2<=ans: 
        print(ans)                
    else:
        print(-1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#単一始点最短経路問題
#負の辺があっても動作する

#最短経路を求める
#計算量O(N * M)

INF = 10 ** 9
#入力
# N = int(input()) #頂点の数
# M = int(input()) #辺の数
N, M, P = map(int, input().split())

# 入力は1-index
# 内部で0-indexにして処理
G = []
for _ in range(M): #M個の辺の情報を受け取る
    l, r, s = map(int, input().split()) #lからrへ重みsの辺が存在
    G += [[l-1, r-1, -(s-P)]] #有向グラフのときはここだけ
    # G += [[r-1, l-1, s]] #無向グラフのときはこの行も必要


#メイン文
d = [0] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                prev[e[1]] = e[0]
        if not update: #更新が終わったとき
            return True
        if count == N: #永遠に更新が起きているとき
            tmp = d[N -1]
        if count == N + 2:
            if d[N - 1] == tmp:
                return True #N-1の値が更新されていないとき
            else:
                return False

#呼び出しスタート地点を入れる
if not shortest_path(1):
    print (-1)
    # print (d)
    exit()
# print (d)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque

def main():
    n, m, p = map(int, input().split())
    edge = defaultdict(list)

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

    score = [0, 0] + [float("-inf")] * (n - 1)

    q = deque()
    q.append((1, {1}))

    while q:
        curr, visited = q.popleft()
        for b, c in edge[curr]:
            if b in visited:
                if score[curr] + c > score[b]:
                    score[curr] = float("inf")
                    if score[b] != float("inf"):
                        score[b] = float("inf")
                        q.append((b, visited))
            else:
                score[b] = max(score[b], score[curr] + c)
                q.append((b, visited | {b}))

    print(max(0, score[n]) if score[n] != float("inf") else -1)


main()

Submission status: Wrong Answer

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


class MaxHeap(object):
    def __init__(self, x):
        self.heap = [-e for e in x]
        heapq.heapify(self.heap)

    def push(self, value):
        a, b = value
        heapq.heappush(self.heap, (-a, b))

    def pop(self):
        a, b = heapq.heappop(self.heap)
        return -a, b

    def __len__(self):
        return len(self.heap)


# 有効グラフを仮定する。
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 LongestPath(g: Graph, s: int):
    """ グラフgにおいて、始点sから各頂点への最長路
    引数
    g: グラフ, s: 始点
    返り値
    dist: 始点からの距離が格納されたリスト
    prev: 始点から最長経路で移動する場合、各頂点に至る前の頂点のリスト
    """
    dist = [INF]*g.N
    dist[s] = 0

    prev = [None]*g.N
    Q = MaxHeap([])
    Q.push((dist[s], s))
    visited = [False]*g.N
    visited[s] = True

    while len(Q) > 0:
        print(Q.heap)
        _, u = Q.pop()
        visited[u] = True
        for v, w in g.E[u]:
            if dist[v] == INF and dist[u] == INF:
                continue
            if visited[v]:
                dist[v] = INF
                prev[v] = u
                Q.push((dist[v], v))

            if dist[v] < dist[u] + w:
                dist[v] = dist[u] + w
                prev[v] = u
                Q.push((dist[v], v))
    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

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

    longest = [0]*N
    visited = [False]*N
    q = MaxHeap([])
    q.push([0, 0])
    while len(q) > 0:
        node, dist = q.pop()
        visited[node] = True
        for to_, coin in g.E[node]:
            if visited[to_] is False:
                longest[to_] = dist+coin
                q.push([to_, dist+coin])
            else:
                if longest[to_] < dist+coin:
                    longest[to_] = INF

    if longest[N-1] == INF:
        print(-1)
    else:
        print(max(longest[N-1], 0))
    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:
N, M, P = map(int, input().split())
edges = []
for i in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, P - C])


def BellmanFord(edges, num_v, source):
    minus_flag = 0
    # グラフの初期化
    inf = float("inf")
    dist = [inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    for i in range(num_v + 1):
        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:
                    minus_flag = 1

    if minus_flag == 0:
        return dist
    else:
        dist.append(-1)
        return dist


ans = BellmanFord(edges, N, 1)
if ans[N-1] >= 0:
    print(0)
elif len(ans) != N:
    print(-1)
else:
    print(ans[-1] * (-1))

Submission status: Wrong Answer

Solution code:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


class Graph:
    """
    隣接リストによる有向グラフ
    """
    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()

def main():
    n, m, p = map(int, input().split())
    graph = defaultdict(list)
    coins = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a-1].append(b-1)
        coins[(a-1,b-1)] = c

    scores = [0] * n
    que = deque()
    que.append((0, 0))
    for _ in range(n):
        next_que = deque()
        while que:
            node, move = que.popleft()
            next_move = move + 1
            for next_node in graph[node]:
                scores[next_node] = max(scores[next_node], scores[node] + coins[(node, next_node)] - next_move * p)
                next_que.append((next_node, next_move))

        que = next_que

    ans = scores[n-1]

    # N の閉路がないか
    scores = [0] * n
    que = deque()
    que.append((n-1, 0))
    for _ in range(n):
        next_que = deque()
        while que:
            node, move = que.popleft()
            next_move = move + 1
            for next_node in graph[node]:
                scores[next_node] = max(scores[next_node], scores[node] + coins[(node, next_node)] - next_move * p)
                next_que.append((next_node, next_move))

    print(-1 if scores[n-1] > 0 else ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
for i in range(m):
    #if info[i][0] == info[i][1]:
    #    continue
    graph[info[i][0] - 1].append((info[i][1] - 1, info[i][2]))

can_goal = [False] * n
can_goal[n-1] = True

def bfs1(start):
    q = deque([start])
    visited = [False] * n
    visited[start] = True
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            else:
                visited[i] = True
                q.append(i)
    return visited
visited_from_start = bfs1(0)
                

def bfs2(start):
    if can_goal[start]:
        return
    q = deque([start])
    visited = [False] * n
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            if can_goal[i]:
                can_goal[start] = True
            else:
                visited[i] = True
                q.append(i)

for i in range(n)[::-1]:
    if visited_from_start[i]:
        bfs2(i)
# print(can_goal)


def bfs3(start):
    q = deque([(start, -1, 0, 0)])
    money = [0] * n
    time = [0] * n
    prev_pos_memo = {}
    while q:
        pos, prev_pos, t, mon = q.popleft()
        for next_pos, next_mon in graph[pos]:
            if not can_goal[next_pos]:
                continue
            if next_pos in prev_pos_memo:
                if pos in prev_pos_memo[next_pos]:
                    if (mon + next_mon) - (t+1)*p > money[next_pos] - time[next_pos]*p:
                        return -1
                        exit()
                    else:
                        continue
                else:
                    prev_pos_memo[next_pos][pos] = 1
            else:
                prev_pos_memo[pos] = {}
                prev_pos_memo[pos][prev_pos] = 1
            if (mon + next_mon) - (t+1)*p > money[next_pos] - time[next_pos]*p:
                time[next_pos] = t + 1
                money[next_pos] = mon + next_mon
                q.append((next_pos, pos, t+1, mon + next_mon))
    return money[n-1] - time[n-1]*p

print(bfs3(0))

Submission status: Wrong Answer

Solution code:
inf = 10 ** 18
n, m, p = map(int, input().split())
edge = []
d = [inf] * n
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = p - c
    edge.append((a, b, c))
d[0] = 0
for i in range(n-1):
    pre = d[n-1]
    update = False
    for a, b, c in edge:
        if (d[a] != inf and d[b] > d[a] + c):
            d[b] = d[a] + c
            update = True
    if not update:
        break

pre = d[n-1]
for a, b, c in edge:
    if (d[a] != inf and d[b] > d[a] + c):
        d[b] = d[a] + c

if pre != d[n-1]:
    print(-1)
else:
    print(max(0, -d[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())
    edges.append([A, B, P - C])


def BellmanFord(edges, num_v, source):
    minus_flag = 0
    # グラフの初期化
    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:
                    minus_flag = 1

    if minus_flag == 0:
        return dist
    else:
        dist.append(-1)
        return dist


ans = BellmanFord(edges, N, 1)
if ans[N-1] >= 0:
    print(0)
elif len(ans) != N:
    print(-1)
else:
    print(ans[-1] * (-1))

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline

def main():
    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,P-C])

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N-1):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
    ans = -1*dist[N-1]

    for edge in edges:
        if dist[edge[1]] > dist[edge[0]] + edge[2]:
            dist[edge[1]] = dist[edge[0]]+edge[2]
    ans2 = -1*dist[N-1]
    if ans==ans2:
        print(max(0,-1*dist[N-1]))
    else:
        print(-1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


from heapq import heappush, heappop


def dijkstra(graph: list, start, INF=float('inf')) -> list:
    n = len(graph)
    dist = [INF] * n
    visited = [False] * n

    dist[start] = 0
    que = [(0, start)]

    while que:
        cost, cur = heappop(que)

        if visited[cur]:
            continue

        visited[cur] = True

        for nextnode, edgecost in graph[cur]:
            nextcost = cost + edgecost
            if nextcost < dist[nextnode]:
                dist[nextnode] = nextcost
                heappush(que, (nextcost, nextnode))

    return dist

n, m, p = li()

# グラフを作る
graph = [[] for _ in range(n)]
for _ in range(m):
    ai, bi, ci = li()
    ai -= 1
    bi -= 1
    graph[ai].append((bi, ci - p))

# 1から到達可能な点のみ抽出
reach = dijkstra(graph, 0)

reachable = set()
for i in range(n):
    if reach[i] != float('inf'):
        reachable.add(i)

INF = float('inf')
dist = [[-INF]*n for _ in range(n+1)]
dist[0][0] = 0
for i in range(n):
    for j in range(n):
        if not j in reachable:
            continue

        dist[i+1][j] = dist[i][j]

    for j in range(n):
        if not j in reachable:
            continue
        for (k, cost) in graph[j]:
            if not k in reachable:
                continue

            dist[i+1][k] = max(dist[i+1][k], dist[i][j] + cost)

if dist[n-1][-1] < dist[n][-1]:
    print(-1)
else:
    print(max(0, dist[n-1][-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]:
            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)
if di=='neg':
    print(-1)
else:
    print(max(0,-di[n-1]))

Submission status: Wrong Answer

Solution code:
import heapq
INF = 10**18
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update >= n:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 0))
G_rev = defaultdict(lambda: defaultdict(lambda: 0))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = C
    G_rev[B][A] = 1

reachable = [0] * (N + 1)
reachable[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable[q] == 0:
            reachable[q] = 1
            queue.append(q)

# print(reachable)

max_score = [-10000000000] * (N + 1)
res = 0
max_score[1] = 0
queue = deque([1])
cnt = 0
while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if not reachable[q]:
            continue
        if max_score[p] + G[p][q] - P > max_score[q]:
            max_score[q] = max_score[p] + G[p][q] - P
            queue.append(q)
            cnt += 1
    if cnt > 3000000:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, max_score[N]))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque

def main():
    n, m, p = map(int, input().split())
    edge = defaultdict(list)

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

    score = [0, 0] + [float("-inf")] * (n - 1)

    q = deque()
    q.append((1, {1}))

    while q:
        curr, visited = q.popleft()
        for b, c in edge[curr]:
            if b in visited:
                if score[curr] + c > score[b]:
                    score[curr] = float("inf")
                    for bb, cc in edge[curr]:
                        score[bb] = float("inf")
            else:
                score[b] = max(score[b], score[curr] + c)
                visited.add(b)
                q.append((b, visited))

    print(max(0, score[n]) if score[n] != float("inf") else -1)


main()

Submission status: Wrong Answer

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

# ベルマンフォード
dist = [float('inf')] * N
dist[0] = 0

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

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

Submission status: Wrong Answer

Solution code:
import sys


def solve(N, M, P, A, B, C):
    INF = float("inf")

    edges = []
    for a, b, c in zip(A, B, C):
        edges.append((a, b, P - c))

    prev = [-1] * (1 + N)

    cost = [INF] * (1 + N)
    cost[1] = 0

    infloop = True
    for _ in range(N):
        update = False
        for a, b, c in edges:
            if cost[a] != INF and cost[b] > cost[a] + c:
                update = True
                cost[b] = cost[a] + c
                prev[b] = a
        if not update:
            infloop = False
            break

    if infloop:
        v = N
        for _ in range(N + 1):
            v = prev[v]
            if v == 1:
                break
        else:
            return -1

    return max(0, -cost[N])


# -----------------------------------------------------------------------------
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))

    ans = solve(N, M, P, A, B, C)
    if ans is not None:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M,P=map(int,input().split())
A=[0 for i in range(M)]
B=[0 for i in range(M)]
C=[0 for i in range(M)]
G=[dict() for i in range(N)]
H=[dict() for i in range(N)]
for i in range(M):
    A[i],B[i],C[i]=map(int,input().split())
    G[B[i]-1][A[i]-1]=C[i]
    H[A[i]-1][B[i]-1]=C[i]
reached1=[0 for i in range(N)]
q=deque([N-1])
while(len(q)>0):
    r=q.popleft()
    reached1[r]=1
    for p in G[r]:
        if reached1[p]==0:
            q.append(p)
reached2=[0 for i in range(N)]
q=deque([0])
while(len(q)>0):
    r=q.popleft()
    reached2[r]=1
    for p in H[r]:
        if reached2[p]==0:
            q.append(p)
reached=[reached1[i]*reached2[i] for i in range(N)]
vertex_list=[]
vertex_num=[0 for i in range(N)]
tmp=1
for i in range(N):
    if reached[i]==1:
        vertex_list.append(i+1)
        vertex_num[i]=tmp
        tmp+=1
num_v=len(vertex_list)
edges=[]
for i in range(M):
    if reached[A[i]-1]==1 and reached[B[i]-1]==1:
        edges.append((vertex_num[A[i]-1],vertex_num[B[i]-1],P-C[i]))
inf=10**6
dist=[inf for i in range(num_v)]
dist[0]=0
#print(reached)
#print(edges)
#print(vertex_list)
#print(vertex_num)
#辺の緩和
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:
                print(-1)
                exit()
print(max(-dist[-1],0))

Submission status: Wrong Answer

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

N,M,P=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(M)]

for i in range(M):
    EDGE[i][2]-=P

ELIST=[[] for i in range(N+1)]
ELIST_rev=[[] for i in range(N+1)]

for a,b,p in EDGE:
    ELIST[a].append([b,p])
    ELIST_rev[b].append(a)


from collections import deque

CANREACH=[0]*(N+1)
CANREACH[N]=1

Q=deque([N])

while Q:
    x=Q.pop()

    for to in ELIST_rev[x]:
        if CANREACH[to]==0:
            CANREACH[to]=1
            Q.append(to)

Q=deque([1])

ANS=[-float("inf")]*(N+1)
ANS[1]=0
count=0

while Q:
    x=Q.pop()
    count+=1

    for to,p in ELIST[x]:
        if CANREACH[to]==0:
            continue
        if ANS[to]<ANS[x]+p:
            if count>7*10**6:
                ANS[to]=float("inf")
            else:
                ANS[to]=ANS[x]+p
                Q.appendleft(to)

if ANS[N]==float("inf"):
    print(-1)
else:
    print(max(ANS[N],0))

Submission status: Wrong Answer

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

import numpy as np
from scipy.sparse.csgraph import bellman_ford, csgraph_from_dense, connected_components

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]

mat = np.full((N+1,N+1), np.inf)
for a,b,c in ABC:
    mat[a][b] = P - c

mat[N][1] = 1
_,comp = connected_components(mat, connection='strong')
mat[N][1] = np.inf
select = (comp == comp[1])

mat = mat[select][:,select]
try:
    dist = bellman_ford(csgraph_from_dense(mat, null_value = np.inf), indices=0)
    answer = int(.5-dist[-1])
    if answer < 0:
        answer = 0
except:
    answer = -1
print(answer)

Submission status: Wrong Answer

Solution code:
n,m,r=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]

g=[[] for _ in [0]*n]
[g[a-1].append([b-1,c]) for a,b,c in abc]

dist=[-10**15 for _ in [0]*n]
dist[0]=0
a,b=-10**15,-10**15

for _ in range(n):
    for p in range(n):
        for i,j in g[p]:
            dist[i]=max(dist[i],dist[p]+j)
    a,b=b,dist[n-1]

if a==b:
    ans=0
    loop=set()
    d=[-10**15 for _ in [0]*n]
    d[0]=0
    q=[[0,1]]
    s=set()
    l=[]
    cnt=0
    while q:
        cnt+=1
        qq=[]
        for q_item in q:
            item,depth=q_item
            if depth<=len(s):
                for _ in range(len(s)-depth+1):
                    rmv=l.pop()
                    s.remove(rmv)
            l.append(item)
            s.add(item)
            for i,dist in g[item]:
                if d[i]<d[item]+dist:
                    if i in s:
                        loop.add(i)
                        continue
                    d[i]=d[item]+dist
                    qq.append([i,depth+1])
        ans=max(ans,d[n-1]-cnt*r)
        q=qq
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

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

Edgeinv = [[] for _ in range(N+1)]
Edge = [[] for _ in range(N+1)]
inf = 2*10**10
Edgenum = [tuple(map(int, sys.stdin.readline().split())) for _ in range(M)]
for a, b, c in Edgenum:
    Edgeinv[b].append(a)
    Edge[a].append(b)

used = set([N])
stack = [N]
while stack:
    vn = stack.pop()
    for vf in Edgeinv[vn]:
        if vf not in used:
            used.add(vf)
            stack.append(vf)

used2 = set([1])
stack = [1]
while stack:
    vn = stack.pop()
    for vf in Edge[vn]:
        if vf not in used2:
            used2.add(vf)
            stack.append(vf)

used &= used2

dp = [-inf]*(N+1)
dp[1] = 0
for i in range(N-1):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp = [max(0, d) for d in dp]
for i in range(N):
    dp2 = dp[:]
    for a, b, c in Edgenum:
        dp2[b] = max(dp2[b], dp[a] + c - P)
    dp = dp2[:]

Dp2 = [max(0, d) for d in dp]
if any(Dp[i] < Dp2[i] for i in used):
    print(-1)
else:
    print(Dp[N])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 0))
G_rev = defaultdict(lambda: defaultdict(lambda: 0))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = C
    G_rev[B][A] = 1

reachable = [0] * (N + 1)
reachable[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable[q] == 0:
            reachable[q] = 1
            queue.append(q)

# print(reachable)

max_score = [-1000000000] * (N + 1)
res = 0
max_score[1] = 0
queue = deque([1])
cnt = 0
while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if not reachable[q]:
            continue
        if max_score[p] + G[p][q] - P > max_score[q]:
            max_score[q] = max_score[p] + G[p][q] - P
            queue.append(q)
            cnt += 1
    if cnt > 1000000:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, max_score[N]))