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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def BellmanFord(g, s):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = set(V)

    dist = defaultdict(lambda: sys.maxsize)
    pred = defaultdict(lambda: -1)

    dist[s] = 0

    N = len(V)
    for i in range(N+1):
        for u in g:
            for v in g[u]:
                if dist[v] > dist[u] + g[u][v]:
                    if i == N:
                        return 'inf'
                    dist[v] = dist[u] + g[u][v]
                    pred[v] = u
    return dist


@mt
def slv(N, M, P, ABC):

    g =defaultdict(dict)
    for a, b, c in ABC:
        g[a][b] = -(c - P)

    def r(s):
        q = [s]
        done = set()
        done.add(s)
        while q:
            v = q.pop()
            for u in g[v]:
                done.add(u)
        return N in done, done

    _, r1 = r(1)
    for i in range(2, N):
        if i not in r1 and i in g:
            g.pop(i)

    d = set()
    for i in range(2, N):
        a, _ = r(i)
        if not a:
            d.add(i)
    
    for i in d:
        g.pop(i)
    for k, v in g.items():
        for i in d:
            if i in v:
                v.pop(i)
    d = BellmanFord(g, 1)
    if d == 'inf':
        return -1
    return max(0, -d[N])


def main():
    N, M, P = read_int_n()
    ABC = [read_int_n() for _ in range(M)]
    print(slv(N, M, P, ABC))

    # N = 100
    # M = 5000
    # P = random.randint(0, 10**5)
    # P= 0
    # ABC = [
    #     [random.randint(1, N), random.randint(1, N), random.randint(1, 10**5)] for _ in range(M)
    # ]
    # print(slv(N, M, P, ABC))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#http://wakabame.hatenablog.com/entry/2017/09/06/221400
def BellmanFord(edges,num_v,source):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(num_v)]
  dist[source-1]=0
  
  #辺の緩和
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        if i==num_v-1: return ['inf']
  
  return dist

n,m,p=map(int,input().split())
g=[]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
g.append([n,n+1,0])
ans=BellmanFord(g,n+1,1)[-1]
if ans=='inf':
  print(-1)
else:
  print(max(ans,0))

Submission status: Wrong Answer

Solution code:
from heapq import heappop, heappush
N, M, P = map(int, input().split())
V = {i : [] for i in range(1, N+1)}
for _ in range(M):
    a, b, c = map(int, input().split())
    V[a].append((b, c-P))
INF = 10 ** 9
# dijkstra
vstd = {i : False for i in range(1, N+1)}
mscr = {i : 0 for i in range(1, N+1)}  # max score
pq = []
heappush(pq, 1)
while pq:
    u = heappop(pq)
    vstd[u] = True
    for vc in V[u]:
        v, c = vc
        if vstd[v]:
            if mscr[u] + c > mscr[v]:
                mscr[v]  = INF
            continue
        if mscr[u] + c > mscr[v]:
            mscr[v] = mscr[u] + c
            heappush(pq, v)


print(max(0, mscr[N]) if mscr[N] < INF else -1)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


from heapq import heappush, heappop


def dijkstra(graph: list, start, INF=float('inf')) -> list:
    n = len(graph)
    dist = [INF] * n
    visited = [False] * n

    dist[start] = 0
    que = [(0, start)]

    while que:
        cost, cur = heappop(que)

        if visited[cur]:
            continue

        visited[cur] = True

        for nextnode, edgecost in graph[cur]:
            nextcost = cost + edgecost
            if nextcost < dist[nextnode]:
                dist[nextnode] = nextcost
                heappush(que, (nextcost, nextnode))

    return dist

n, m, p = li()

# グラフを作る
graph = [[] for _ in range(n)]
for _ in range(m):
    ai, bi, ci = li()
    ai -= 1
    bi -= 1
    graph[ai].append((bi, ci - p))

# 1から到達可能な点のみ抽出
reach = dijkstra(graph, 0)
print(reach)

reachable = set()
for i in range(n):
    if reach[i] != float('inf'):
        reachable.add(i)

INF = float('inf')
dist = [[-INF]*n for _ in range(2*n+1)]
dist[0][0] = 0
for i in range(2*n):
    for j in range(n):
        if not j in reachable:
            continue

        dist[i+1][j] = dist[i][j]

    for j in range(n):
        if not j in reachable:
            continue
        for (k, cost) in graph[j]:
            if not k in reachable:
                continue

            dist[i+1][k] = max(dist[i+1][k], dist[i][j] + cost)

if dist[2*n-1][-1] < dist[2*n][-1]:
    print(-1)
else:
    print(max(0, dist[n-1][-1]))

Submission status: Wrong Answer

Solution code:
INF = 10**10
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update > 1:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

Solution code:
#単一始点最短経路問題
#負の辺があっても動作する

#最短経路を求める
#計算量O(N * M)

INF = 10 ** 15
#入力
# N = int(input()) #頂点の数
# M = int(input()) #辺の数
N, M, P = map(int, input().split())

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


#メイン文
d = [0] * N #最短距離を記録しておくリスト
prev = [-1] * N
def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = 0
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != 0 and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                update = True
                prev[e[1]] = e[0]
        if not update: #更新が終わったとき
            return True
        if count == N: #永遠に更新が起きているとき
            tmp = d[N -1]
        if count == N + 2:
            if d[N - 1] == tmp:
                return True #N-1の値が更新されていないとき
            else:
                return False #N + 2回目でもN - 1の値が小さくなっている-->得点が無限に大きくなる

#呼び出しスタート地点を入れる
if not shortest_path(1):
    print (-1)
    print (d)
    exit()
# print (d)

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

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(200000)

from collections import deque

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

# print(edge)
visited = [0] * n
def dfs(v):
    for u in edge[v]:
        if visited[u] == 0:
            visited[u] = 1
            dfs(u)
visited[0] = 1
dfs(0)
# print(visited)
flag = [vi for vi in visited]

def dfs2(v):
    for u in edge[v]:
        if u == n - 1:
            visited2[u] = 1
            break
        if visited2[u] == 0:
            visited2[u] = 1
            dfs2(u)

for i in range(1, n):
    if flag[i] == 0:
        continue

    visited2 = [0] * n
    visited2[i] = 1
    dfs2(i)
    if visited2[n-1] == 0 and flag[i] == 1:
        flag[i] = 0

# print(flag)
target_v = set([i for i in range(n) if flag[i] == 1])
# print(target_v)

q = deque()
q.append((0, 0))
visited3 = [0] * n
visited3[0] = 1
ans = [0] * n
iter = 0
impossible = False
def dfs3(v, c):
    global impossible
    # print(v, c, visited3)
    for u in edge[v]:
        if u not in target_v:
            continue

        # print(u)
        if visited3[u] == 0:
            ans[u] = c + coin[v][u]
            visited3[u] = 1
            dfs3(u, c + coin[v][u])
            visited3[u] = 0
        else:
            # print(u, ans[u], c+coin[v][u])
            if ans[u] <= c + coin[v][u]:
                impossible = True
                break

dfs3(0, 0)

if impossible:
    print(-1)
else:
    print(max(0, ans[n-1]))

Submission status: Wrong Answer

Solution code:
n,m,r=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]

g=[[] for _ in [0]*n]
[g[a-1].append([b-1,c]) for a,b,c in abc]

dist=[-10**15 for _ in [0]*n]
dist[0]=0
a,b=-10**15,-10**15

for _ in range(n):
    for p in range(n):
        for i,j in g[p]:
            dist[i]=max(dist[i],dist[p]+j-r)
    a,b=b,dist[n-1]
if a==b:
    print(max(0,b))
else:
    print(-1)

Submission status: Wrong Answer

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

E = [[0, 0, 0] for n in range(M)]
for m in range(M):
    A, B, C = map(int, input().split())
    E[m][0] = A - 1
    E[m][1] = B - 1
    E[m][2] = P - C


def BellmanFord(edges, num_v, source, end):
    inf = 10 ** 8
    dist = [inf for i in range(num_v)]
    dist[source] = 0

    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]

    end1 = dist[end]
    for i in range(num_v):
        for edge in edges:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]] + edge[2]

    end2 = dist[end]

    return max(0, -end1) if end1 == end2 else -1


res = BellmanFord(E, N, 0, N - 1)
print(res)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    p = [[] for _ in range(N)]
    for i in range(M):
        p[A[i] - 1].append([B[i] - 1, C[i] - P, i])

    def detect(idx, cur, start, visited, cnt = 0):
        #print(idx, cur, start, visited)
        if cnt > 0 and idx == start:
            if cur > 0:
                return True
            else:
                return False
        for nex in p[idx]:
            if not visited[nex[0]]:
                visited[nex[0]] = True
                tmp = detect(nex[0], cur + nex[1], start, visited, cnt + 1)
                if tmp:
                    return True
                visited[nex[0]] = False
        return False

    def can(idx, target, visited):
        if idx == target:
            return True
        visited[idx] = True
        for nex in p[idx]:
            if not visited[nex[0]]:
                if can(nex[0], target, visited):
                    return True
        return False

    def dfs(idx, cur, dp, used):
        dp[idx] = max(dp[idx], cur)
        for nex in p[idx]:
            if not used[nex[2]]:
                used[nex[2]] = True
                dp = dfs(nex[0], cur + nex[1], dp, used)
        return dp

    for i in range(N):
        visited = [False] * N
        tmp = detect(i, 0, i, visited)
        if tmp:
            #print(i, visited)
            visited = [False] * N
            tmp1 = can(0, i, visited)
            visited = [False] * N
            tmp2 = can(i, N - 1, visited)
            if tmp1 and tmp2:
                #print(i, visited)
                print(-1)
                return
    used = [False] * M
    dp = [0] * N
    dp = dfs(0, 0, dp, used)
    #print(dp)
    ret = max(0, dp[N - 1])
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]" 
    B = [int()] * (M)  # type: "List[int]" 
    C = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys

inf = float('inf')

def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    dist = [inf] * N
    dist[0] = 0
    loop = [False] * N

    for count in range(N):
        for u, v, c in zip(A, B, C):
            if dist[u] + c < dist[v]:
                dist[v] = dist[u] + c
                if count >= v-1:
                    loop[v] = True
    
    if loop[N-1]:
        print(-1)
        return
    print(max(-dist[N-1], 0))
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]" 
    B = [int()] * (M)  # type: "List[int]" 
    C = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        A[i] = int(next(tokens))-1
        B[i] = int(next(tokens))-1
        C[i] = -(int(next(tokens))-P)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
INF = 10**10
n, m, p = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
for i in range(m):
    a, b, c = [int(item) for item in input().split()]
    a -= 1; b -= 1; c -= p
    c *= -1
    edge[a].append((b, c))
print(edge)

dist = [INF] * n
dist[0] = 0
update = 1
terminal_update = 0
for _ in range(n):
    update = 0
    for v, e in enumerate(edge):
        for t, cost in e:
            if dist[v] != INF and dist[v] + cost < dist[t]:
                dist[t] = dist[v] + cost
                update = 1
                if t == n-1:
                    terminal_update += 1
    if not update:
        print(max(0, -dist[n-1]))
        break
else:
    if terminal_update > 1:
        print(-1)
    else:
        print(max(0, -dist[n-1]))

Submission status: Wrong Answer

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

v_list = [[] for _ in range(N)]
r_list = [[] for _ in range(N)]
for _ in range(M):
	a, b, c = map(int, input().split())
	a -= 1
	b -= 1
	v_list[a].append((b, c))
	r_list[b].append((a, c))


queue = [N - 1]
coins = [None] * N
coins[N - 1] = 0
while queue:
	cur = queue.pop()
	coin = coins[cur]
	for n, c in r_list[cur]:
		x = coins[n]
		y = coin + c - P
		if x == None:
			coins[n] = y
		elif x < y:
			print("-1")
			exit(0)

max_value = 0
for i in range(N):
	coin = coins[i]
	if coin != None and coin > max_value:
		max_value = coin
print(max_value)

Submission status: Wrong Answer

Solution code:
from collections import deque


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

graph = [[] for i in range(n)]
for i in range(m):
    graph[info[i][0] - 1].append((info[i][1] - 1, info[i][2]))


# スタート地点からゴールにたどり着ける頂点を探す
def bfs1(start):
    q = deque([start])
    visited = [False] * n
    visited[start] = True
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            else:
                visited[i] = True
                q.append(i)
    return visited

visited_from_start = bfs1(0)
can_goal = [False] * n
can_goal[n-1] = True


# ある地点からゴールに着ける頂点を探す
def bfs2(start):
    if can_goal[start]:
        return
    q = deque([start])
    visited = [False] * n
    visited[start] = True
    while q:
        pos = q.popleft()
        for i, _ in graph[pos]:
            if visited[i]:
                continue
            if i == n-1:
                can_goal[start] = True
                break
            else:
                visited[i] = True
                q.append(i)

for i in range(n)[::-1]:
    if visited_from_start[i]:
        bfs2(i)
# print(can_goal)


def bfs3(start):
    q = deque([(start, -1, 0, 0)])
    prev_pos_money = {}
    prev_pos_memo = {}
    while q:
        pos, prev_pos, t, mon = q.popleft()
        for next_pos, next_mon in graph[pos]:
            if not can_goal[next_pos]:
                continue
            if next_pos in prev_pos_memo:
                if pos in prev_pos_memo[next_pos]:
                    if (mon + next_mon) - (t+1)*p > prev_pos_money[next_pos][pos] - prev_pos_memo[next_pos][pos]*p:
                        return -1
                        exit()
                    else:
                        continue
                else:
                    prev_pos_memo[next_pos][pos] = -1
                    prev_pos_money[next_pos][pos] = 0
            else:
                prev_pos_memo[next_pos] = {}
                prev_pos_memo[next_pos][pos] = -1
                prev_pos_money[next_pos] = {}
                prev_pos_money[next_pos][pos] = 0
            if prev_pos_memo[next_pos][pos] == -1 or (mon + next_mon) - (t+1)*p > prev_pos_money[next_pos][pos] - prev_pos_memo[next_pos][pos]*p:
                prev_pos_memo[next_pos][pos] = t + 1
                prev_pos_money[next_pos][pos]= mon + next_mon
                q.append((next_pos, pos, t+1, mon + next_mon))
    ans = 0
    for i in prev_pos_memo[n-1]:
        ans = max(ans, prev_pos_money[n-1][i] - prev_pos_memo[n-1][i]*p)
    return ans

print(bfs3(0))

Submission status: Wrong Answer

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

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

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

data, row_ind, col_ind = [], [], []
for a, b, c in abc:
    data.append(1)
    row_ind.append(a - 1)
    col_ind.append(b - 1)

g = csr_matrix((data, (row_ind, col_ind)), shape=(n, n))

dist_matrix = bellman_ford(g)

ignores = []
for i in range(n):
    if (dist_matrix[0, i] == float("inf")) | (dist_matrix[i, n - 1] == float("inf")):
        ignores.append(i)
ignores = set(ignores)

data, row_ind, col_ind = [], [], []
for a, b, c in abc:
    if (a - 1 not in ignores) | (b - 1 not in ignores):
        data.append(p - c)
        row_ind.append(a - 1)
        col_ind.append(b - 1)

g = csr_matrix((data, (row_ind, col_ind)), shape=(n, n))

try:
    dist_matrix = bellman_ford(g, indices=[0])
    ans = max(0, -int(dist_matrix[0][-1]))
except NegativeCycleError:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 0))
G_rev = defaultdict(lambda: defaultdict(lambda: 0))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = C
    G_rev[B][A] = 1

reachable = [0] * (N + 1)
reachable[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable[q] == 0:
            reachable[q] = 1
            queue.append(q)

# print(reachable)
assert reachable[1] == 1

max_score = [-10000000000] * (N + 1)
res = 0
max_score[1] = 0
queue = deque([1])
cnt = 0
while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if reachable[q] == 0:
            pass
        elif max_score[p] + G[p][q] - P > max_score[q]:
            max_score[q] = max_score[p] + G[p][q] - P
            queue.append(q)
            cnt += 1
    if cnt > 1000000:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, max_score[N]))

Submission status: Wrong Answer

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


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

    INF = 10**14*2
    V = [INF]*N
    V[0] = 0
    for _ in range(N-1):
        for e in d:
            s, t = e
            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 __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque

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

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

    res = [0, 0] + [float("-inf")] * (n - 1)

    q = deque()
    q.append((1, {1}, [0, 0] + [float("-inf")] * (n - 1)))

    while q:
        curr, visited, score = q.pop()
        for b, c in edge[curr]:
            if b in visited:
                if score[curr] + c > score[b]:
                    score[curr] = float("inf")
                    res[curr] = float("inf")
                    if score[b] != float("inf"):
                        score[b] = float("inf")
                        res[b] = float("inf")
                        q.append((b, visited, score))
            else:
                score[b] = score[curr] + c
                if score[b] > res[b]:
                    res[b] = score[b]
                    q.append((b, visited | {b}, score))


    print(max(0, res[n]) if res[n] != float("inf") else -1)


main()

Submission status: Wrong Answer

Solution code:
n,m,r=map(int,input().split())
abc=[list(map(int,input().split())) for _ in [0]*m]

g=[[] for _ in [0]*n]
[g[a-1].append([b-1,c]) for a,b,c in abc]

dist=[-10**15 for _ in [0]*n]
dist[0]=0
a,b=-10**15,-10**15

for _ in range(n):
    for p in range(n):
        for i,j in g[p]:
            dist[i]=max(dist[i],dist[p]+j-r)
    a,b=b,dist[n-1]

if a==b:
    ans=0
    d=[-10**15 for _ in [0]*n]
    d[0]=0
    q=[[0,1]]
    s=set()
    l=[]
    cnt=0
    while q:
        cnt+=1
        qq=[]
        for q_item in q:
            item,depth=q_item
            if depth<=len(s):
                for _ in range(len(s)-depth+1):
                    rmv=l.pop()
                    s.remove(rmv)
            l.append(item)
            s.add(item)
            for i,dist in g[item]:
                if d[i]<d[item]+dist:
                    if i in s:
                        continue
                    d[i]=d[item]+dist
                    qq.append([i,depth+1])
        ans=max(ans,d[n-1]-cnt*r)
        q=qq
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def BellmanFord(edges,num_v,start):
    inf=float('inf')
    dist=[inf for _ in range(num_v)] #グラフの初期化
    dist[start]=0
    #辺の和
    for i in range(num_v):
        for edge in edges: #edge: (始点,終点,コスト)
            if dist[edge[0]]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                dist[edge[1]]=dist[edge[0]]+edge[2]
                #負閉経路かつそれがゴールを通るものがある
                #i==num_v-1だけだと、負閉経路の検出だけになる
                if i==num_v-1 and edge[1]==num_v-1:
                    return -1
    return dist

n,m,p=map(int,input().split())
Edges=[]
for _ in range(m):
    a,b,c=map(int,input().split())
    a-=1; b-=1
    c-=p
    Edges.append((a,b,-c))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
edges = []
for i in range(M):
    A, B, C = map(int, input().split())
    edges.append([A, B, P - C])


def BellmanFord(edges, num_v, source):
    minus_flag = 0
    inf_flag = 0
    # グラフの初期化
    inf = float("inf")
    dist = [inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    for i in range(num_v):
        for edge in edges:
            if edge[0] != inf and dist[edge[1] - 1] > dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i == num_v - 1:
                    minus_flag = 1
                if minus_flag == 1:
                    if edge[1] == N:
                        inf_flag = 1

    if inf_flag == 0:
        return dist
    else:
        dist.append(-1)
        return dist


ans = BellmanFord(edges, N, 1)
if len(ans) != N:
    print(-1)
else:
    print(max(0, ans[-1] * -1))

Submission status: Wrong Answer

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

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

INF = 10 ** 18
dist = [INF] * (N+1)
dist[1] = 0

loop = False
for i in range(N+100):
    for a,b,c in ABC:
        x = dist[a] + P - c
        if dist[b] > x:
            dist[b] = x
            if b == N and i > N:
                loop = True

if loop:
    answer = -1
else:
    answer = -dist[N]
    if answer < 0:
        answer = 0

print(answer)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
G = defaultdict(lambda: defaultdict(lambda: 0))
G_rev = defaultdict(lambda: defaultdict(lambda: 0))

for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = C
    G_rev[B][A] = 1

reachable = [0] * (N + 1)
reachable[N] = 1
queue = deque([N])

while len(queue) > 0:
    p = queue.popleft()
    for q in G_rev[p].keys():
        if reachable[q] == 0:
            reachable[q] = 1
            queue.append(q)

# print(reachable)
assert reachable[1] == 1

max_score = [-10000000000] * (N + 1)
res = 0
max_score[1] = 0
queue = deque([1])
cnt = 0
while len(queue) > 0:
    p = queue.popleft()
    for q in G[p].keys():
        if not reachable[q]:
            continue
        if max_score[p] + G[p][q] - P > max_score[q]:
            max_score[q] = max_score[p] + G[p][q] - P
            queue.append(q)
            cnt += 1
    if cnt > 1000000:
        res = -1
        break

if res == -1:
    print(res)
else:
    print(max(0, max_score[N]))