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 heapq


class Dijkstra:

    def __init__(self, rote_map, start_point, goal_point=None):
        self.rote_map = rote_map
        self.start_point = start_point
        self.goal_point = goal_point

    def execute(self):
        num_of_city = len(self.rote_map) + 10000
        dist = [float("inf") for _ in range(num_of_city)]
        prev = [float("inf") for _ in range(num_of_city)]

        dist[self.start_point] = 0
        heap_q = []
        heapq.heappush(heap_q, (0, self.start_point))
        route_count = [0 for _ in range(num_of_city)]
        route_count[self.start_point] = 1
        while len(heap_q) != 0:
            prev_cost, src = heapq.heappop(heap_q)

            if dist[src] < prev_cost:
                continue

            for dest, cost in self.rote_map[src].items():
                if cost != float("inf") and dist[dest] > dist[src] + cost:
                    dist[dest] = dist[src] + cost
                    heapq.heappush(heap_q, (dist[dest], dest))
                    prev[dest] = src
                if dist[dest] == dist[src] + cost:
                    route_count[dest] += route_count[src]

        if self.goal_point is not None:
            return self._get_path(self.goal_point, prev)
        else:
            return dist, route_count

    def _get_path(self, goal, prev):
        path = [goal]
        dest = goal

        while prev[dest] != float("inf"):
            path.append(prev[dest])
            dest = prev[dest]

        return list(reversed(path))


N, M, P = map(int, input().split())
items = []
from collections import defaultdict

graph = defaultdict(dict)
graph2 = defaultdict(dict)
for i in range(M):
    a, b, c = map(int, input().split())
    graph[a][b] = c
    if a != b:
        graph2[a-1][b-1] = 1

if M in graph[M] and graph[M][M] - P > 0:
    print(-1)
    exit()
res = Dijkstra(graph2, 0, N-1).execute()

if len(res) == 1:
    print(-1)
    exit()
print(0)

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] = INF
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                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
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+10):
    for a,b,c in ABC:
        x = dist[a] + P - c
        if dist[b] > x:
            dist[b] = x
            if b == N and i == N+9:
                loop = True

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

print(answer)

Submission status: Wrong Answer

Solution code:
#https://qiita.com/chun1182/items/ddf2b6cba932b2bb0d4e
def BF(p,n,s):
    inf=float("inf")
    d=[inf for i in range(n)]
    d[s-1]=0
    for i in range(n+1):
        for e in p:
            if e[0]!=inf and d[e[1]-1]>d[e[0]-1]+e[2]:
                d[e[1]-1] = d[e[0]-1] + e[2]
        if i==n-1:t=d[-1]
        if i==n and t!=d[-1]:
            return [0,'inf']
    return list(map(lambda x:-x, d))

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=BF(g,n+1,1)[-1]
if ans=='inf':
  print(-1)
else:
  print(max(ans,0))

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
#sys.setrecursionlimit(10 ** 9)
import math
import heapq

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

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["second"] = -1
	tree[i]["score"] = 0
	tree[i]["reach"] = -1
	tree[i]["eda"] = []
	tree[i]["eda2"] = []
for i in range(M):
	A, B, C = list(map(int, input().split()))
	A -= 1
	B -= 1
	tree[A]["eda"].append([A,B,C])
	tree[B]["eda2"].append([B,A])

tree[N - 1]["reach"] = 1
stack = [N - 1]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda2"]:
		if tree[edge[1]]["reach"] == -1:
			stack.append(edge[1])
			tree[edge[1]]["reach"] = 1

tree[0]["second"] = 1
stack = [0]
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda"]:
		if tree[edge[1]]["reach"] == 1:
			if tree[edge[1]]["second"] == 1:
				if tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					print(-1)
					exit()
			else:
				tree[edge[1]]["score"] = tree[edge[0]]["score"] + edge[2] - P
				stack.append(edge[1])
				tree[edge[1]]["second"] = 1
print(max(tree[N - 1]["score"],0))

Submission status: Wrong Answer

Solution code:
INF = 10**12
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:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    graph = defaultdict(list)
    coins = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a-1].append(b-1)
        coins[(a-1,b-1)] = c

    scores = [0] * n
    que = deque()
    que.append((0, 0))
    for i in range(n * 3):
        next_que = deque()
        while que:
            node, move = que.popleft()
            next_move = move + 1
            for next_node in graph[node]:
                score = scores[node] + coins[(node, next_node)] - next_move * p
                if score > scores[next_node]:  # そのさきもやる価値あり
                    scores[next_node] = score
                    next_que.append((next_node, next_move))

        que = next_que

        if i == n-1:
            ans = scores[n-1]

    print(-1 if ans != scores[n-1] else ans)


if __name__ == '__main__':
    main()

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())


n, m, p = li()

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

# ベルマンフォード
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 dist[i][j] != -INF:
            dist[i+1][j] = dist[i][j]
        for (k, cost) in graph[j]:
            dist[i+1][j] = max(dist[i+1][j],  dist[i][k] + cost)


# n回目の遷移とn+1回目の遷移で差があるとNG
if dist[2*n-1][n-1] < dist[2*n][n-1]:
    print(-1)
else:
    print(max(0, dist[2*n-1][n-1]))

Submission status: Wrong Answer

Solution code:

import sys

sys.setrecursionlimit(10000)

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

for i in range(m):
    abc[i][0] -= 1
    abc[i][1] -= 1
    abc[i][2] = -(abc[i][2] - p)

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

d = [1e9] * n
d[0] = 0
reachable = [False] * n
reachable[0] = True
reachable[n - 1] = True


def dfs(i, a):
    for v in al[i]:
        if v == n - 1:
            for x in a:
                reachable[x] = True
        elif v not in a:
            dfs(v, a + [v])


dfs(0, [])

for _ in range(n - 1):
    for u, v, c in abc:
        if not reachable[v]:
            continue
        if d[v] > d[u] + c:
            d[v] = d[u] + c
            # pre[v] = u

flag = False
for u, v, c in abc:
    if d[u] + c < d[v] and reachable[v]:
        flag = True
        break

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]

def sp(s,n,w,es):
  d=[float("inf")]*n
  d[s]=0
  count=0
  while count<n:
    update=False
    for i in range(w):
      e=es[i]
      if d[e[0]]!=float("inf") and d[e[1]]>d[e[0]]+e[2]:
        d[e[1]]=d[e[0]]+e[2]
        update=True
    if not update:
      break
    count+=1
  return d



print(max(0,-sp(0,n,m,edge)[n-1]))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(M)]

INF = float('inf')
d = [INF] * N
d[0] = 0
for i in range(N):
    for fr,to,c in ABC:
        fr,to = fr-1,to-1
        cost = -(c-P)
        if d[fr] != INF and d[to] > d[fr]+cost:
            d[to] = d[fr] + cost
            if i == N-1 and to == N-1:
                print(-1)
                exit()
print(max(0,-d[-1]))

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())
    E = [[] for _ in range(N)]
    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
        E[a].append(b)

    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-1):
        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:

#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n, m, p = map(int, input().split())
    graph = defaultdict(list)
    coins = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        graph[a-1].append(b-1)
        coins[(a-1,b-1)] = c

    scores = [0] * n
    que = deque()
    que.append((0, 0))
    for i in range(n * 2):
        next_que = deque()
        while que:
            node, move = que.popleft()
            next_move = move + 1
            for next_node in graph[node]:
                score = scores[node] + coins[(node, next_node)] - next_move * p
                if score > scores[next_node]:  # そのさきもやる価値あり
                    scores[next_node] = score
                    next_que.append((next_node, next_move))

        que = next_que

        if i == n-1:
            ans = scores[n-1]

    print(-1 if ans != scores[n-1] else ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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:
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)])
    money = [0] * n
    time = [-1] * n
    time[0] = 0
    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 > money[next_pos] - time[next_pos]*p:
                        return -1
                        exit()
                    else:
                        continue
                else:
                    prev_pos_memo[next_pos][pos] = 1
            else:
                prev_pos_memo[pos] = {}
                prev_pos_memo[pos][prev_pos] = 1
            if time[next_pos] == -1 or (mon + next_mon) - (t+1)*p > money[next_pos] - time[next_pos]*p:
                time[next_pos] = t + 1
                money[next_pos] = mon + next_mon
                q.append((next_pos, pos, t+1, mon + next_mon))
    return max(0, money[n-1] - time[n-1]*p)

print(bfs3(0))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
INF = float("inf")


class MaxHeap(object):
    def __init__(self, x):
        self.heap = [-e for e in x]
        heapq.heapify(self.heap)

    def push(self, value):
        a, b = value
        heapq.heappush(self.heap, (-a, b))

    def pop(self):
        a, b = heapq.heappop(self.heap)
        return -a, b

    def __len__(self):
        return len(self.heap)


# 有効グラフを仮定する。
class Graph(object):
    def __init__(self, N):
        self.N = N
        self.V = list(range(N))
        self.E = [[] for _ in range(N)]

    def add_edge(self, edge):
        """辺を加える。edgeは(始点, 終点、重み)からなるリスト
        重みがなければ、重み1とする。
        """
        if len(edge) == 2:
            edge.append(1)
        elif len(edge) != 3:
            print("error in add_edge")
            pass

        s, t, w = edge
        self.E[s].append([t, w])

        pass


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

    g = Graph(N)
    for a, b, c in zip(A, B, C):
        g.add_edge([a-1, b-1, c])

    longest = [0]*N
    visited = [False]*N
    q = MaxHeap([])
    q.push([0, 0])
    while len(q) > 0:
        node, dist = q.pop()
        visited[node] = True
        for to_, coin in g.E[node]:
            if longest[node] == INF and longest[to_] != INF:
                visited[to_] = False
            if visited[to_] is False:
                longest[to_] = dist+coin
                q.push([to_, dist+coin])
            else:
                if longest[to_] < dist+coin:
                    longest[to_] = INF
                    q.push([to_, INF])

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

    # print(longest)
    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:
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


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):
    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
while q:
    v, c = q.popleft()
    for u in edge[v]:
        if u not in target_v:
            continue
        if visited3[u] == 0:
            ans[u] = c + coin[v][u]
            visited3[u] = 1
            q.append((u, c + coin[v][u]))
        else:
            if ans[u] <= c + coin[v][u]:
                impossible = True
                break

    if impossible:
        break

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

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)])
    money = [0] * n
    time = [0] * n
    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 > money[next_pos] - time[next_pos]*p:
                        return -1
                        exit()
                    else:
                        continue
                else:
                    prev_pos_memo[next_pos][pos] = 1
            else:
                prev_pos_memo[pos] = {}
                prev_pos_memo[pos][prev_pos] = 1
            if (mon + next_mon) - (t+1)*p > money[next_pos] - time[next_pos]*p:
                time[next_pos] = t + 1
                money[next_pos] = mon + next_mon
                q.append((next_pos, pos, t+1, mon + next_mon))
    return money[n-1] - time[n-1]*p

print(bfs3(0))

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)
    a,b=b,dist[n-1]

if a-p<=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:
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)

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

INF = float('inf')
dist = [[0]*n for _ in range(n+1)]
dist[0][0] = 0
for i in range(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[n-1][-1] < dist[n][-1]:
    print(-1)
else:
    print(max(0, dist[n-1][-1]))

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))

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

    q = deque()
    q.append((1, {1}))

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

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


main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2000000)

N,M,P = map(int,input().split())
side = [[]for i in range(N)]
for i in range(M):
    a,b,c = map(int,input().split())
    side[a-1].append([b-1,c-P])
node = [-float('inf')]*N
node[0] = 0

def DFS(p,l):
    if node[p] == float('inf'):
        return
    elif p in l:
        node[p] = float('inf')
        for i,v in side[p]:
            DFS(i,l+[p])
    else:
        for i,v in side[p]:
            if node[i] < node[p]+v:
                node[i] = node[p]+v
                DFS(i,l+[p])
    return

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

Submission status: Wrong Answer

Solution code:
#https://qiita.com/chun1182/items/ddf2b6cba932b2bb0d4e
def BF(p,n,s):
    inf=float("inf")
    d=[inf for i in range(n)]
    d[s-1]=0
    for i in range(n+1):
        for e in p:
            if e[0]!=inf and d[e[1]-1]>d[e[0]-1]+e[2]:
                d[e[1]-1] = d[e[0]-1] + e[2]
        if i==n-1:t=d[-1]
        if i==n and t!=d[-1]:
            return [0,'inf']
    return list(map(lambda x:-x, d))

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)])
ans=BF(g,n,1)[-1]
if ans=='inf':
  print(-1)
else:
  print(max(ans,0))

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 = float("inf")
    dist = [inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    for i in range(num_v * 2):
        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 == 0:
        return dist
    else:
        dist.append(-1)
        return dist


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