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 heapq
import sys
from collections import deque
input = sys.stdin.readline

INF = float('inf')

class Edge():
    def __init__(self, start, end, cost):
        self.start = start
        self.end = end
        self.cost = cost

def dijkstra(n, G, s):
    dist = [INF] * n
    dist[s] = 0
    h = []
    heapq.heappush(h, (0, s))

    while h:
        # 使っていない頂点のうち、現時点で最も距離の近いものを選びvとする
        d, v = heapq.heappop(h)
        if dist[v] < d:
            continue
        # vから到達可能な頂点について、距離が短くなれば更新
        for e in G[v]:
            if dist[e.end] > dist[v] + e.cost:
                dist[e.end] = dist[v] + e.cost
                heapq.heappush(h, (dist[e.end], e.end))
    return dist

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

g1 = [[] for _ in range(n)]
g2 = [[] for _ in range(n)]
es = []

abc = []

for _ in range(m):
    a, b, c = map(int, input().split())
    abc.append((a-1, b-1, c))
    g1[a-1].append(Edge(a-1, b-1, 1))
    g2[b-1].append(Edge(b-1, a-1, 1))

dist1 = dijkstra(n, g1, 0)
dist2 = dijkstra(n, g2, n-1)

# print(dist1)
# print(dist2)

ng = set({})

for i in range(n):
    if dist1[i] == INF or dist2[i] == INF:
        ng.add(i)

for a, b, c in abc:
    if a in ng or b in ng:
        continue
    es.append(Edge(a, b, p-c))

def bellman_ford(n, es, s):
    dist = [INF] * n
    dist[s] = 0
    # 更新が止まるまで繰り返す O(V*E)
    # i度目の更新までにsを始点として0~i個の辺からなる経路が探索され、その時点の最短経路が計算される
    # 最短経路は最大でもV-1個の頂点しか通らないため、最悪でもv-1回で収束する
    while True:
        update = False
        # 辺をすべて見る
        for e in es:
            # aに到達可能かつa経由の方が近ければ更新する
            if dist[e.start] != INF and dist[e.end] > dist[e.start] + e.cost:
                dist[e.end] = dist[e.start] + e.cost
                update = True
        # 一度も更新されなければ終了
        if not update:
            break
    return dist

def find_negative_loop(n, es):
    dist = [0] * n
    for i in range(n):
        for e in es:
            if dist[e.end] > dist[e.start] + e.cost:
                dist[e.end] = dist[e.start] + e.cost
                if i == n - 1:
                    return True
    return False

if find_negative_loop(n, es):
    print(-1)
    sys.exit()

dist = bellman_ford(n, es, 0)
print(max(0, -dist[n-1]))

Submission status: Accepted

Solution code:
INF = 1e12
n,m,p = map(int,input().split())

grafo = []

for x in range(m):
    a,b,c = map(int,input().split())
    grafo.append((a-1,b-1,c-p))

def bellman_ford(v):
    distancia = [float("inf")] * n
    distancia[v] = 0
    for i in range(2 * n):
        for a,b,c in grafo:
            if distancia[b] > distancia[a] - c:
                distancia[b] = distancia[a] - c
                if i == n - 1:
                    distancia[b] = -float("inf")
    return distancia

distancia = bellman_ford(0)

if distancia[-1] ==  -float("inf"):
    print(-1)
else:
    if distancia[-1] > 0:
        print(0)
    else:
        print(-1 * distancia[-1])

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
edge=[]
for i in range(m):
    a,b,c=map(int,input().split())
    edge.append((a,b,p-c))
INF=float('inf')
def bellmanford(s,n):
    d = [INF for i in range(n+1)]
    d[s]=0
    for i in range(n-1):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=d[a]+c
    for i in range(n-1):
         for a,b,c in edge:
            if d[b]>d[a]+c:
                d[b]=-INF
    return d
d=bellmanford(1,n)
if d[n]==-INF:
    print(-1)
elif d[n]>=0:
    print(0)
else:
    print(-d[n])

Submission status: Accepted

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
# from math import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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

#True : 負の経路が存在する
def find_negative_loop1(n,w,es):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0
    infdic=defaultdict(int)
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == n-1:
                    infdic[e[0]]=1
    return infdic

def find_negative_loop2(n,w,es,infd):
    #負の経路の検出
    #n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    d[0] = 0
    for i in infd.keys():
        d[i]=-float('inf')
    #この始点はどこでもよい
    for i in range(n):
        for j in range(w):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                # if i == n-1:
                #     return True
    return d


#############################
w = m
es = [[] for i in range(w)] #es[i]: [辺の始点,辺の終点,辺のコスト]
for i in range(w):
    x,y,z = abc[i]
    es[i] = [x-1,y-1,p-z]
# w = w*2
# print(es)

tmp=find_negative_loop1(n,w,es)
# print(tmp)
tmp2=find_negative_loop2(n,w,es,tmp)
# print(tmp2)
if tmp2[-1]==-float('inf'):
    print(-1)
else:
    print(-min(tmp2[-1],0))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline
INF = 10 ** 18


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 bellman_ford(n, edges, s):
    dists = [INF] * n
    dists[s] = 0
    for cnt in range(n):
        for u, v, cost in edges:
            if dists[u] != INF and dists[u] + cost < dists[v]:
                if cnt == n - 1:
                    return -1
                dists[v] = dists[u] + cost
    return dists


def solve():
    N, M, P = map(int, rl().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, rl().split())
        a, b = a - 1, b - 1
        A[i], B[i], C[i] = a, b, P - c
        to[a].append(b)
        reverse_to[b].append(a)
    
    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))
    edges = [(u, v, cost) for (u, v), cost in edge_dict.items()]
    
    dists = bellman_ford(N, edges, 0)
    if dists == -1:
        print(-1)
    else:
        print(max(0, -dists[-1]))


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
n, m, p = map(int, input().split())
edge = []

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

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

# check = [0 for _ in range(n)]

for i in range(n*2):
    for now, next, weight in edge:
        if d[next] > d[now] + weight + p:
            d[next] = d[now] + weight + p
            # n+1回目で更新された場合はループしているのでチェックを入れる
            if i > n-1:
                d[next] = -float("inf")
                # check[next] = 1
        if i == n-1:
            prev = d[-1]
            # if check[now]:
            #     check[next] = 1
        # print(d)

# print(check)
# if check[-1]:
if prev != d[-1]:
    print("-1")
else:
    print(max(-prev, 0))
    # print(prev)

Submission status: Accepted

Solution code:
from collections import deque
def use_path(n,start,es):
    q = deque()
    chk = [False] * n
    q.append(start)
    chk[start] = True
    used = {start}
    while len(q) > 0:
        node = q.popleft()
        for nex in es[node]:
            if not chk[nex]:
                chk[nex] = True
                q.append(nex)
                used.add(nex)
    return used
  
def belman(s,g,n,es):
    d = [10**10] * n
    d[s] = 0
    fin = False
    cnt = 0
    while True:
      update = False
      for p,q,r in es:
        if d[p] != 10**10 and d[q] > d[p] + r:
          d[q] = d[p] + r
          update = True
      cnt += 1
      if not update:
        fin = True
        break
      if cnt > n+1:
          break      
    if fin:
        return max(0,-d[g])
    else:
        return -1   
  
n,m,p = map(int, input().split())

l = [[] for i in range(n)]
r = [[] for i in range(n)]
edges = []

for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    l[a].append(b)
    r[b].append(a)
    edges.append((a,b,-c+p))
    
use_nodes = use_path(n,0,l) & use_path(n,n-1,r)
es = [(a,b,c) for a,b,c in edges if a in use_nodes and b in use_nodes]
print(belman(0,n-1,n,es))

Submission status: Accepted

Solution code:
INF = 10 ** 15
MOD = 10 ** 9 + 7

def beruman(n,X,edges,start = 0,negative_loop = False):
    ans = False #startを含む負の閉路が存在するか
    dist = [INF] * n
    dist[start] = 0

    for i in range(X):
        update = False
        for a,b,c in edges:
            if dist[a] != INF and dist[b] > dist[a] + c:
                dist[b] = dist[a] + c
                update = True

        if not update:
            break
        if i == X - 1:
            ans = True
    
    if negative_loop:
        return dist,ans
    else:
        return dist

def dfs(G,can_reach,start):
    stack = [start]
    can_reach[start] = True
    while stack:
        v = stack.pop()
        for e in G[v]:
            if can_reach[e]:
                continue
            stack.append(e)
            can_reach[e] = True
    return can_reach

def main():
    N,M,P = map(int,input().split())
    edges = []
    G = [[] for _ in range(N)]
    G_inv = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = map(int,input().split())
        a -= 1
        b -= 1
        edges.append((a,b,P - c))
        G[a].append(b)
        G_inv[b].append(a)
    
    can_reach_from_start = [False] * N
    can_reach_from_goal = [False] * N
    dfs(G,can_reach_from_start,0)
    dfs(G_inv,can_reach_from_goal,N - 1)
    in_route = [False] * N
    X = 0
    for i in range(N):
        if can_reach_from_goal[i] and can_reach_from_start[i]:
            in_route[i] = True
            X += 1
        
    edge = []
    for a,b,c in edges:
        if in_route[a] and in_route[b]:
            edge.append((a,b,c))

    dist,flag = beruman(N,X,edge,0,True)
    if flag:
        print(-1)
    else:
        print(max(-dist[-1],0))
if __name__ == '__main__':
    main()

Submission status: Accepted

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

INF = float('inf')

def BellmanFord(adjList, vSt, INF):
    numV = len(adjList)
    negINF = -INF
    costs = [INF] * numV
    costs[vSt] = 0
    vNows = set([vSt])

    for _ in range(numV):
        vChangeds = set()
        for vFr in vNows:
            costFr = costs[vFr]
            for vTo, wt in adjList[vFr]:
                c2 = costFr + wt
                if c2 < costs[vTo]:
                    costs[vTo] = c2
                    vChangeds.add(vTo)
        if not vChangeds:
            return costs
        vNows = vChangeds

    for v in vNows:
        costs[v] = negINF

    Q = deque(vNows)
    while Q:
        vFr = Q.popleft()
        for vTo, wt in adjList[vFr]:
            if costs[vTo] == negINF: continue
            costs[vTo] = negINF
            Q.append(vTo)

    return costs


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

costs = BellmanFord(adjL, 0, INF)

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

Submission status: Accepted

Solution code:

"""

https://atcoder.jp/contests/abc137/tasks/abc137_e

辺の重みからPを引いておく
→あとはベルマンフォード？

正の閉路探索→むずくね？
閉路があったとしても、増えなきゃあっていい…

→まずゴールにたどり着ける頂点を列挙
→たどり着けない点は無意味なのでremove

→あとはベルマンフォード
"""

import sys
sys.setrecursionlimit(200000)

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

lis = [ [] for i in range(N) ]
rev = [ [] for i in range(N) ]
exist = [False] * N

for i in range(M):

    A,B,C = map(int,input().split())
    A -= 1
    B -= 1

    lis[A].append([B , C - P])
    rev[B].append(A)

def dfs(v):

    exist[v] = True
    for nex in rev[v]:
        if not exist[nex]:
            dfs(nex)

dfs(N-1)

dis = [float("-inf")] * N
dis[0] = 0

for i in range(N+1):

    flag = False

    for v in range(N):
        for uc in lis[v]:

            if exist[uc[0]] and dis[uc[0]] < dis[v] + uc[1]:
                #print (uc[0] , dis[v] + uc[1])
                dis[uc[0]] = dis[v] + uc[1]
                flag = True

if flag:
    print (-1)
else:
    print (max( 0 , dis[N-1] ))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

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

    visited = [0]*n
    visited[-1] = 1
    dq = deque([n-1])
    while dq:
        v = dq.popleft()
        for nv in adj[v]:
            if visited[nv] == 0:
                visited[nv] = 1
                dq.append(nv)
    
    def bellmanford(n, s, edge):
        inf = 10**17
        d = [inf] * n
        d[s] = 0
        for i in range(n):
            for a,b,c in edge:
                if d[a] != inf and d[b] > d[a]+c:
                    d[b] = d[a] + c
                    if i == n-1 and visited[b] == 1:
                        return -inf
        return -d[-1]

    res = bellmanford(n,0,edge)
    if res == -inf:
        print(-1)
    elif res < 0:
        print(0)
    else:
        print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

INF = 10 ** 9
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])

flag1 = [0] * N
flag2 = [0] * N
flag = [0] * N

flag1[0] = 1
flag2[N-1] = 1

for i in range(N-1):
    for j in range(M):
        edge = edges[j]
        if flag1[edge[0]]:
            flag1[edge[1]] = 1
        if flag2[edge[1]]:
            flag2[edge[0]] = 1

for i in range(N):
    if flag1[i] and flag2[i]:
        flag[i] = 1

d = [INF] * N
d[0] = 0
k = None

for i in range(N):
    for j in range(M):
        edge = edges[j]
        if d[edge[1]] > d[edge[0]] + edge[2]:
            d[edge[1]] = d[edge[0]] + edge[2]
            if i == N - 1 and flag[edge[1]]:
                print(-1)
                sys.exit()

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

Submission status: Accepted

Solution code:
from collections import deque
N,M,P,*L = map(int, open(0).read().split())
INF = 10**9
Els = []
dic = [[] for i in range(N+1)]
rdic = [[] for i in range(N+1)]
for a,b,c in zip(*[iter(L)]*3):
  dic[a].append((b,c-P))
  rdic[b].append((a,c-P))
  Els.append((a,b,-c+P))
ok1 = [False]*(N+1)
ok1[1] = True
q = deque([1])
while q:
  v = q.popleft()
  for p,c in dic[v]:
    if not ok1[p]:
      ok1[p] = True
      q.append(p)

ok2 = [False]*(N+1)
ok2[N] = True
q = deque([N])
while q:
  v = q.popleft()
  for p,c in rdic[v]:
    if not ok2[p]:
      ok2[p] = True
      q.append(p)

ok = [a&b for a,b in zip(ok1,ok2)]

dist = [INF]*(N+1)
dist[1] = 0
cnt = 0
while True:
  end = True
  for a,b,c in Els:
    if ok[a] and ok[b] and dist[a]!=INF and dist[b]>dist[a]+c:
      end = False
      dist[b] = dist[a]+c
  if end:
    print(max(0,-dist[N]))
    break
  cnt += 1
  if cnt>N:
    print(-1)
    break

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, M, P = (int(i) for i in input().split())
    adj_list = [[] for _ in range(N)]
    radj_list = [[] for _ in range(N)]
    ok = [False]*N
    edge = []
    for i in range(M):
        a, b, c = (int(i) for i in input().split())
        c -= P
        adj_list[a-1].append(b-1)
        radj_list[b-1].append(a-1)
        edge.append((a-1, b-1, -c))

    def dfs(G, v):
        seen = [False]*N
        todo = [v]
        seen[v] = True
        while todo:
            u = todo.pop()
            for next_v in G[u]:
                if seen[next_v]:
                    continue
                seen[next_v] = True
                todo.append(next_v)
        return seen

    i = 0
    for s, rs in zip(dfs(adj_list, 0), dfs(radj_list, N-1)):
        ok[i] = s and rs
        i += 1

    # Bellman_ford
    d = [10**12]*N
    d[0] = 0
    update = True
    step = 0
    while update:
        update = False
        for a, b, c in edge:
            if not(ok[a]) or not(ok[b]):
                continue
            newD = d[a] + c
            if newD < d[b]:
                update = True
                d[b] = newD
        step += 1
        if step > N:
            return print(-1)
    print(max(0, d[N-1]*-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from itertools import product
    import sys
    input = sys.stdin.buffer.readline
    N, M, P = (int(i) for i in input().split())
    adj_list = [[] for _ in range(N)]
    radj_list = [[] for _ in range(N)]
    ok = [False]*N
    edge = []
    for i in range(M):
        a, b, c = (int(i) for i in input().split())
        c -= P
        adj_list[a-1].append(b-1)
        radj_list[b-1].append(a-1)
        edge.append((a-1, b-1, -c))

    def dfs(G, v):
        seen = [False]*N
        todo = [v]
        seen[v] = True
        while todo:
            u = todo.pop()
            for next_v in G[u]:
                if seen[next_v]:
                    continue
                seen[next_v] = True
                todo.append(next_v)
        return seen

    i = 0
    for s, rs in zip(dfs(adj_list, 0), dfs(radj_list, N-1)):
        ok[i] = s and rs
        i += 1

    # Bellman_ford
    d = [10**12]*N
    d[0] = 0
    update = True
    step = 0
    while update:
        update = False
        for a, b, c in edge:
            if not(ok[a]) or not(ok[b]):
                continue
            newD = d[a] + c
            if newD < d[b]:
                update = True
                d[b] = newD
        step += 1
        if step > N:
            return print(-1)
    print(max(0, d[N-1]*-1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    N,M,P=map(int, input().split())
    E=[]
    G=[[] for _ in range(N)]
    H=[[] for _ in range(N)]
    for _ in range(M):
        a,b,c=map(int, input().split())
        a,b=a-1,b-1
        E.append((a,b,c-P))
        G[b].append(a)
        H[a].append(b)

    R1=[False]*N
    R1[0]=True
    stk=[0]
    while stk:
        v=stk.pop()
        for to in H[v]:
            if R1[to]: continue
            R1[to]=True
            stk.append(to)

    R2=[False]*N
    R2[N-1]=True
    stk=[N-1]
    while stk:
        v=stk.pop()
        for to in G[v]:
            if R2[to]: continue
            R2[to]=True
            stk.append(to)

    INF=10**10
    d=[-INF]*N
    d[0]=0
    for i in range(N):
        for a,b,c in E:
            if R1[a]==False: continue
            if R2[b]==False: continue
            if d[a]==-INF: continue
            if d[b] < d[a] + c:
                d[b] = d[a] + c
                if i==N-1:
                    print(-1)
                    return
    print(max(0,d[N-1]))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

INF = 10 ** 9
#入力

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

check = [False] * N
d = [INF] * N #距離を記録

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    d[s] = 0
    j = 0
    while j < N - 1:
        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]
        j += 1
    
    j = 0
    while j < N:
        for i in range(M):
            e = G[i]
            if d[e[0]] == INF:
                continue
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                check[e[1]] = True
            if check[e[0]]:
                check[e[1]] = True
        j += 1

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

Submission status: Accepted

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

for i in e:
    i[0] -= 1
    i[1] -= 1
    i[2] -= p

d = [-10**18] * n
ok1 = [False] * n
ok2 = [False] * n
d[0] = 0
ok1[0] = True
ok2[-1] = True

for _ in range(n):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True
aa = d[:]

for _ in range(n):
    for a, b, c in e:
        if ok1[a]:
            d[b] = max(d[b], d[a] + c)
            ok1[b] = True
        if ok2[b]:
            ok2[a] = True

bb = d[:]

ok = False
for i in range(n):
    if ok1[i] and ok2[i]:
        if aa[i] != bb[i]:
            ok = True
if ok:
    print("-1")
else:
    print(max(aa[-1], 0))

Submission status: Accepted

Solution code:
from collections import deque


def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [-INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

def bellman_ford2(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [-INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n + 100):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

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

graph = [[] for i in range(n)]
rev_graph = [[] for i in range(n)]
for a, b, cost in info:
    a -= 1
    b -= 1
    cost -= p
    graph[a].append((b, cost))
    rev_graph[b].append((a, cost))

visited = [False] * n
def dfs():
    q = deque([0])
    visited[0] = True
    while q:
        v = q.pop()
        for nxt_v, _ in graph[v]:
            if visited[nxt_v]:
                continue
            visited[nxt_v] = True
            q.append(nxt_v)
dfs()

visited2 = [False] * n
def dfs2():
    q = deque([n - 1])
    visited2[n - 1] = True
    while q:
        v = q.pop()
        for nxt_v, _ in rev_graph[v]:
            if visited2[nxt_v]:
                continue
            visited2[nxt_v] = True
            q.append(nxt_v)
dfs2()

#print(visited)
#print(visited2)

boolian, dist = bellman_ford(0, graph)
boolian, dist2 = bellman_ford2(0, graph)
if not boolian:
    print(max(dist[-1], 0))
else:
    for i in range(n):
        if dist[i] < dist2[i]:
            print(-1)
            exit()
    print(dist2[-1])

Submission status: Accepted

Solution code:
#グラフ上でのBFS
#s=始点 n=頂点数 e=隣接リスト
def glaph_bfs(s,n,e):
  Q=[s]
  visited={s}
  while Q:
    P=[]
    for i in Q:
      for j,_ in e[i]:
        if j in visited:continue
        visited.add(j)
        P.append(j)
    Q=P
  return visited
  

#負の閉路検出
#n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def find_negative_loop(n,e):
	d=n*[10**20];d[0]=0
	for h in range(n):
		for i,j,k in e:
			if d[j]>d[i]+k:
				d[j]=d[i]+k
				if h==n-1:return True
	return False

#ベルマンフォード(d[i]=頂点sから頂点iの最短距離)
#単一始点最短経路(負の辺対応)
#s=始点 n=頂点数 e=[[a,b,c],[]...](a~bの距離がc)
def bellman_ford(s,n,e):
  inf=10**20;d=[inf]*n;d[s]=0
  while 1:
    f=True
    for i,j,k in e:
      if d[i]!=inf and d[j]>d[i]+k:d[j]=d[i]+k;f=False
    if f:break
  return d

n,m,p=map(int,input().split())
edge=[[]for _ in range(n)]
edger=[[]for _ in range(n)]
for _ in range(m):
  a,b,c=map(int,input().split())
  c-=p
  a-=1
  b-=1
  edge[a].append((b,c))
  edger[b].append((a,c))
visited=glaph_bfs(0,n,edge)
visitedr=glaph_bfs(n-1,n,edger)
for i in range(n):
  if not(i in visited and i in visitedr):edge[i]=[]
e=[]
for i in range(n):
  for j in range(len(edge[i])):e.append((i,edge[i][j][0],-edge[i][j][1]))
if find_negative_loop(n,e):print(-1);exit()
print(max(-bellman_ford(0,n,e)[n-1],0))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M,P=map(int,input().split())
    edge=[]
    for _ in range(M):
        A,B,C=map(int1,input().split())
        C+=1
        edge.append((A,B,P-C))
    d=[INF]*N
    d[0]=0
    f=False
    for i in range(N*2):
        for a,b,c in edge:
            if d[b]>d[a]+c:
                if i<N-1:
                    d[b]=d[a]+c
                else:
                    if d[a]<10**17:
                        d[b]=-INF
                    if b==N-1:
                        f=True
    if f:
        print(-1)
    else:
        print(max(-d[N-1],0))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

edges = [[] for _ in range(N)]
to = [[] for _ in range(N)]
ot = [[] for _ in range(N)]

for a, b, c in X:
    a -= 1
    b -= 1
    c = -(c - P)
    edges[a].append((b, c))
    to[a].append(b)
    ot[b].append(a)

ok_1 = [False] * N
ok_n = [False] * N

# Reachable
def dfs(u):
    if ok_1[u]:
        return
    
    ok_1[u] = True
    for v in to[u]:
        dfs(v)
        
def rdfs(u):
    if ok_n[u]:
        return
    
    ok_n[u] = True
    for v in ot[u]:
        rdfs(v)
        
dfs(0)
rdfs(N - 1)
flag = [ok_1[i] & ok_n[i] for i in range(N)]

# Bellman ford
INF = 10 ** 9 + 7
d = [INF] * N
d[0] = 0
cnt = 0
updated = True
while updated and cnt <= N:
    updated = False
    cnt += 1
    for u in range(N):
        if not flag[u]:
            continue
        for v, c in edges[u]:
            if not flag[v]:
                continue

            value = d[u] + c
            if d[v] > d[u] + c:
                d[v] = value
                updated = True

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