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:
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
    from itertools import product
    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)]
    adj_list = [[] for _ in range(N)]
    radj_list = [[] for _ in range(N)]
    ok = [False]*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
            adj_list[a-1].append(b-1)
            radj_list[b-1].append(a-1)

    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

    for i, s, rs in product(range(N), dfs(adj_list, 0), dfs(radj_list, N-1)):
        if s and rs:
            ok[i] = True

    for i in range(N):
        if ok[i]:
            continue
        for j in range(N):
            g[i][j] = 10**6

    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:
def get_path(start, goal, pred):
    return get_path_row(start, goal, pred[start])


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, 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[0][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())
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]))

Submission status: Runtime Error

Solution code:
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]))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
import heapq
def input(): return sys.stdin.readline().strip()


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

    """
    あらかじめ各辺のコイン枚数からP引いておけば、求めるのは単純にコイン枚数の最大値となる。
    すなわちこれは「最長経路問題」に他ならない。
    するとコイン枚数を(-1)倍して「最短経路問題」を求めればよく典型問題に帰着。
        ダイクストラ　　　→　負辺があるのでダメ
        ベルマンフォード　→　O(VE)で解けるので今回はこれ
        ワ―シャルフロイド →　O(V^3)なので間に合わない

    ベルマンフォード復習：
        １．スタートする頂点をsとしてd[s] = 0、その他の頂点はd[v] = \inftyで初期化
        ２．重みwの辺u→vに対してd[v] = min(d[v], d[u] + w)
        ３．この更新を「すべての辺」（E本）に対して行う
        ４．２－３ステップをN（頂点数）回繰り返すと値の更新が（負閉路を除き）収束する
    
    ただし本問では負閉路検出後にそれが1-(負閉路)-Nのように頂点1と頂点Nの間にいることを
    確認する必要がある。
    """

    edges = [] # ベルマンフォードするなら頂点よりも辺が主役なので
    repn = [[] for _ in range(N)]
    reverse_repn = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        repn[a - 1].append(b - 1)
        reverse_repn[b - 1].append(a - 1)
        edges.append((a - 1, b - 1, P - c))

    """
    後々必要なので、頂点0「から」たどり着ける頂点と、
    頂点(N-1)「に」たどり着ける頂点をそれぞれ列挙する
    """

    reachable_from_1 = [0] * N
    reachable_to_N = [0] * N
    ok = [0] * N # 始点と終点の間にいる頂点（ここだけ考慮すれば十分）

    def dfs(v):
        if reachable_from_1[v]:
            return
        reachable_from_1[v] = 1
        for u in repn[v]:
            dfs(u)
    
    def reverse_dfs(v):
        if reachable_to_N[v]:
            return
        reachable_to_N[v] = 1
        for u in reverse_repn[v]:
            reverse_dfs(u)
    
    dfs(0)
    reverse_dfs(N - 1)
    for i in range(N):
        if reachable_from_1[i] and reachable_to_N[i]:
            ok[i] = 1

    """
    ここからベルマンフォード
    """

    d = [float("inf")] * N
    d[0] = 0
    step = 0
    update = True
    while update:
        update = False
        for i in range(M):
            a, b, cost = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            new_cost = d[a] + cost
            if new_cost < d[b]:
                update = True
                d[b] = new_cost
        step += 1
        if step > N:
            print(-1)
            return
    print(max(0, -d[N - 1]))


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

def bellmanford(G, s, N):
    n = len(G)
    inf = float('inf')
    dist = [inf] * n
    dist[s] = 0
    for i in range(n+1):
        for v in range(n):
            for w, c in G[v]:
                if dist[w] > dist[v] + c:
                    dist[w] = dist[v] + c
                    if i == n and w == N - 1:
                        return False
    return dist

def bellmanford(G, s):
    n = len(G)
    inf = float('inf')
    dist = [inf] * n
    dist[s] = 0
    for i in range(n):
        for v in range(n):
            for w, c in G[v]:
                if dist[w] > dist[v] + c:
                    dist[w] = dist[v] + c
                    if i == n - 1 and w == n - 1:
                        return -1
    return dist

def main():
    N, M, P = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        G[a].append((b, -c+P))
    ans = bellmanford(G, 0, N)
    if ans:
        print(max(0, -ans[N-1]))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n,m,p = map(int,input().split())
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError
# キュー
from collections import deque

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

can_go_1 = set()
can_go_n = set()

d = deque()
d.append(1)
while(d):
    tmp = d.pop()
    can_go_1.add(tmp)
    for i in graph[tmp]:
        if(not i in can_go_1):
            d.append(i)

d = deque()
d.append(n)
while(d):
    tmp = d.pop()
    can_go_n.add(tmp)
    for i in graph_rev[tmp]:
        if(not i in can_go_n):
            d.append(i)

can_go = can_go_1 & can_go_n

data = []
row = []
col = []
for tmp in abc:
    a,b,c = tmp
    if(a in can_go)&(b in can_go):
        data.append(c)
        row.append(a)
        col.append(b)

csr_graph = csr_matrix((data, (row,col)), shape=(n+1,n+1))
try:
    bf = bellman_ford(csr_graph, indices=1)
except NegativeCycleError:
    print(-1)
    exit()

ans = int(bf[-1]) * -1
print(max(0,ans))

Submission status: Runtime Error

Solution code:
, m, p = map(int, input().split())
abcs = [list(map(int, input().split())) for _ in range(m)]
distance = [-100000 * n] * (n + 1)

distance[1] = 0
for _ in range(n + 1):
    for a, b, c in abcs:
        if distance[b] < distance[a] + c - p:
            distance[b] = distance[a] + c - p

ret = distance[n]
for _ in range(n + 1):
    for a, b, c in abcs:
        if distance[b] < distance[a] + c - p:
            distance[b] = distance[a] + c - p

print(-1 if ret != distance[n] else max(ret, 0))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n,m,p = map(int,input().split())
abd = [list(map(int,input().split())) for i in range(m)]
come = [[] for i in range(n+1)]
for a,b,d in abd:
  come[b].append(a)
visitable = [0]*(n+1)
stack = [n]
visitable[n] = 1
while stack:
  x = stack.pop()
  for y in come[x]:
    if visitable[y] == 0:
      visitable[y] = 1
      stack.append(y)
score = [10**15 for i in range(n+1)]
score[1] = 0
for j in range(n+1):
  flg = 0
  for i in range(m):
    v1,v2,e = abd[i]
    if visitable[v1] & visitable[v2] == 0:
      continue 
    e = -e+p
    if score[v1] != 10**15 and score[v2] > score[v1]+e:
      score[v2] = score[v1]+e
      flg = 1
      if j == n-1:
        last = -score[n]
      if j == n:
        onemore = -score[n]
  if flg == 0:
    break
if flg == 0:
  print(max(0,-score[n]))
else:
  if last == onemore:
    print(max(last,0))
  else:
    print(2/0)

Submission status: Runtime Error

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

dis1 = [False]*n
def dfs1(x):
    if dis1[x] == False:
        dis1[x] = True
        for nex in E1[x]:
            dfs1(nex)

dis2 = [False]*n
def dfs2(x):
    if dis2[x] == False:
        dis2[x] = True
        for nex in E2[x]:
            dfs2(nex)

dfs1(0)
dfs2(n-1)

ok = []
for i in  range(n):
    if dis1[i] == True and dis2[i] == True:
        ok.append(True)
    else:
        ok.append(False)
nedge = []
for a,b,c in edge:
    if ok[a] and ok[b]:
        nedge.append((a,b,c))

def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in nedge:
            
            if dis[a] != float("INF") and dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n+1 and check:
            return float("INF")
    
    return -dis[-1]

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

Submission status: Runtime Error

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

dis1 = [False]*n
def dfs1(x):
    if dis1[x] == True:
        return
    dis1[x] = True
    for nex in E1[x]:
        dfs1(nex)

dis2 = [False]*n
def dfs2(x):
    if dis2[x] == True:
        return
    dis2[x] = True
    for nex in E2[x]:
        dfs2(nex)

dfs1(0)
dfs2(n-1)

ok = []
for i,j in zip(dis1,dis2):
    if i == True and j == True:
        ok.append(True)
    else:
        ok.append(False)
nedge = []
for a,b,c in edge:
    if ok[a] and ok[b]:
        nedge.append((a,b,c))

edge = nedge
def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in edge:
            
            if dis[a] != float("INF") and dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n+1 and check:
            return float("INF")
    
    return -dis[-1]

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

Submission status: Runtime Error

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

dis1 = [False]*n
def dfs1(x):
    if dis1[x] == True:
        return
    dis1[x] = True
    for nex in E1[x]:
        dfs1(nex)

dis2 = [False]*n
def dfs2(x):
    if dis2[x] == True:
        return
    dis2[x] = True
    for nex in E2[x]:
        dfs2(nex)

dfs1(0)
dfs2(n-1)

ok = []
for i,j in zip(dis1,dis2):
    if i == True and j == True:
        ok.append(True)
    else:
        ok.append(False)

def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in edge:
            if (not ok[a]) or (not ok[b]):
                continue
            if dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n+1 and check:
            return float("INF")
    
    return -dis[-1]

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

Submission status: Runtime Error

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

dis1 = [False]*n
def dfs(x,dis,E):
    if dis[x] == True:
        return
    dis[x] = True
    for nex in E[x]:
        dfs(nex,dis,E)

dis2 = [False]*n

dfs(0,dis1,E1)
dfs(n-1,dis2,E2)

ok = []
for i,j in zip(dis1,dis2):
    if i == True and j == True:
        ok.append(True)
    else:
        ok.append(False)

def belw():
    dis = [float("INF")]*n
    dis[0] = 0
    count = 0
    check = True

    while check:
        check = False
        for a,b,c in edge:
            if (not ok[a]) or (not ok[b]):
                continue
            if dis[b] > dis[a]+c:
                check = True
                dis[b] = dis[a]+c
        count += 1

        if count > n:
            return float("INF")
    
    return -dis[-1]

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

Submission status: Runtime Error

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Bellman_Ford(s,n,w,es,ppp):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [Max] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    po = 0
    while po < 2*N + 2*M:
        update = False
        for p,q,r in es:
        # e: 辺iについて [from,to,cost]
            if d[p] != Max and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
                if (ppp[q] != -1 and po > N):
                    d[-1] = None
                    update = False
                    break
        if not update:
            break
        po += 1
    return d

import heapq

def dijkstra(n,w,e):
    #n:辺数,w:スタート一

    edge = [[] for i in range(n)]
    dg = 10**18
    # edge[i]:[コスト]
    for i in e:
        x,y = i
        z = 1
        x -= 1
        y -= 1
        edge[x].append(dg + y)
        
    
    s = w-1
    d = [-1]*n
    
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,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




N,M,P = m()

es = []
ess = []

for _ in range(M):

    x,y,z = map(int,input().split())

    x -= 1
    y -= 1
    es.append([x,y,-z+P])
    ess.append([y,x])


ppp = dijkstra(M,M,ess)
po = Bellman_Ford(0,N,M,es,ppp)


print(-1 if po[-1] == None else -po[-1] if po[-1] <= 0 else 0)

Submission status: Runtime Error

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    if len(x) == 0:
        return []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def Bellman_Ford(s,n,w,es,ppp):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [Max] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    po = 0
    while po < 2*N + 2*M:
        update = False
        for p,q,r in es:
        # e: 辺iについて [from,to,cost]
            if d[p] != Max and d[q] > d[p] + r:
                d[q] = d[p] + r
                update = True
                if (ppp[q] != -1 and po > N):
                    
                    d[-1] = None
                    update = False
                    break
        if not update:
            break
        po += 1
    return d

import heapq

def dijkstra(n,w,e):
    #n:辺数,w:スタート一

    edge = [[] for i in range(n)]
    dg = 10**18
    # edge[i]:[コスト]
    for i in e:
        x,y = i
        z = 1
        x -= 1
        y -= 1
        edge[x].append(dg + y)
        
    
    s = w-1
    d = [-1]*n
    
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,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




N,M,P = m()

es = []
ess = []
for _ in range(M):

    x,y,z = map(int,input().split())

    x -= 1
    y -= 1
    es.append([x,y,-z+P])
    ess.append([x,y])

ppp = dijkstra(M,M,ess)
po = Bellman_Ford(0,N,M,es,ppp)


print(-1 if po[-1] == None else -po[-1] if po[-1] <= 0 else 0)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
edges = []
to = defaultdict(list) # 1から到達できるか
ot = defaultdict(list) # Nから到達できるか
N, M, P = map(int, input().split())
visited_toN = [False]*(N+1)
visited_fm1 = [False]*(N+1)    
for i in range(M):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append((a,b,-c+P))
    to[a].append(b)
    ot[b].append(a)

def dfs(v):
    global visited_fm1
    if visited_fm1[v]:return
    visited_fm1[v] = True
    for nxt in to[v]:
        dfs(nxt)
    
def dfs_r(v):
    global visited_toN
    if visited_toN[v]:return
    visited_toN[v] = True
    for nxt in ot[v]:
        dfs_r(nxt)
        
dfs(0)
dfs_r(N-1)
is_ok = []

for s, t in zip(visited_fm1,visited_toN):
    is_ok.append(s and t)


# BellmanFord    
INF = 10 ** 18
def bellmanFord(n, edges, s, g):
    """
    input
        n : 頂点の数
        edges : (始点, 終点, コスト)のリスト
        s : 探索の始点
        g : 探索の終点
    output
        sから各点への最短距離
    """    
    d = [INF] * n
    d[s] = 0
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if not is_ok[a]:continue
            if not is_ok[b]:continue
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt > n:
            print(-1)
            exit()
        # print(d,cnt)
    return d[g]



ans = bellmanFord(N,edges,0,N-1)
print(max(0,-ans))

Submission status: Runtime Error

Solution code:
from collections import defaultdict
edges = []
to = defaultdict(list) # 1から到達できるか
ot = defaultdict(list) # Nから到達できるか
N, M, P = map(int, input().split())
visited_toN = [False]*(N+1)
visited_fm1 = [False]*(N+1)    
for i in range(M):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append((a,b,-c+P))
    to[a].append(b)
    ot[b].append(a)

def dfs(v):
    global visited_fm1
    if visited_fm1[v]:return
    visited_fm1[v] = True
    for nxt in to[v]:
        dfs(nxt)
    
def dfs_r(v):
    global visited_toN
    if visited_toN[v]:return
    visited_toN[v] = True
    for nxt in ot[v]:
        dfs_r(nxt)
        
dfs(0)
dfs_r(N-1)
is_ok = []

for s, t in zip(visited_fm1,visited_toN):
    is_ok.append(s&t)


# BellmanFord    
INF = 10 ** 18
def bellmanFord(n, edges, s, g):
    """
    input
        n : 頂点の数
        edges : (始点, 終点, コスト)のリスト
        s : 探索の始点
        g : 探索の終点
    output
        sから各点への最短距離
    """    
    d = [INF] * n
    d[s] = 0
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if not is_ok[a]:continue
            if not is_ok[b]:continue
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt == n:
            print(-1)
            exit()
        # print(d,cnt)
    return d[g]



ans = bellmanFord(N,edges,0,N-1)
print(max(0,-ans))

Submission status: Runtime Error

Solution code:
mod = 10 ** 9 + 7
from collections import deque


def main():
    N, M = iip(False)
    A = []
    for i in range(N):
        A.append(iip(True))

    ret = solve(N, M, A)
    print(ret)


def solve(N, M, A):
    A = sorted(A, key=lambda x: x[1], reverse=True)

    sch = [False] * M

    ret = 0
    for nouki, money in A:
        day = M - nouki
        if day < 0:
            continue

        do = True
        while True:
            if sch[day]:
                day -= 1
            else:
                break
            if day == -1:
                do = False
                break
        if not do:
            continue

        sch[day] = True
        ret += money

        # print(nouki, money)

    return ret


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2) ** 2) % mod
    if p % 2 == 1:
        return (n * power(n, p - 1)) % mod


if __name__ == "__main__":
    main()