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:
import functools
from heapq import*
from collections import deque
import collections
import math
from collections import defaultdict
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
inf = float("inf")


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors


def factorize(n):
    fct = []  # prime factor
    b, e = 2, 0  # base, exponent
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct


def is_prime(n):
    if n == 1:
        return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True


def primes(n):
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5) + 1):
        if not is_prime[i]:
            continue
        for j in range(i * 2, n + 1, i):
            is_prime[j] = False
    return [i for i in range(n + 1) if is_prime[i]]


def modpow(a, n, mod):
    res = 1
    while n > 0:
        if n & 1:
            res = res * a % mod
        a = a * a % mod
        n >>= 1
    return res


def modinv(a, mod):
    return modpow(a, mod - 2, mod)


def cnk(a, b):
    MOD = 10**9+7
    ret = 1
    for i in range(b):
        ret *= (a-i)
        ret %= MOD
        ret = ret * modinv(i+1, MOD) % MOD
    return ret


def Dijkstra(n, start, e):
    # input parm e
    # e = [[]for i in range(n)]
    # e[x].append([y, 1])
    # e[y].append([x, 1])
    n += 10

    d = [float("inf") for i in range(n)]
    d[start] = 0

    pathnum = [0 for i in range(n)]
    pathnum[start] = 1

    visited = [False for i in range(n)]
    q = []
    heappush(q, (0, start))
    while len(q):
        now_distance, v = heappop(q)
        if visited[v]:
            continue
        visited[v] = True
        for next_v, next_distance in e[v]:
            if visited[next_v]:
                continue
            dd = now_distance + next_distance
            if d[next_v] > dd:
                d[next_v] = dd
                heappush(q, (dd, next_v))
            if d[next_v] == dd:
                pathnum[next_v] += pathnum[v]
                pathnum[next_v] %= MOD

    return d, pathnum


def warshall_floyd(d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    return d


class UnionFind:
    def __init__(self, n):
        self.sz = [-1 for i in range(n)]

    # 検索
    def find(self, x):
        if self.sz[x] < 0:
            return x
        else:
            self.sz[x] = self.find(self.sz[x])
            return self.sz[x]

    # 併合

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.sz[x] > self.sz[y]:
            x, y = y, x
        self.sz[x] += self.sz[y]
        self.sz[y] = x

    # 同じ集合に属するか判定
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # xが含まれている集合のサイズを求める
    def size(self, x):
        return -self.sz[self.find(x)]


class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        # 根への距離を管理
        self.weight = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            # 親への重みを追加しながら根まで走査
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    # 併合
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        # xの木の高さ < yの木の高さ
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        # xの木の高さ ≧ yの木の高さ
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            # 木の高さが同じだった場合の処理
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    # 同じ集合に属するか
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # xからyへのコスト
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

#
# kruskal
#


@functools.lru_cache(maxsize=None)
class UNION_FIND(object):
    def __init__(self, n):
        self.parent = [-1 for i in range(n)]

    def root(self, x):
        if self.parent[x] < 0:
            return x
        else:
            self.parent[x] = self.root(self.parent[x])
            return self.parent[x]

    def size(self, x):
        return -self.parent[self.root(x)]

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return False
        if self.size(x) < self.size(y):
            x, y = y, x
        self.parent[x] += self.parent[y]
        self.parent[y] = x
        return True


def compute_mst_kruskal(max_v, edges):
    edges.sort(key=lambda x: x[2], reverse=1)
    uf = UNION_FIND(max_v)
    mst = []
    for (a, b, c, d) in edges:
        if uf.root(a-1) != uf.root(b-1):
            uf.union(a-1, b-1)
            mst += [d+1]
    return mst


# max_v, max_e = map(int, input().split())
# edges = []
# for i in range(max_e):
#     a, b, c = map(int, input().split())
#     heappush(edges, (a, b, c, i))

# mst = compute_mst_kruskal(max_v, edges)
# mst.sort()
# for i in mst:
#   print(i)

#
# Dinic
#

class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, s, t):
        self.level = level = [None]*self.N
        deq = deque([s])
        level[s] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10**9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow

# V, E, r = map(int, input().split())
# edges = []
# for i in range(E):
#     s, t, d = map(int, input().split())
#     edges.append([s, t, d])

# d = BellmanFord(edges, V, r)
# if d == -1:
#     print("NEGATIVE CYCLE")
#     exit()

# for i in range(V):
#     if d[i] == float("inf"):
#         print("INF")
#     else:
#         print(d[i])


# def BellmanFord(edges, n, s):
#     # グラフの初期化
#     dist = [float("inf") for i in range(n)]
#     dist[s] = 0

#     # 辺の緩和
#     for i in range(n):
#         for edge in edges:
#             if 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 edge[1] == n - 1:
#                     return -1

#     return dist

ok = [False for i in range(2505)]


def Bellmanford(edges, n, s):
    d = [float("inf") for i in range(n)]
    d[s] = 0

    # 二回辺の緩和をすることで、目的となる点n-1が負の閉路に含まれるか分かる。
    # update = True
    # while update:
    for i in range(n):
        for x, y, z in edges:
            if not ok[x] or not ok[y]:
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if i == n - 1:
                    print(-1)
                    exit()
    # d1 = d[n - 1];l
    # print(d)
    # for i in range(n):
    #     for x, y, z in edges:
    #         if d[y] > d[x] + z:
    #             d[y] = d[x] + z
    # print(d)
    print(max(0, -d[n - 1]))


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

    to = [[] for i in range(n + 1)]
    rto = [[] for i in range(n + 1)]
    e = []
    for i in range(m):
        a, b, c = map(int, input().split())
        to[a - 1].append(b - 1)
        rto[b - 1].append(a - 1)
        e.append((a - 1, b - 1, p - c))

    can_reach_to = [False for i in range(n+1)]
    can_reach_rto = [False for i in range(n+1)]

    def todfs(i):
        if can_reach_to[i]:
            return 0
        can_reach_to[i] = True
        for v in to[i]:
            todfs(v)

    def rtodfs(i):
        if can_reach_rto[i]:
            return 0
        can_reach_rto[i] = True
        for v in rto[i]:
            rtodfs(v)
    todfs(0)
    rtodfs(n-1)
    for i in range(n):
        ok[i] = (can_reach_to[i] & can_reach_rto[i])

    d = Bellmanford(e, n, 0)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, M, P = map(int, input().split())
E = dict()
for i in range(M):
    a, b, c = map(int, input().split())
    E[(i, a, b)] = c-P
INF = float('inf')

dist = {i: -INF for i in range(1, N+1)}
dist[1] = 0
ans = 0
for i in range(N*2):
    for iuv, c in E.items():
        _, u, v = iuv
        if dist[v] < dist[u] + c:
            dist[v] = dist[u] + c
            if i >= N:
                dist[v] = INF
    if i == N-1:
        ans = dist[N]

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

Submission status: Accepted

Solution code:
#57 ABC137E
#ベルマンフォード

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

abc=[list(map(int,input().split())) for _ in range(m)]
abc=[[a,b,p-c] for a,b,c in abc]
def BF(edges,num_v,source):
    #グラフの初期化
    inf=float("inf")
    dist=[inf for i in range(num_v)]
    dist[source-1]=0
  
    #辺の緩和
    neg=[False for _ in range(num_v)]
    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]
    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]
                neg[edge[1]-1]=True
            if neg[edge[0]-1]==True:
                neg[edge[1]-1]=True
    return dist,neg
dis,neg=BF(abc,n,1)
#print(dis,neg)
print(-1 if neg[-1] else max(0,-dis[-1]))

Submission status: Accepted

Solution code:
def is_reachable(edges,start,end):
  g = {}
  for f,t,w in edges:
    if f in g: g[f].append(t)
    else: g[f] = [t]
  visiting = [start]
  visited = {}
  while visiting:
    v = visiting.pop()
    if v in visited: continue
    if v == end: return True
    visited[v] = True
    for v2 in g.get(v, ()):
      if v2 in visited or v2 in visiting: continue
      visiting.append(v2)
  return False

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

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

neg_inf = float("-Inf")
no_answer = False

start = 1
end = N

distance = {}
for i in range(1,N+1):
  distance[i] = neg_inf
distance[start] = 0

for i in range(N-1):
    for f,t,w in edges:
        if distance[f] + w - P > distance[t]:
            distance[t] = distance[f] + w - P

for f,t,w in edges:
    if distance[f] + w - P > distance[t] and is_reachable(edges,t,end):
        no_answer = True
        break

if no_answer:
    print(-1)
else:
    print(max(0,distance[end]))

Submission status: Accepted

Solution code:
from collections import deque


def bellman_ford(start: int, goal: int, graph: list) -> list:
    '''bellman-ford法: 始点startから終点goalへの最小コストを求める
    重み付きグラフgraphは隣接リストで与えられ、辺のコストは負でも良い
    次の3種類のパターンが存在する
        1. 始点startから終点goalにたどり着くことが不可能である
           -> float("inf")を返す

        2. 始点startから終点goalにたどり着くことが可能であり、
           パス上に負閉路が存在する
           -> -float("inf")を返す

        3. 始点startから終点goalにたどり着くことが可能であり、
           パス上に負閉路が存在しない
           -> 最小コストを返す

    計算量: O(|E||V|)
    '''
    INF = float("inf")
    n = len(graph)

    # スタートから到達可能な地点を調べる
    is_reachable = [False] * n
    is_reachable[start] = True
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, _ in graph[pos]:
            if is_reachable[next_pos]:
                continue
            is_reachable[next_pos] = True
            q.append(next_pos)

    # 逆辺で構築したグラフで、ゴールから到着可能な地点を調べる
    reverse_graph = [[] for i in range(n)]
    for pos, edge in enumerate(graph):
        for next_pos, cost in edge:
            reverse_graph[next_pos].append((pos, cost))

    is_rev_reachable = [False] * n
    is_rev_reachable[goal] = True
    q = deque([goal])
    while q:
        pos = q.popleft()
        for next_pos, _ in reverse_graph[pos]:
            if is_rev_reachable[next_pos]:
                continue
            is_rev_reachable[next_pos] = True
            q.append(next_pos)            

    is_on_the_path_from_start_to_goal = [False] * n
    for i in range(n):
        is_on_the_path_from_start_to_goal[i] = is_reachable[i] and is_rev_reachable[i]

    distance = [INF] * n
    distance[start] = 0
    for _ in range(n):
        is_updated = False
        for pos, edge in enumerate(graph):
            for next_pos, cost in edge:
                if not is_on_the_path_from_start_to_goal[next_pos]:
                    continue
                if distance[pos] != INF and distance[pos] + cost < distance[next_pos]:
                    distance[next_pos] = distance[pos] + cost
                    is_updated = True
        if not is_updated:
            return distance[goal]
    # 負閉路が存在する
    return -INF


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):
    a, b, c = info[i]
    graph[a - 1].append((b - 1, -(c - p)))
ans = bellman_ford(0, n-1, graph)

if ans == -float("inf"):
    print(-1)
else:
    print(max(-ans, 0))

Submission status: Accepted

Solution code:
from collections import deque


def bellman_ford(start: int, goal: int, graph: list) -> list:
    '''bellman-ford法: 始点startから終点goalへの最小コストを求める
    重み付きグラフgraphは隣接リストで与えられる
    辺のコストは負でも良い
    負閉路検出: 始点startから終点goal上のパスに負閉路があるときは[-1]を返す
    計算量: O(|E||V|)
    '''
    INF = float("inf")
    n = len(graph)

    # スタートからゴールに到着可能かどうか判定する
    is_reachable = [False] * n
    is_reachable[start] = True
    q = deque([start])
    while q:
        pos = q.popleft()
        for next_pos, _ in graph[pos]:
            if is_reachable[next_pos]:
                continue
            is_reachable[next_pos] = True
            q.append(next_pos)

    # 逆辺で構築したグラフでゴールからスタートに到着可能かどうか判定する
    reverse_graph = [[] for i in range(n)]
    for pos, edge in enumerate(graph):
        for next_pos, cost in edge:
            reverse_graph[next_pos].append((pos, cost))

    is_rev_reachable = [False] * n
    is_rev_reachable[goal] = True
    q = deque([goal])
    while q:
        pos = q.popleft()
        for next_pos, _ in reverse_graph[pos]:
            if is_rev_reachable[next_pos]:
                continue
            is_rev_reachable[next_pos] = True
            q.append(next_pos)            

    need = [False] * n
    for i in range(n):
        need[i] = is_reachable[i] and is_rev_reachable[i]

    distance = [INF] * n
    distance[start] = 0
    for _ in range(n):
        is_updated = False
        for pos, edge in enumerate(graph):
            for next_pos, cost in edge:
                if not need[pos]:
                    continue
                if distance[pos] != INF and distance[pos] + cost < distance[next_pos]:
                    distance[next_pos] = distance[pos] + cost
                    is_updated = True
        if not is_updated:
            return distance[goal]
    # 負閉路が存在する
    return -INF


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):
    a, b, c = info[i]
    graph[a - 1].append((b - 1, -(c - p)))
ans = bellman_ford(0, n-1, graph)
if ans == -float("inf"):
    print(-1)
else:
    print(max(-ans, 0))

Submission status: Accepted

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

def find_negative_loop(s,n,w,es):
  # s: start
  # n: number of nodes
  # w: number of edges
  # es[i]: from, to, cost
  
  # d: shortest dist of s -> i
  inf = float('inf')
  d = [inf for _ in range(n)]
  d[s] = 0
  for i in range(2*n):
    for j in range(w):
      p, q, r = es[j]
      if d[p] != inf and (d[q] > d[p] + r):
        d[q] = d[p] + r
        if i >= n:
          d[q] = (-1)*inf
    if i == n-1:
      temp = d[-1]
  return temp, d[-1]
         

n, w, p = map(int, input().split())
es = []
for i in range(w):
  x, y, z = map(int, input().split())
  es.append([x-1, y-1, (z-p)*(-1)])
  
temp, d = find_negative_loop(0, n, w ,es)
if temp == d:
  print(min(0, d)*(-1))
else:
  print('-1')

Submission status: Accepted

Solution code:
import sys
import time
from queue import Queue
limit_time = time.time() + 1.70
input = sys.stdin.readline
sys.setrecursionlimit(1000000000)

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

A = [-1]*M
B = [-1]*M
C = [-1]*M
nodes_edges = [[] for _ in range(N)]
rev_nodes_edges = [[] for _ in range(N)]
coin = [-float('inf')]*N
coin[0] = 0
availables = set()

for edge in range(M):
    a, b, c = map(int, input().split())
    A[edge] = a-1
    B[edge] = b-1
    C[edge] = c-P
    nodes_edges[a-1].append(edge)
    rev_nodes_edges[b-1].append(edge)

def cut_graph(node):
    edges = rev_nodes_edges[node]
    availables.add(node)
    for edge in edges:
        prev = A[edge]
        if prev in availables:
            continue
        cut_graph(prev)

cut_graph(N-1)
q = Queue()
q.put(0)
count = 0
limit = M*(1+len(availables))
while not q.empty():
    if time.time() >= limit_time:
        print(-1)
        break
    node = q.get()
    edges = nodes_edges[node]
    for edge in edges:
        nxt = B[edge]
        if nxt not in availables:
            continue
        new_coin = C[edge]+coin[node]
        if new_coin > coin[nxt]:
            coin[nxt] = new_coin
            q.put(nxt)
    count += 1
else:
    ans = coin[N-1]
    ans = 0 if ans < 0 else ans
    print(ans)

Submission status: Accepted

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

inf = float('inf')

# 計算量O(VE) V:頂点数, E:辺の数
# True - >正常に更新, False -> startからendまでの経路において負閉路有り
def bellmanford(start, end):
    global dist
    dist = [inf] * N
    dist[start] = 0
    # 頂点数Nなら更新は高々N-1回で済む
    for _ in range(N-1):
        for v ,nv, w in edges:
            if dist[nv] > dist[v] + w:
                dist[nv] = dist[v] + w
    # 負閉路の検出部分
    # N回目で更新があった場合、負閉路を含む
    for v, nv, w in edges:
        if dist[nv] > dist[v] + w:
            return False
    return True

def dfs(v, ad):
    visited[v] = True
    for nv in ad[v]:
        if not visited[nv]:
            dfs(nv, ad)

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

visited = [False] * N

dfs(0, to)
tmp = visited[:]
visited = [False] * N
dfs(N-1, fr)
visited = [a and b for a, b in zip(tmp, visited)]
edges = [(v, nv, w) for v, nv, w in edges if visited[v] and visited[nv]]

flag = bellmanford(0, N-1)
ans = max(-dist[N-1], 0) if flag else -1
print(ans)

Submission status: Accepted

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

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


visited = [0] * n
def dfs(v):
    for u in edge_inv[v]:
        if visited[u] == 0:
            visited[u] = 1
            dfs(u)

visited[n-1] = 1
dfs(n-1)
target_nodes = set([i for i in range(n) if visited[i] == 1])

INF = float('inf')
d = [INF] * n
d[0] = 0
for i in range(n):
    update = False
    for v_from, v_to, cost in edge:
        if v_from not in target_nodes or v_to not in target_nodes:
            continue
        if d[v_from] != INF and d[v_to] > d[v_from] + cost:
            update = True
            d[v_to] = d[v_from] + cost


if update:
    print(-1)
else:
    print(max(0, -d[n-1]))

Submission status: Accepted

Solution code:
import sys

n, m, p = map(int, sys.stdin.readline().split())

abc = []
# edge = [[] for _ in range(n)]
rev_edge = [[] for _ in range(n)]

for _ in range(m):
	a, b, c = map(int, sys.stdin.readline().split())
	abc.append((a-1, b-1, p-c))
	rev_edge[b-1].append(a-1)

def dfs(e, s):
	v_set = {s, }
	stack = [s]

	while stack:
		v = stack.pop()
		for next_v in e[v]:
			if not next_v in v_set:
				stack.append(next_v)
				v_set.add(next_v)
	return v_set

def bellman_ford(sub_abc, n):
	dist = [float('inf')]*n 
	dist[0] = 0

	for _ in range(n):
		updated = False
		for ele in sub_abc:
			a, b, d = ele
			if dist[a] + d < dist[b]:
				dist[b] = dist[a] + d 
				updated = True
		if not updated:
			break
	else:
		return -1

	return max(-dist[n-1], 0)

use = dfs(rev_edge, n-1)
print(bellman_ford([(a, b, c) for a, b, c in abc if a in use and b in use], n))

Submission status: Accepted

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

class edge:
   f, t, c = 0, 0, 0

inf = 10 ** 5 * (M + 1)
D = [inf] * N
D[0] = 0
E = [edge() for _ in range(M)]
for i in range(M):
  f, t, c = ABC[i]
  E[i].f = f - 1
  E[i].t = t - 1
  E[i].c = P - c
  
L = [False] * N
L[-1] = True
for i in range(N):
  for j in range(M):
    e = E[j]
    if L[e.t]:
      L[e.f] = True

cnt = N + 1
while True:
  flag = True
  for i in range(M):
    e = E[i]
    if D[e.f] != inf and D[e.t] > D[e.f] + e.c:
      D[e.t] = D[e.f] + e.c
      flag = False
      if cnt == 1:
        if L[e.t]:
          print(-1)
          exit()
  if flag:
    break
  cnt -= 1
  if cnt <= 0:
    break

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

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(12345678)

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    # print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc137/tasks/abc137_e

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop
import sys
sys.setrecursionlimit(1000000)

def main():
    n, m, p = map(int, input().split())
    edges = []
    graph = defaultdict(list)
    rev_graph = defaultdict(list)

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

    # pick up nodes on goal path
    reachable_from_start = [False] * n

    # print(edges)
    def dfs(node):
        if reachable_from_start[node]:
            return
        reachable_from_start[node] = True
        for next_node in graph[node]:
            dfs(next_node)

    reachable_to_end = [False] * n

    def rdfs(node):
        if reachable_to_end[node]:
            return
        reachable_to_end[node] = True
        for next_node in rev_graph[node]:
            rdfs(next_node)

    dfs(0)
    rdfs(n-1)

    valid = [False] * n
    for i in range(n):
        valid[i] = reachable_from_start[i] and reachable_to_end[i]

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    loop = 0

    # bellman-ford
    updated = True
    while updated:
        updated = False
        for i in range(m):
            a, b, c = edges[i]
            if not valid[a]:
                continue
            if not valid[b]:
                continue

            new_cost = scores[a] + c
            if new_cost < scores[b]:
                updated = True
                scores[b] = new_cost

        loop += 1
        if loop > n:
            print(-1)
            return

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import collections
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
cd = collections.defaultdict
Ga = cd(set)
Gb = cd(set)
G = []
ok = cd(int)
for a, b, c in ABC:
    Ga[a].add(b)
    Gb[b].add(a)
#dfs
for pair in [[1, Ga], [N, Gb]]:
    S = pair
    Gn = pair.pop()
    visited = [0] * (N + 1)
    while S:
        s = S.pop()
        if not visited[s]:
            visited[s] = 1
            ok[s] += 1
            for ns in Gn[s]:
                S += [ns]
for a, b, c in ABC:
    if ok[a] == ok[b] == 2:
        G += [(a, b, P - c)]


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [INF] * V
    D[i] = 0
    for _ in range(V):
        update = False
        for s, t, d in G:
            if D[s] != INF and D[t] > D[s] + d:
                D[t] = D[s] + d
                update = True
        if not update:
            return D
        if _ == V:
            return False


a = bellman_ford(N + 1, G, 1)
try:
    print(max(-a[-1], 0))
except:
    print(-1)

Submission status: Accepted

Solution code:
import collections

n, m, p = map(int, input().split())
dist1 = []
edges1 = [[] for _ in range(n)]
edges2 = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    dist1.append((a, b, (c - p) * -1))
    edges1[a].append(b)
    edges2[b].append(a)

def dfs(edges, start):
    stack = [start]
    use = {start, }
    while stack:
        x = stack.pop()
        for y in edges[x]:
            if y in use:
                continue
            stack.append(y)
            use.add(y)
    return use


def bellman_ford(dist):
    v = [float('inf')] * n
    v[0] = 0
    for _ in range(n):
        updated = False
        for a, b, c in dist:
            if v[a] + c < v[b]:
                updated = True
                v[b] = v[a] + c
        if not updated:
            return max(0, v[n - 1] * -1)
    return -1

use = dfs(edges1, 0) & dfs(edges2, n - 1)
dist2 = [(a, b, c) for a, b, c in dist1 if a in use and b in use]
print(bellman_ford(dist2))