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: Accepted

Solution code:
class Dijkstra():
    """ ダイクストラ法
    重み付きグラフにおける単一始点最短路アルゴリズム

    * 使用条件
        - 負のコストがないこと
        - 有向グラフ、無向グラフともにOK

    * 計算量はO(E*log(V))

    * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい
    """
    class Edge():
        """ 重み付き有向辺 """
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        """ 重み付き有向辺
        無向辺を表現したいときは、_fromと_toを逆にした有向辺を加えればよい

        Args:
            V(int): 頂点の数
        """
        self.G = [[] for i in range(V)]  # 隣接リストG[u][i] := 頂点uのi個目の隣接辺
        self._E = 0  # 辺の数
        self._V = V  # 頂点の数

    @property
    def E(self):
        """ 辺数
        無向グラフのときは、辺数は有向グラフの倍になる
        """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        """ 始点sから頂点iまでの最短路を格納したリストを返す
        Args:
            s(int): 始点s
        Returns:
            d(list): d[i] := 始点sから頂点iまでの最短コストを格納したリスト。
                     到達不可の場合、値はfloat("inf")
        """
        import heapq
        que = []  # プライオリティキュー（ヒープ木）
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))  # 始点の(最短距離, 頂点番号)をヒープに追加する

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する
                e = self.G[v][i]  # vのi個目の隣接辺e
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost  # dの更新
                    heapq.heappush(que, (d[e.to], e.to))  # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush
        return d

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: return -1

  return dist

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

use=set([N-1])
t=test.shortest_path(N-1)
for i in range(0,N-1):
    if t[i]!=10**15:
        use.add(i)

useedges=[]
for i in range(0,M):
    a,b,c=edges[i]
    if a-1 in use and b-1 in use:
        useedges.append(edges[i])

ans=BellmanFord(useedges,N,1)
if ans==-1:
    print(-1)
else:
    if -ans[N-1]>=0:
        print(-ans[N-1])
    else:
        print(0)

Submission status: Accepted

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


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

EDGES = []
TO = [[] for _ in range(N + 1)]
RTO = [[] for _ in range(N + 1)]

for _ in range(M):
    a, b, c = map(int, readline().split())
    EDGES.append((a, b, c))
    TO[a].append(b)
    RTO[b].append(a)

# 1から到達可能な点
REACH_FROM_1 = [False] * (N+1)
q = [1]
while q:
    u = q.pop()
    if REACH_FROM_1[u]:
        continue
    REACH_FROM_1[u] = True
    for v in TO[u]:
        q.append(v)

# Nから到達可能な点
REACH_TO_N = [False] * (N + 1)
q = [N]
while q:
    u = q.pop()
    if REACH_TO_N[u]:
        continue
    REACH_TO_N[u] = True
    for v in RTO[u]:
        q.append(v)

STATE = [REACH_FROM_1[i] & REACH_TO_N[i] for i in range(N + 1)]


INF = 10 ** 12
POINT = [INF] * (N + 1)

POINT[1] = 0

for i in range(N):
    update = False
    for j in range(M):
        a, b, c = EDGES[j]
        if not STATE[a]:
            continue
        pt = - (c - P)
        if POINT[a] != INF and POINT[a] + pt < POINT[b]:
            POINT[b] = POINT[a] + pt
            update = True

            if i == N-1:
                print(-1)
                exit()

    if not update:
        break

# print(POINT)
pt = -POINT[N]

ans = pt if pt > 0 else 0
print(ans)

Submission status: Accepted

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
# 終了時、T*P枚支払う
graph = [tuple(lr()) for _ in range(M)]

def bellmanford(start, N):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(N+N+5):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # n回繰り返してもスコアが更新された場合
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Submission status: Accepted

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
# 終了時、T*P枚支払う
graph = [lr() for _ in range(M)]

def bellmanford(start, N):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(N+N+5):
        for pre, ne, weight in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # n回繰り返してもスコアが更新された場合
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(1, N)
print(answer)

Submission status: Accepted

Solution code:
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
# 終了時、T*P枚支払う
graph = []
for _ in range(M):
    a, b, c = lr()
    graph.append((a, b, c))

def bellmanford(N, start):
    INF = 10 ** 12
    dist = [-INF] * (N+1) # 1-indexed
    dist[start] = 0
    for i in range(N+N+5):
        for (pre, ne, weight) in graph:
            if dist[pre] != -INF and dist[pre] + weight - P > dist[ne]:
                dist[ne] = dist[pre] + weight - P
                # n回繰り返してもスコアが更新された場合
                if i > N-1:
                    dist[ne] = INF
    if dist[N] == INF:
        return -1
    else:
        return max(0, dist[N])

answer = bellmanford(N, 1)
print(answer)

Submission status: Accepted

Solution code:
#import decimal
#decimal.getcontext().prec==500 Floatの桁数を500まで増やす
#Decimal(c).sqrt() それで平方根を求める
#Decimal(1) / Decimal(7) 1/7
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
import math
from fractions import gcd
import sys
#input = sys.stdin.readline


#N=int(input())
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
for i in range(M):
    ABC[i][2]=-1*(ABC[i][2]-P)
data=[[] for i in range(N+1)]
for a,b,c in ABC:
    data[b].append(a)

idle_max=10**9




visited=set()
stack=[N]
while stack:
    a=stack.pop()
    for p in data[a]:
        if not p in visited:
            visited.add(p)
            stack.append(p)




data=[idle_max for i in range(N+1)]
data[1]=0
for i in range(N-1):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)
predata=copy.copy(data)
value=data[N]
for i in range(N):
    for a,b,c in ABC:
        if data[a] != idle_max:
            data[b]=min(data[b],data[a]+c)

for i in visited:
    if predata[i]>data[i]:
        break
else:
    print(max(-value,0))
    exit()
print(-1)

Submission status: Accepted

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    INF = 10**19
    dist = [INF] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[a] != INF and dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Accepted

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]

def bellmanford(s, g):
    dist = [float('inf')] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            if dist[b] > dist[a] - c + P:
                dist[b] = dist[a] - c + P
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Accepted

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, M, P = lr()
graph = [lr() for _ in range(M)]


def bellmanford(s, g):
    dist = [float("inf")] * (N+1)
    dist[s] = 0
    for i in range(2 * N):
        for a, b, c in graph:
            cost = -(c - P)
            if dist[b] > dist[a] + cost:
                dist[b] = dist[a] + cost
                if i >= N:
                    dist[b] = -float("inf")
 
    if dist[g] == -float("inf"):
        return -1
    else:
        return max(-dist[g], 0)

answer = bellmanford(1, N)
print(answer)
#

Submission status: Accepted

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


def bellman_ford(s, g):
    # loop 0 - (n-1) : bellman ford
    # loop n - (2n-1): check g can be updated
    dist = [float("inf")] * n
    dist[s] = 0
    for i in range(2 * n):
        for a, b, c in abc:
            a -= 1
            b -= 1
            cost = -(c - p)

            if dist[b] > dist[a] + cost:
                dist[b] = dist[a] + cost
                if i >= n:
                    dist[b] = -float("inf")

    if dist[g] == -float("inf"):
        return -1

    else:
        return max(-dist[g], 0)


ans = bellman_ford(0, n - 1)
print(ans)

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
def BellmanFord(edges,num_v,s):
  #グラフの初期化
  inf=float("inf")
  dist=[inf]*num_v
  dist[s]=0
  #辺の緩和
  for i in range(num_v-1):
    for edge in edges: #edges[頂点][頂点][重み]
      if dist[edge[0]] != inf and dist[edge[1]] > dist[edge[0]] + edge[2]+p:
        dist[edge[1]] = dist[edge[0]] + edge[2]+p
  cnt1=-dist[n-1]
  neg=[False]*num_v
  for i in range(num_v):
    for edge in edges: #edges[頂点][頂点][重み]
      if dist[edge[1]] > dist[edge[0]] + edge[2]+p:
        dist[edge[1]] = dist[edge[0]] + edge[2]+p
        neg[edge[1]]=True
      if neg[edge[0]]:
        neg[edge[1]]=True
  if neg[n-1]:
    ans=-1
  else:
    ans=max(cnt1,0)
  return ans
edges=[]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c*=-1
  edges.append((a,b,c))
print(BellmanFord(edges,n,0))

Submission status: Accepted

Solution code:
from collections import deque

def dfs(edge, s):
    used = {s}
    que = deque([s])
    while que:
        v = que.pop()
        for u in edge[v]:
            if u in used:
                continue
            used.add(u)
            que.append(u)
    return used

def bellmanFord(edges):
    coins = [float('inf')] * N
    coins[0] = 0
    for _ in range(len(U)):
        f = True
        for u, v, c in edges:
            if coins[u] + c < coins[v]:
                coins[v] = coins[u] + c
                f = False
        if f:
            return max(0, -coins[-1])
    return -1

N, M, P = map(int, input().split())
A = [[] for _ in range(N)]
A_rev = [[] for _ in range(N)]
E = [tuple()] * M
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = P - c
    A[a].append(b)
    A_rev[b].append(a)
    E[i] = (a, b, c)
U = dfs(A, 0) & dfs(A_rev, N-1)
F = [(a, b, c) for (a, b, c) in E if a in U and b in U]
print(bellmanFord(F))

Submission status: Accepted

Solution code:
from collections import deque

def dfs(edge, s):
    used = {s}
    que = deque([s])
    while que:
        v = que.pop()
        for u in edge[v]:
            if u in used:
                continue
            used.add(u)
            que.append(u)
    return used

def bellmanFord(edges):
    coins = [float('inf')] * N
    coins[0] = 0
    for _ in range(N):
        f = True
        for u, v, c in edges:
            if coins[u] + c < coins[v]:
                coins[v] = coins[u] + c
                f = False
        if f:
            return max(0, -coins[-1])
    return -1

N, M, P = map(int, input().split())
A = [[] for _ in range(N)]
A_rev = [[] for _ in range(N)]
E = [tuple()] * M
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = P - c
    A[a].append(b)
    A_rev[b].append(a)
    E[i] = (a, b, c)
U = dfs(A, 0) & dfs(A_rev, N-1)
F = [(a, b, c) for (a, b, c) in E if a in U and b in U]
print(bellmanFord(F))

Submission status: Accepted

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


def reachable_nodes(s, edges):
    cur = {s}
    reachable = set()
    while cur:
        reachable |= cur
        cur = set().union(*(edges[node] for node in cur)) - reachable
    return reachable


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 = reachable_nodes(0, to) & reachable_nodes(N - 1, reverse_to)
    
    edge_dict = dict()
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            edge_dict[(a, b)] = min(c, edge_dict.get((a, b), 10 ** 6))
    AA, BB, CC = [], [], []
    for (a, b), c in edge_dict.items():
        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: Accepted

Solution code:
def BF(v, start, edges):
    INF = 10**18
    nega = False
    d = [INF] * v
    d[start] = 0
    for _ in range(v):
        f = False
        for a, b, c in edges:
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        if not f:
            break
    else:
        nega = True
    return d, nega

from collections import deque
def BFS(N, graph, start):
    d = [-1 for i in range(N)]
    Q = deque([])
    Q.append(start)
    d[start] = 0
    while Q:
        v = Q.popleft()
        for u in graph[v]:
            if d[u] == -1:
                d[u] = d[v] + 1
                Q.append(u)
    return d

N, M, P = (int(i) for i in input().split())
graph = [[] for i in range(N)]
graphr = [[] for i in range(N)]
edges = []
for i in range(M):
    A, B, C = (int(i) for i in input().split())
    graph[A-1].append(B-1)
    graphr[B-1].append(A-1)
    edges.append((A-1, B-1, P-C))
d_start = BFS(N, graph, 0)
d_end = BFS(N, graphr, N-1)
nodes_start = [i for i in range(N) if d_start[i] >= 0]
nodes_end = [i for i in range(N) if d_end[i] >= 0]
new_edges = []
for A, B, C in edges:
    if A in nodes_start and B in nodes_start and A in nodes_end and B in nodes_end:
        new_edges.append((A, B, C))
d, Nega = BF(N, 0, new_edges)
if Nega == True:
    print(-1)
else:
    print(max(-d[N-1], 0))

Submission status: Accepted

Solution code:
from collections import deque

class GraphWeighted(): #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

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)
            self.deg[e[1]-1] += 1
    def BFS(self,s):
        dist = [None for _ in range(self.n)]
        dist[s] = 0
        queue = deque([s])
        while queue:
            node = queue.popleft()
            for adj in self.graph[node]:
                if dist[adj] is not None:
                    continue
                dist[adj] = dist[node]+1
                queue.append(adj)
        return dist

INF = 10**18

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

rev = []
for e in E:
    rev.append((e[1],e[0]))

R = Graph(N,rev)
reachable = R.BFS(N-1)

edge = []
for e in E:
    if reachable[e[0]-1] is None or reachable[e[1]-1] is None:
        continue
    edge.append((e[0],e[1],P-e[2]))

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

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

Submission status: Accepted

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)


for a, b, c in abc:
  d = dist[a] + c
  if dist[b] < d:
    dist[b] = float('inf')

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

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

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)
N, M, P = map(int,input().split())
es = []
to = defaultdict(list)
rto = defaultdict(list)
rf = [False]*N
rt = [False]*N
for i in range(M):
  a, b, c = map(int, input().split())
  es += [(a-1,b-1,-c+P)]
  to[a-1] += [b-1]
  rto[b-1] += [a-1]

def dfs(v):
  if rf[v]:
    return
  rf[v] = True
  for u in to[v]:
    dfs(u)

def rdfs(v):
  if rt[v]:
    return
  rt[v] = True
  for u in rto[v]:
    rdfs(u)

dfs(0)
rdfs(N-1)
ok = [False]*N
for i in range(N):
  ok[i] = rf[i]&rt[i]

dist = [float('inf')]*N
dist[0] = 0
upd = True
cnt = 0
while upd:
  upd = False
  for j in range(M):
    f, t, c = es[j]
    if (not ok[f]) or (not ok[t]):
      continue
    if dist[t]>dist[f]+c:
      upd = True
      dist[t] = dist[f]+c
  cnt += 1
  if cnt>N:
    print(-1)
    break
else:
  print(max(0,-dist[N-1]))

Submission status: Accepted

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):
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n: dist[v]=-inf
  return dist

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

Submission status: Accepted

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(3*n):
    for u,v,cost in edges:
      if dist[u] != inf and dist[v] > dist[u] + cost:
        dist[v] = dist[u] + cost
        if i>=n: dist[v]=-inf
  return dist

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

Submission status: Accepted

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

Submission status: Accepted

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[to] > dist[fr] + cost:
            dist[to] = dist[fr] + cost
            if i >= N:
                dist[to] = -float('inf')


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

Submission status: Accepted

Solution code:
INF = float('inf')
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
d[0] = 0

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

ans = d[-1]

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

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

Submission status: Accepted

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
d[0] = 0

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

ans = d[-1]

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

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

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)

    # 0 => N-1の間にある閉路を検出したいので
    # 0とN-1からたどりつけない場所は前処理で取り除く
    
    visited1 = set() 
    visited2 = set()
    visited1.add(0)
    visited2.add(N-1)
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        for dest in g[v]:
            if dest in visited1:
                continue
            visited1.add(dest)
            Q.append(dest)
    
    Q.append(N-1)
    while Q:
        v = Q.popleft()
        for dest in rg[v]:
            if dest in visited2:
                continue
            visited2.add(dest)
            Q.append(dest)
    
    OK = visited1 & visited2
    
    flag = True
    d = [float('inf')] * N
    d[0] = 0
    #ベルマンフォード法、N回実行してまだ更新されている場合は負の閉路が存在する
    #for _ in range(N):
    #    flag = False
    #    for a, b, c in edge:
    #        if not a in OK:
    #            continue
    #        if not b in OK:
    #            continue
    #        newD = d[a] + c
    #        if newD < d[b]:
    #            d[b] = newD
    #            flag = True
    #    if not flag:
    #        print(max(0,-d[N-1]))
    #        exit()
    #else:
    #    print(-1)
    #    exit()
    step = 0
    while flag:
        flag = False
        for A, B, C in edge:
            if not A in OK:
                continue
            if not B in OK:
                continue
            newD = d[A] + C
            if newD < d[B]:
                d[B] = newD
                flag = True
        step += 1
        if step > N:
            print(-1)
            exit()
 
    print(max(0,-d[N-1]))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline


def main():
    N, M, P = map(int, input().split())
    edge = []
    g = [[] for _ in range(N)]
    rg = [[] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        A -= 1
        B -= 1
        C -= P
        C = -C
        edge.append((A,B,C))
        g[A].append(B)
        rg[B].append(A)

    # 0 => N-1の間にある閉路を検出したいので
    # 0とN-1からたどりつけない場所は前処理で取り除く
    
    visited1 = set() 
    visited2 = set()
    visited1.add(0)
    visited2.add(N-1)
    Q = deque()
    Q.append(0)
    while Q:
        v = Q.popleft()
        for dest in g[v]:
            if dest in visited1:
                continue
            visited1.add(dest)
            Q.append(dest)
    
    Q.append(N-1)
    while Q:
        v = Q.popleft()
        for dest in rg[v]:
            if dest in visited2:
                continue
            visited2.add(dest)
            Q.append(dest)
    
    OK = visited1 & visited2
    
    flag = True
    d = [float('inf')] * N
    d[0] = 0
    #ベルマンフォード法、N回実行してまだ更新されている場合は負の閉路が存在する
    for _ in range(N):
        flag = False
        for a, b, c in edge:
            if not a in OK:
                continue
            if not b in OK:
                continue
            newD = d[a] + c
            if newD < d[b]:
                d[b] = newD
                flag = True
        if not flag:
            print(max(0,-d[N-1]))
            exit()
    else:
        print(-1)
        exit()


if __name__ == "__main__":
    main()