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: Runtime Error

Solution code:
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
import sys
input = sys.stdin.readline


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

    edges = []
    routes = [[] for _ in range(n)]
    rev_routes = [[] for _ in range(n)]


    def get_reachable_nodes(start, routes):
        seen = {start}
        todo = []
        for to in routes[start]:
            todo.append(to)
            seen.add(to)

        while todo:
            node = todo.pop()
            for to in routes[node]:
                if to in seen:
                    continue
                todo.append(to)
                seen.add(to)
        return seen


    for _ in range(m):
        node1, node2, value = map(int, input().split())
        node1, node2, value = node1 - 1, node2 - 1, value - p
        edges.append([node1, node2, value])
        routes[node1].append(node2)
        rev_routes[node2].append(node1)

    from_start = get_reachable_nodes(0, routes)
    if n-1 not in from_start:
        print(-1)
        return

    to_goal = get_reachable_nodes(n-1, rev_routes)

    from_start_to_goal = from_start & to_goal

    values = []
    rows = []
    cols = []

    for row, col, value in edges:
        if {row, col} <= from_start_to_goal:
            rows.append(row)
            cols.append(col)
            values.append(-value)

    graph = coo_matrix((values, (rows, cols)))
    try:
        bf = bellman_ford(graph, indices=[0])
        print(max(0, -int(bf[0][n - 1])))
    except NegativeCycleError:
        print(-1)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

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

fwd = [[] for _ in range(n + 1)]
rev = [[] for _ in range(n + 1)]

for a, b, c in abc:
    fwd[a].append(b)
    rev[b].append(a)


def dfs(s, adj):
    stack = [s]
    arrived = [False] * (n + 1)
    arrived[s] = True
    while stack:
        u = stack.pop()
        for v in adj[u]:
            if not arrived[v]:
                arrived[v] = True
                stack.append(v)

    return arrived


can_go_fwd = dfs(1, fwd)
can_go_rev = dfs(n, rev)

row = []
col = []
cost = []
for a, b, c in abc:
    if can_go_fwd[a] and can_go_rev[b]:
        row.append(a)
        col.append(b)
        cost.append(p - c)

g = csr_matrix((cost, (row, col)), shape=(n + 1, n + 1))
try:
    dist = bellman_ford(g, indices=1).astype(int)
    ans = max(0, -dist[n])
    print(ans)
except NegativeCycleError:
    print(-1)

Submission status: Runtime Error

Solution code:
INF = 10**18

def dfs1(cur):
    for to in G1[cur]:
        if done1[to]: continue
        done1[to] = True
        dfs1(to)

def dfs2(cur):
    for to in G2[cur]:
        if done2[to]: continue
        done2[to] = True
        dfs2(to)

N, M, P = map(int, input().split())
G = []
G1 = [[] for i in range(N)]
G2 = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    G.append((a, b, c-P))
    G1[a].append(b)
    G2[b].append(a)
D = [0]*N
for i in range(N):
    D[i] = -INF
D[0] = 0
for i in range(N):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
done1 = [False]*N
done1[0] = True
dfs1(0)
done2 = [False]*N
done2[N-1] = True
dfs2(N-1)
for _ in range(N):
    for j in range(M):
        fr, to, cost = G[j]
        if D[fr] != -INF and D[fr]+cost > D[to]:
            D[to] = D[fr]+cost
            if done1[to] and done2[to]:
                print(-1)
                exit()
if D[N-1] < 0:
    print(0)
else:
    print(D[N-1])

Submission status: Runtime Error

Solution code:
# Coins Respawn

from collections import deque
N, M, P = map(int, input().split())
graph = []
d = deque()

# グラフの整形

from_1 = [[] for i in range(N+1)]
from_N = [[] for i in range(N+1)]

for _ in range(M):
    a, b, c = map(int, input().split())
    from_1[a].append(b)
    from_N[b].append(a)
    d.append((a, b, P-c))


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True


while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        graph.append((p, q, weight))

# ベルマンフォード


def bellman_ford(s,n):
    dist = [10**20 for i in range(n+1)]
    dist[s] = 0
    for i in range(1, n+1):
        flag = False
        for some in graph:
            a, b, d = some[0], some[1], some[2]
            newlen = dist[a]+d
            if newlen < dist[b]:
                flag = True
                dist[b] = newlen
        if not flag:
            break
        if i == n:
            return False
    return dist

K=bellman_ford(1,N)
if K==False:
     print(-1)
else:
    print(max(0,-K[N]))

Submission status: Runtime Error

Solution code:
import sys
N,M,P = map(int,input().split())
N-=1 #頂点番号を0スタートに
INF = float("inf")
edge = []
to = [[] for _ in range(N+1)] #普通に移動できる点
rto = [[] for _ in range(N+1)] #逆に戻れる点
reachablefrom = [False for _ in range(N+1)] #始点0から終点N-1へ行けるかチェック
reachableto = [False for _ in range(N+1)] #終点N-1から始点0へ戻れるかチェック
OK = [False for _ in range(N+1)] #どちらからもいける点を検出。ここ以外の点はどうでもよい。
for i in range(M):
  a,b,c = map(int,input().split())
  a-=1;b-=1 #頂点番号を0スタートに
  c-=P #ここで先に最後に払う分を引いておく。
  c = -c #最短経路にしたいのでコストを負にする。
  edge.append((a,b,c))
  to[a].append(b)
  rto[b].append(a)

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

def rdfs(v):
  if reachableto[v]:
    return
  reachableto[v] = True
  for u in rto[v]:
    rdfs(u)
    
dfs(0)
rdfs(N)
for i in range(len(OK)): #len(OK)でもまあ良いか。
  OK[i] = reachablefrom[i]&reachableto[i]
#ここからベルマンフォード法
d = [INF for _ in range(N+1)]
d[0] = 0 #スタートのコストは0
upd = True #サイクルで更新の有無をチェック
step = 0
while upd:
  upd = False
  for i in range(M):
    a,b,c = edge[i]
    if not OK[a] or not OK[b]:
      continue
    new = d[a]+c
    if new < d[b]: #aから来たほうが最短
      upd = True
      d[b] = new
  step += 1
  if step > N:
    print("-1")
    sys.exit()
ans = -d[N] #最後、コストをマイナスで戻す
ans = max(0,ans)
print(ans)

Submission status: Runtime Error

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

INF = 10 ** 4

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/0)
    print(-1)
    sys.exit()

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

Submission status: Runtime Error

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

INF = 10 ** 4

class Edge():
    def __init__(self, end, cost):
        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)]
g3 = [[] for _ in range(n)]
g4 = [[] for _ in range(n)]

abc = []

for _ in range(m):
    a, b, c = map(int, input().split())
    abc.append((a-1, b-1, c))
    g1[a-1].append(Edge(b-1, 1))
    g2[b-1].append(Edge(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)

H = [0] * n
cnt = 0
for a, b, c in abc:
    if a in ng or b in ng:
        continue
    cnt += 1
    g3[a].append(Edge(b, c))
    g4[b].append(Edge(a, c-p))
    H[b] += 1

stack = deque([])
topo = []

for i, hi in enumerate(H):
    if hi == 0:
        stack.append(i)

while stack:
    v = stack.pop()
    topo.append(v)
    for e in g3[v]:
        H[e.end] -= 1
        if H[e.end] == 0:
            stack.append(e.end)   

if len(topo) < cnt:
    print(1/0)
    print(-1)
    sys.exit()

f = 0
dp = ['null'] * n
dp[0] = 0

for v in topo:
    if f:
        dp[v] = 0
        for e in g4[v]:
            if e.end == 0 or dp[e.end] != "null":
                dp[v] = max(dp[v], dp[e.end] + e.cost)
    if v == 0:
        f = 1

print(dp[n-1])

Submission status: Runtime Error

Solution code:
import sys
import math
import bisect
import heapq
from collections import deque
stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

N,M,P=nm()

reachable=[False]*2505
reachableN=[False]*2505
ok=[False]*N
to=[[] for _ in range(2505)]
rto=[[] for _ in range(2505)]
edge=[[] for _ in range(M)]
for i in range(M):
    A,B,C=nm()
    to[A-1].append(B-1)
    rto[B-1].append(A-1)
    edge[A-1].append((B-1,C-P))


def dfs(v):
    if(reachable[v]):
        return
    reachable[v]=True
    for i in to[v]:
        dfs(i)

def rdfs(v):
    if(reachableN[v]):
        return
    reachableN[v]=True
    for i in rto[v]:
        rdfs(i)

    
def bfs(start,edge):
    INF=10**18
    money=[-INF]*N
    money[start]=0
    arrived=[-1]*N
    q=deque([start])
    while (q):
        e=q.popleft()
        for i in edge[e]:
            if(ok[i[0]]==False):
                continue
            if(money[i[0]]<money[e]+i[1]):
                if(arrived[i[0]]==0):
                        print(-1)
                        sys.exit(0)
                money[i[0]]=money[e]+i[1]
                arrived[i[0]]=0
                q.append(i[0])
    return money

dfs(0)
rdfs(N-1)
for i in range(N):    
    ok[i]=(reachable[i] and reachableN[i])
money=bfs(0,edge)
print(max(0,money[N-1]))

Submission status: Runtime Error

Solution code:
import sys
import math
import bisect
import heapq
from collections import deque
stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

N,M,P=nm()
edge=[[] for _ in range(M)]
for i in range(M):
    A,B,C=nm()
    edge[A-1].append((B-1,C-P))


def bfs(start,edge):
    INF=10**18
    money=[-INF]*N
    money[start]=0
    arrived=[-1]*N
    q=deque([start])
    while (q):
        e=q.popleft()
        for i in edge[e]:
            if(money[i[0]]<money[e]+i[1]):
                if(arrived[i[0]]==0):
                    print(-1)
                    sys.exit(0)
                money[i[0]]=money[e]+i[1]
                arrived[i[0]]=0
                q.append(i[0])
    return money

money=bfs(0,edge)
print(money[N-1])

Submission status: Runtime Error

Solution code:
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""

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

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(n)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1; b -= 1
    c -= p
    c = -c
    edges.append((a,b,c))
    to[a].append(b) # 到達可能性を判定するための変数
    rto[b].append(a) # nに辿り着けるかを判定するための変数
    
dfs(0)
rdfs(n-1)
for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] # okになっている頂点だけを考える
# ベルマンフォード
def main():
    global edges, ok
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 # 負閉路検出用。更新回数がnステップを超えたら負閉路あり
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    return
    
main()

Submission status: Runtime Error

Solution code:
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""

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

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1; b -= 1
    c -= p
    c = -c
    edges.append((a,b,c))
    to[a].append(b) # 到達可能性を判定するための変数
    rto[b].append(a) # nに辿り着けるかを判定するための変数
    
dfs(0)
rdfs(n-1)

for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] # okになっている頂点だけを考える

# ベルマンフォード
def main():
    global edges, ok
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 # 負閉路検出用。更新回数がnステップを超えたら負閉路あり
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    return
    
main()

Submission status: Runtime Error

Solution code:
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""

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

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1; b -= 1
    c -= p
    c = -c
    edges.append((a,b,c))
    to[a].append(b) # 到達可能性を判定するための変数
    rto[b].append(a) # nに辿り着けるかを判定するための変数
    
dfs(0)
rdfs(n-1)

for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] # okになっている頂点だけを考える

# ベルマンフォード
def main():
    global edges
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 # 負閉路検出用。更新回数がnステップを超えたら負閉路あり
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    return
    
main()

Submission status: Runtime Error

Solution code:
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""

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

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1; b -= 1
    c -= p
    c = -c
    edges.append((a,b,c))
    to[a].append(b) # 到達可能性を判定するための変数
    rto[b].append(a) # nに辿り着けるかを判定するための変数
    
dfs(0)
rdfs(n-1)

for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] # okになっている頂点だけを考える

# ベルマンフォード
def main():
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 # 負閉路検出用。更新回数がnステップを超えたら負閉路あり
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    
main()

Submission status: Runtime Error

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]+cost:
                d[b]=d[a]+cost
    for i in range(n-1):
         for a,b,c in edge:
            if d[b]>d[a]+cost:
                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: Runtime Error

Solution code:
def get_path(start, goal, pred):
    return get_path_row(start, goal, pred)


def get_path_row(start, goal, pred_row):
    path = []
    i = goal
    while i != start and i >= 0:
        path.append(i)
        i = pred_row[i]
    if i < 0:
        return []
    path.append(i)
    return path[::-1]


def main():
    from scipy.sparse.csgraph import bellman_ford
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph._shortest_path import NegativeCycleError
    import sys
    input = sys.stdin.buffer.readline
    N, M, P = (int(i) for i in input().split())
    g = [[10**6]*N for _ in range(N)]
    ban_v = set()
    for i in range(M):
        a, b, c = (int(i) for i in input().split())
        c -= P
        if a == b:
            ban_v.add(a-1)
        else:
            g[a-1][b-1] = -c

    csr = csr_matrix(g)
    ans = -1
    try:
        dist, p = bellman_ford(csr, indices=0, return_predecessors=True)
        path = get_path(0, N-1, p)
        if any(v in ban_v for v in path):
            ans = -1
        else:
            ans = max(0, int(dist[N-1]*-1))
    except NegativeCycleError:
        ans = -1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

INF = 10**10
# Bellman-Fordをするときは、辺集合を持つ
edges = [] 
# 1から行けない辺やNに到達できない辺を削除するための探索をする用
to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

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

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

for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1; b -= 1
    c -= P
    c = -c # 最短路にするため符号を逆転
    edges.append([a, b, c])
    to[a].append(b)
    rto[b].append(a)

# 考えるべき頂点だけ洗い出し
dfs(0)
rdfs(N-1)
for i in range(N):
    ok[i] = reachableFrom1[i] & reachableToN[i]

# Bellman-Ford
d = [INF for _ in range(N)]
d[0] = 0
upd = True
step = 0
flag = True
while upd:
    upd = False
    for i in range(M):
        a, b, c = edges[i]
        if not ok[a]:
            continue
        if not ok[b]:
            continue
        newD = d[a]+c
        if newD < d[b]:
            upd = True
            d[b] = newD
    step += 1
    if step > N:
        flag = False
        break
if flag:
    ans = -d[N-1]
    ans = max(ans, 0)
    print(ans)
else:
    print(-1)

Submission status: Runtime Error

Solution code:

"""

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

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

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

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

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

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: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
N,M,P=map(int,input().split())

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

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

visited=[None]*(N+1)
def check_reachable(u,ls):
  if u==N:
    #print(ls+[u])
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    if reachable[v]!=None:
      ret=reachable[v]
    elif not visited[v]:
      ret=check_reachable(v,ls+[u])
    if ret:        
      cnt+=1
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    reachable[u]=False
    return False
  
reachable=[None]*(N+1)
for i in range(1,N+1):
#for i in range(23,24):
  if reachable[i]==None:
    visited=[False]*(N+1)
    check_reachable(i,[])
#print(reachable)
#print(reachable[23])
#sys.exit(0)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

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

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Runtime Error

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

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

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

visited=[None]*(N+1)
def check_reachable(u):
  if u==N:
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    if not visited[v]:
      ret=check_reachable(v)
      if ret:        
        cnt+=1
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    #reachable[u]=False #入れるとエラー
    return False
  
reachable=[False]*(N+1)
for i in range(1,N+1):
  if not reachable[i]:
    visited=[False]*(N+1)
    check_reachable(i)
#print(reachable)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

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

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
chk = []
for i in range(n):
  a,b =  map(int,input().split())
  if a <= m:
    chk.append((a,b))

from heapq import heappop, heappush
from operator import itemgetter
chk = sorted(chk,key=itemgetter(0),reverse=True)

q = []
ans = 0
for i in range(1, m + 1):
    while chk and chk[-1][0] <= i:
        a,b = chk.pop()
        heappush(q,-b)
    if q:
        ans -= heappop(q)
print(ans)