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: Wrong Answer

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

def main():
    N, M, P = map( int, input().split())
    d = dict()
    for _ in range(M):
        a, b, c = map( int, input().split())
        a, b = a-1, b-1
        d[(a,b)] = P-c

    V = [None]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    W = [V[i] for i in range(N)]

    for e in d:
        s, t = e
        if V[s] == None:
            continue
        if V[t] == None:
            V[t] = V[s] + d[e]
            continue
        if V[s] + d[e] < V[t]:
            V[t] = V[s] + d[e]
    for i in range(N):
        if V[i] == None:
            continue
        if V[i] < W[i]:
            V[i] = -10**14
    for _ in range(N):
        for e in d:
            s, t = e
            if V[s] == None:
                continue
            if V[t] == None:
                V[t] = V[s] + d[e]
                continue
            if V[s] + d[e] < V[t]:
                V[t] = V[s] + d[e]
    # ans = V[N-1]
    # for _ in range(N):
    #     for e in d:
    #         s, t = e
    #         if V[s] + d[e] < V[t]:
    #             V[t] = V[s] + d[e]

    # if V[N-1] < ans:
    #     print(-1)
    #     return
    # print( max(-ans,0))
    if V[-1] <= -10**14:
        print(-1)
    else:
        print(max(-V[-1],0))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N,M,P = map(int, input().split())
R = []
OPT = [float("inf")]*(N+1)
for _ in range(M):
    A,B,C = map(int, input().split())
    R.append([A,B,-C+P])

OPT[1] = 0
OPT_tmp = OPT

for _ in range(N-1):
    for i in range(M):
        tmp_r = R[i]
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
tmp_opt = OPT[N]

for _ in range(2*N):
    for i in range(M):
        tmp_r = R[i]
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
    
if tmp_opt > OPT[N]:
    answer = -1
else:
    answer = max(0,-tmp_opt)

print(answer)

Submission status: Wrong Answer

Solution code:
N,M,P = map(int, input().split())
R = []
OPT = [float("inf")]*(N+1)
for _ in range(M):
    A,B,C = map(int, input().split())
    R.append([A,B,-C+P])

OPT[1] = 0
OPT_tmp = OPT

for _ in range(N-1):
    for i in range(M):
        tmp_r = R[i]
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
tmp_opt = OPT[N]

for _ in range(N-1):
    for i in range(M):
        tmp_r = R[i]
        if OPT[tmp_r[0]] + tmp_r[2] < OPT[tmp_r[1]]:
            OPT[tmp_r[1]] = OPT[tmp_r[0]] + tmp_r[2]
    OPT = OPT_tmp
    
if tmp_opt > OPT[N]:
    answer = -1
else:
    answer = max(0,-tmp_opt)

print(answer)

Submission status: Wrong Answer

Solution code:
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
G = [{} for _ in range(N)]
for abc in ABC:
    a, b, c = abc
    a -= 1
    b -= 1
    G[a][b] = c - P


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [-INF] * V
    D[i] = 0
    ans= []
    for cycle in range(2):
        for _ in range(V - 1):
            update = False
            for fr in range(V):
                for to in G[fr]:
                    if D[fr] != -INF and D[to] < D[fr] + G[fr][to]:
                        if cycle == 1:
                            D[to] = INF
                        else:
                            D[to] = D[fr] + G[fr][to]
                        update = True
            if not update:
                break
        ans += [D[V - 1]]
    if ans[0] == ans[1]:
        return ans[0]
    else:
        return False


ans = bellman_ford(N, G, 0)
if ans is False:
    print(-1)
else:
    print(max(0, ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
revedgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  revedgedict[t-1][f-1] = 1

# Nに到達できない頂点を削除
visited = [False] * N
def dfs(f):
  visited[f] = True
  for t in revedgedict[f].keys():
    if not visited[t]:
      dfs(t)
dfs(N-1)

# ベルマンフォード
INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(M):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and visited[t] and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
revedgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  revedgedict[f-1][t-1] = 1

# Nに到達できない頂点を削除
visited = [False] * N
def dfs(f):
  visited[f] = True
  for t in revedgedict[f].keys():
    if not visited[t]:
      dfs(t)
dfs(N-1)

# ベルマンフォード
INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(M):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and visited[t] and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c



def dfs(graph, start, goal):
    que = deque()
    que.append(start)
    reached = set()
    while que:
        edges = que.popleft()
        for to, cost in enumerate(graph[edges]):
            if cost != -float('inf') and to not in reached:
                que.append(to)
                reached.add(to)
    if goal in reached:
        return True
    else:
        return False


dist = [-float('inf')] * n
dist[0] = 0
update_points = []
ans = 0
flag = True
for time in range(1, n+1):
    if not flag:
        break
    new_dist = [-float('inf')] * n
    flag = False
    for before, cost in enumerate(dist):
        if before == -float('inf'):
            continue
        for to, cost in enumerate(graph[before]):
            if dist[before] + cost > new_dist[to]:
                new_dist[to] = dist[before] + cost
                flag = True
                if time == n:
                    update_points.append(to)
    dist = new_dist
    ans = max(new_dist[n-1] - time * p, ans)



flag = False
for i in update_points:
    if dfs(graph, i, n-1):
        print(-1)
        break
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
G = [{} for _ in range(N)]
for abc in ABC:
    a, b, c = abc
    a -= 1
    b -= 1
    G[a][b] = c - P


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [-INF] * V
    D[i] = 0
    ans= []
    for cycle in range(2):
        for _ in range(V - 1):
            update = False
            for fr in range(V):
                for to in G[fr]:
                    if D[fr] != -INF and D[to] < D[fr] + G[fr][to]:
                        D[to] = D[fr] + G[fr][to]
                        update = True
            if not update:
                break
        ans += [D[V - 1]]
    if ans[0] == ans[1]:
        return ans[0]
    else:
        return False


ans = bellman_ford(N, G, 0)
if ans is False:
    print(-1)
else:
    print(max(0, ans))

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c



def dfs(graph, start, goal):
    que = deque()
    que.append(start)
    reached = set()
    while que:
        edges = que.popleft()
        for to, cost in enumerate(graph[edges]):
            if cost != -float('inf') and to not in reached:
                que.append(to)
                reached.add(to)
    if goal in reached:
        return True
    else:
        return False


dist = [-float('inf')] * n
dist[0] = 0
update_points = []
ans = 0
flag = True
for time in range(1, n+1):
    if not flag:
        break
    new_dist = [-float('inf')] * n
    flag = False
    for before, edges in enumerate(graph):
        for to, cost in enumerate(edges):
            if dist[before] + cost > new_dist[to]:
                new_dist[to] = dist[before] + cost
                flag = True
                if time == n:
                    update_points.append(to)
    dist = new_dist
    ans = max(new_dist[n-1] - time * p, ans)



flag = False
for i in update_points:
    if dfs(graph, i, n-1):
        print(-1)
        break
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N, M, P = [int(_) for _ in input().split()]
ABC = [[int(_) for _ in input().split()] for _ in range(M)]
G = [{} for _ in range(N)]
for abc in ABC:
    a, b, c = abc
    a -= 1
    b -= 1
    G[a][b] = c - P


def bellman_ford(V, G, i):
    INF = float('inf')
    D = [-INF] * V
    D[i] = 0
    back = [None] * V
    for cycle in range(2):
        for _ in range(V - 1):
            update = False
            for fr in range(V):
                for to in G[fr]:
                    if D[fr] != -INF and D[to] < D[fr] + G[fr][to]:
                        if to == V - 1 and cycle == 1:
                            return False
                        D[to] = D[fr] + G[fr][to]
                        update = True
                        back[to] = fr
            if not update:
                return D[V - 1]
    return D[V - 1]


ans = bellman_ford(N, G, 0)
if ans is False:
    print(-1)
else:
    print(max(0, ans))

Submission status: Wrong Answer

Solution code:
from collections import deque


n, m, p = map(int, input().split())
graph = [[-float('inf')] * n for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a-1][b-1] = c



def dfs(graph, start, goal):
    que = deque()
    que.append(start)
    reached = set()
    while que:
        edges = que.popleft()
        for to, cost in enumerate(graph[edges]):
            if cost != -float('inf') and to not in reached:
                que.append(to)
                reached.add(to)
            if goal in reached:
                return True
    return False


dist = [-float('inf')] * n
dist[0] = 0
ans = -float('inf')
flag = True
for time in range(1, n+1):
    if not flag:
        break
    new_dist = [-float('inf')] * n
    flag = False
    for before, edges in enumerate(graph):
        for to, cost in enumerate(edges):
            if dist[before] + cost > dist[to]:
                new_dist[to] = dist[before] + cost
                flag = True
                if time == n:
                    update_points = []
                    update_points.append(to)
    ans = max(0, new_dist[n-1] - time * p, ans)



flag = False
for i in update_points:
    if dfs(graph, i, n-1):
        flag = True


if flag:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
rev = csr_matrix((data, (col, row)), (n, n))
use = set(csgraph.depth_first_order(rev, n-1, return_predecessors=False))
flag = np.array([r in use and c in use for r, c in zip(row, col)])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, indices=(0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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, float('inf'))

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

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
rev = csr_matrix((data, (col, row)), (n, n))
use = set(csgraph.depth_first_order(rev, n-1, True, False))
g = np.int64([(r, c, d)for r, c, d in zip(row, col, data) if r in use and c in use])
g = csr_matrix((g[:, 2], (g[:, 0], g[:, 1])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use
import numpy as np
from scipy.sparse import csr_matrix, csgraph
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
rev = [[]for _ in range(n)]
for a, b, c in zip(row, col, data):
    rev[b].append(a)
use = dfs(rev, n-1)
flag = np.array([r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use
import numpy as np
from scipy.sparse import csr_matrix, csgraph
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
edge = [[]for _ in range(n)]
edge_rev = [[]for _ in range(n)]
for a, b, c in zip(row, col, data):
    edge[a].append(b)
    edge_rev[b].append(a)
use = use = dfs(edge, 0) & dfs(edge_rev, n-1)
flag = np.array([r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
# 頂点sから到達する頂点の集合
def dfs(edge, s):
    use = {s}
    q = [s]
    while q:
        v = q.pop()
        for w in edge[v]:
            if w in use:continue
            use.add(w)
            q.append(w)
    return use

# ベルマンフォード法
def bellman_ford(v, s, t, e):
    # コストをINFで初期化
    d = [10**18] * v
    # 開始頂点は0
    d[s] = 0
    # 負の閉路が無ければ更新はV-1回までで終わる
    for _ in range(v):
        f = False
        for a, b, c in e:
            # aまでのコスト+辺abのコストがbまでのコストより小さければ更新
            cost = d[a] + c
            if cost < d[b]:
                d[b] = cost
                f = True
        # 更新が無ければbreak
        if not f:break
    else:
        # V回目まで更新があったら負の閉路がある
        return -1
    return max(-d[t], 0)

def main():
    import sys
    input = sys.stdin.readline
    n, m, p = map(int, input().split())
    edge = [[] for _ in range(n)]
    edge_rev = [[] for _ in range(n)]
    e = []
    for _ in range(m):
        a, b, c = map(int, input().split())
        edge[a-1].append(b-1)
        # 頂点Nからdfsするため辺の向きを逆にする
        edge_rev[b-1].append(a-1)
        e.append((a-1, b-1, p-c))
    """
    # 頂点1と頂点Nのどちらからも到達できる頂点の集合
    use = dfs(edge, 0) & dfs(edge_rev, n-1)
    # fromとtoがどちらもuseに含まれる辺のみ使う
    # そうすることで負の閉路を検出した場合答えは必ず-1になる
    """
    # ↑って思ってたけど頂点Nから到達できるか見るだけでいいらしいよ(えー)
    use = dfs(edge_rev, n-1)
    e = [(a, b, c) for a, b, c in e if a in use and b in use]
    print(bellman_ford(n, 0, n-1, e))   
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for r, c in zip(row, col)], '?')
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, int(-csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((np.ones(m), (row, col)), (n, n))
rev = csr_matrix((np.ones(m), (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for r, c in zip(row, col)])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
g = np.array([(r, c, d) for r, c, d in zip(row, col, data) if r in use and c in use])
g = csr_matrix((g[:, 2], (g[:, 0], g[:, 1])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
bfs = csgraph.breadth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(bfs(graph, 0, True, False)) & set(bfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for r, c in zip(row, col)])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([i for i, (r, c) in enumerate(zip(row, col))if r in use and c in use])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse import csr_matrix, csgraph
dfs = csgraph.depth_first_order
n, m, p, *t = map(int, open(0).read().split())
row = np.int64([a-1 for a in t[::3]])
col = np.int64([b-1 for b in t[1::3]])
data = np.int64([p-c for c in t[2::3]])
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for i, (r, c) in enumerate(zip(row, col))])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from scipy.sparse import csr_matrix, csgraph
input = sys.stdin.readline
dfs = csgraph.depth_first_order
n, m, p = map(int, input().split())
row = np.zeros(m)
col = np.zeros(m)
data = np.zeros(m)
for i in range(m):
    a, b, c = map(int, input().split())
    row[i] = a - 1
    col[i] = b - 1
    data[i] = p - c
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for i, (r, c) in enumerate(zip(row, col))])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g, True, (0,))[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from scipy.sparse import csr_matrix, csgraph
input = sys.stdin.readline
dfs = csgraph.depth_first_order
n, m, p = map(int, input().split())
row = np.zeros(m)
col = np.zeros(m)
data = np.zeros(m)
for i in range(m):
    a, b, c = map(int, input().split())
    row[i] = a - 1
    col[i] = b - 1
    data[i] = p - c
graph = csr_matrix((data, (row, col)), (n, n))
rev = csr_matrix((data, (col, row)), (n, n))
use = set(dfs(graph, 0, True, False)) & set(dfs(rev, n-1, True, False))
flag = np.array([r in use and c in use for i, (r, c) in enumerate(zip(row, col))])
g = csr_matrix((data[flag], (row[flag], col[flag])), (n, n))
try:
    print(max(0, -int(csgraph.bellman_ford(g)[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Wrong Answer

Solution code:
from math import isinf


class Edge(object):

    def __init__(self, src, dst, cost):
        self.src = src
        self.dst = dst
        self.cost = cost


class BellmanFord(object):

    def __init__(self, v_len, edges, start):
        """
        隣接行列を使っていないので、有向グラフにのみ適用可能。
        ベルマンフォード法によって最短経路を求める。
        ダイクストラと違って負の数も扱えるが、O(|V||E|) なのでダイクストラより遅い。

        :param v_len: グラフのノード数 通常は|V|、1-indexedなグラフなら |V| + 1
        :param edges: 辺のリスト
        :param start: 始点 単一視点最短経路問題として解くので必要
        """
        self._dist = [float('inf') for _ in range(v_len)]  # 始点から各頂点までの最短距離
        self._prev = [float('inf') for _ in range(v_len)]  # 最短経路における，その頂点の前の頂点のIDを格納する

        self._solve(edges, start)
        self.d = dict()
        for e in edges:
            self.d[(e.src, e.dst)] = e.cost

    def _solve(self, edges, start):
        self._dist[start] = 0

        cnt = 0
        while True:  # 更新は高々 |V| - 1 回で終わる
            cnt += 1
            updated = False
            for e in edges:
                if self._dist[e.src] + e.cost < self._dist[e.dst]:
                    self._dist[e.dst] = self._dist[e.src] + e.cost
                    self._prev[e.dst] = e.src
                    if cnt >= len(self._dist):
                        self._dist[e.dst] = float('-inf')
                    updated = True
            if not updated:
                break

    def distance(self, goal):
        """
        負の閉路を含む場合は -inf を返す。
        """
        return self._dist[goal]

    def path(self, goal):
        """
        負の閉路を含む場合は計算が終わらない。
        """
        path = list()
        path.append(goal)
        cursor = goal

        while not isinf(self._prev[cursor]):
            path.append(self._prev[cursor])
            cursor = self._prev[cursor]

        return list(reversed(path))

    def score(self, goal):
        s = 0
        p = self.path(goal)
        for i in range(len(p) - 1):
            s += self.d[(p[i], p[i + 1])]
        return s


N, M, P = map(int, input().split())
edges = list()
for _ in range(M):
    A, B, C = map(int, input().split())
    e = Edge(A, B, P - C)
    edges.append(e)
bf = BellmanFord(N + 1, edges, 1)

if isinf(bf.distance(N)):
    print(-1)
else:
    print(-min(0, bf.score(N)))

Submission status: Wrong Answer

Solution code:
def main():
    def dfs(edge,s):
        use={s}
        q=[s]
        while q:
            v=q.pop()
            for w in edge[v]:
                if w in use:continue
                use.add(w)
                q.append(w)
        return use
    n,m,p,*t=map(int,open(0).read().split())
    edge=[[]for _ in range(n)]
    edge_rev=[[]for _ in range(n)]
    e=[]
    for a,b,c in zip(t[::3],t[1::3],t[2::3]):
        edge[a-1].append(b-1)
        edge_rev[b-1].append(a-1)
        e.append((a-1,b-1,p-c))
    use=dfs(edge,0)&dfs(edge_rev,n-1)
    e=[(a,b,c)for a,b,c in e if a in use and b in use]
    INF=10**18
    d=[0]+[INF]*(n-1)
    for _ in range(n-1):
        f=False
        for a,b,c in e:
            cost=d[a]+c
            if cost<d[b]:
                d[b]=cost
                f=True
        if not f:break
    else:
        print(-1)
        exit()
    print(max(-d[-1],0))
main()

Submission status: Wrong Answer

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

N, M, P = [int(item) for item in input().split()]

from collections import defaultdict
next_b = defaultdict(lambda: [])

for i in range(M):
    a, b, c = [int(item) for item in input().split()]
    next_b[a].append([b, c - P])

max_sc = [0] + [int(-1e30)] * (N - 1)
route = [[0] * N] * N

pos_n = [0]
flag = 1

for loop in range(N):
    # print(max_sc)
    if not flag:
        print(max(max_sc[N - 1], 0))
        break
    flag = 0
    for i in pos_n:
        for d, scr in next_b[i + 1]:
            # print(route, d - 1, i)
            if route[d - 1][i] == 0:
                new_sc = max_sc[i] + scr
                if new_sc > max_sc[d - 1]:
                    max_sc[d - 1] = new_sc
                    route[d - 1] = copy.deepcopy(route[i])
                    route[d - 1][i] = 1
                    pos_n.append(d - 1)
                    flag = 1
else:
    print(-1)