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())
    g = [[] for _ in range(N+1)]
    g2 = [[] for _ in range(N+1)]
    data0 = [None] * (M+1)
    data1 = [None] * (M+1)
    data2 = [None] * (M+1)
    for i in range(M):
        a, b, c = map(int, input().split())
        data0[i] = a
        data1[i] = b
        data2[i] = c


    for i in range(M):
        g[data1[i]].append(data0[i])
        g2[data0[i]].append(data1[i])

    visit = [False]*(N+1)
    visit2 = [False]*(N+1)

    queue = [N]
    while len(queue) > 0:
        nextqueue = []
        for now in queue:
            visit[now] = True
            for next in g[now]:
                if not visit[next]:
                    nextqueue.append(next)
        queue = nextqueue[:]

    queue = [1]
    while len(queue) > 0:
        nextqueue = []
        for now in queue:
            visit2[now] = True
            for next in g2[now]:
                if not visit2[next]:
                    nextqueue.append(next)
        queue = nextqueue[:]




    for i in range(1, N+1):
        visit[i] = visit[i] and visit2[i]



if __name__ == "__main__":
    main()

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
  ret=[]
  while count<n+1:
    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:
      ret.append(d[-1])
      ret.append(d[-1])
      break
    count+=1
    if count>=n:
      ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Wrong Answer

Solution code:

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

    INF = 10**15
    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:
import sys
input = sys.stdin.readline

def main():
    N, M, P = map(int, input().split())
    g = [[] for _ in range(N+1)]
    g2 = [[] for _ in range(N+1)]
    data0 = [None] * (M+1)
    data1 = [None] * (M+1)
    data2 = [None] * (M+1)
    for i in range(M):
        a, b, c = map(int, input().split())
        data0[i] = a
        data1[i] = b
        data2[i] = c


    for i in range(M):
        g[data1[i]].append(data0[i])
        g2[data0[i]].append(data1[i])




    INF = -100000001
    d = [INF] * (N+1)
    d[1] = 0

    for i in range(N):
        d_N = 0
        for j in range(M):
            d[data1[j]] = max(d[data1[j]], d[data0[j]]+data2[j]-P)
        if i == N-1:
                ans = -1

        else:
                ans = d[N]

    if ans == -1:
        print(-1)
    else:
        print(max(0, ans))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque

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, [0, 0] + [float("-inf")] * (n - 1)))

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


print(max(0, res[n]) if res[n] != float("inf") else -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())
    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**15
    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:

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:
import os
import sys
from collections import deque

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


class Dinic:
    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int)) graph: (to, cap) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap in graph[v]:
                rev = [v, 0]
                edge = [u, cap, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def _dist(self, s):
        """
        :param int s:
        :rtype: list of int
        :return: s からの距離。残余グラフ上で到達できない場合は -1
        """
        ret = [-1] * len(self.graph)
        ret[s] = 0
        que = deque([(s, 0)])
        while que:
            v, d = que.popleft()
            for u, cap, _ in self.graph[v]:
                if ret[u] < 0 < cap:
                    ret[u] = d + 1
                    que.append((u, d + 1))
        return ret

    def _dfs(self, s, t, dist, iter, flow=float('inf')):
        """
        :param int s:
        :param int t:
        :param list of int dist:
        :param list of int iter:
        :param int flow:
        """
        if s == t:
            return flow
        while iter[s] < len(self.graph[s]):
            edge = self.graph[s][iter[s]]
            to, cap, rev = edge
            if dist[s] < dist[to] and cap > 0:
                f = self._dfs(to, t, dist, iter, min(flow, cap))
                if f > 0:
                    edge[1] -= f
                    rev[1] += f
                    return f
            iter[s] += 1
        return 0

    def maximum_flow(self, from_v, to_v):
        """
        :param int from_v:
        :param int to_v:
        :return: from_v から to_v への最大流
        """
        ret = 0
        while True:
            dist = self._dist(from_v)
            if dist[to_v] < 0:
                break
            iter = [0] * len(self.graph)
            while True:
                flow = self._dfs(from_v, to_v, dist, iter)
                if flow == 0:
                    break
                ret += flow
        return ret


class MinCostFlow:
    """
    最小費用流 ベルマンフォード版
    """

    def __init__(self, graph=None, residual=None):
        """
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :param list of (list of (list of (int|list))) residual: (to, cap, cost, rev) の残余グラフ
        """
        assert (graph and not residual) or (not graph and residual)
        if graph:
            self.graph = self.residual_graph(graph)
        else:
            self.graph = residual

    @staticmethod
    def residual_graph(graph):
        """
        残余グラフ構築
        :param list of (list of (int, int, int)) graph: (to, cap, cost) の隣接リスト
        :rtype: list of (list of (list of (int|list)))
        :return: (to, cap, cost, rev) の残余グラフ
        """
        ret = [[] for _ in range(len(graph))]
        for v in range(len(graph)):
            for u, cap, cost in graph[v]:
                rev = [v, 0, -cost]
                edge = [u, cap, cost, rev]
                rev.append(edge)
                ret[v].append(edge)
                ret[u].append(rev)
        return ret

    def solve(self, from_v, to_v, flow):
        """
        :param int from_v:
        :param int to_v:
        :param int flow:
        :rtype: int
        """
        remains = flow
        total_cost = 0

        while remains > 0:
            # 最短路
            dist = [float('inf')] * len(self.graph)
            preve = [None] * len(self.graph)
            prevv = [None] * len(self.graph)
            dist[from_v] = 0
            stop = False
            cnt = 0
            while not stop:
                stop = True
                for v, edges in enumerate(self.graph):
                    for edge in edges:
                        u, cap, cost, rev = edge
                        if cap > 0 and dist[v] + cost < dist[u]:
                            dist[u] = dist[v] + cost
                            prevv[u] = v
                            preve[u] = edge
                            stop = False
                cnt += 1
                if cnt > len(self.graph) + 100:
                    if prevdist != dist[to_v]:
                        return IINF
                    else:
                        return 0
                prevdist = dist[to_v]
            flow = remains
            if dist[to_v] == float('inf'):
                total_cost = -1
                break

            v = to_v
            while v != from_v:
                cap = preve[v][1]
                v = prevv[v]
                flow = min(cap, flow)

            # path に沿って flow 流す
            cost = 0
            v = to_v
            while v != from_v:
                cost += preve[v][2] * flow
                preve[v][1] -= flow
                preve[v][3][1] += flow
                v = prevv[v]

            remains -= flow
            total_cost += cost
        return total_cost


N, M, P = list(map(int, sys.stdin.readline().split()))
ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

S = 0
T = N + 1
graph = [[] for _ in range(N + 2)]
graph[S].append((1, 1, 0))
graph[N].append((T, 1, 0))
for a, b, c in ABC:
    graph[a].append((b, IINF, -c + P))

ans = MinCostFlow(graph).solve(S, T, 1)
if ans == IINF:
    print(-1)
else:
    print(-ans)

Submission status: Wrong Answer

Solution code:
INF = 10**18
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 + 10):
    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:
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect


def main():
    node_num, edge_num, p = map(int, input().split())
    data = [list(map(int, input().split())) for i in range(edge_num)]
    graph_data = defaultdict(set)
    weight_graph = defaultdict(int)

    for i in range(edge_num):
        a, b, c = data[i]
        graph_data[a].add(b)
        weight_graph[(a, b)] = c

    visit_weight = [0 for i in range(node_num + 1)]
    now_set = set()
    next_set = set()
    now_set.add(1)

    ind = 0
    while len(now_set) > 0:
        # ind += 1
        for now_ele in now_set:
            for next_ele in graph_data[now_ele]:
                next_value = visit_weight[now_ele] + weight_graph[(now_ele, next_ele)] - p
                if visit_weight[next_ele] > next_value:
                    continue
                if visit_weight[next_ele] > 0:
                    print(-1)
                    sys.exit()
                visit_weight[next_ele] = next_value
                next_set.add(next_ele)
                # print(visit_weight, next_value)
        now_set = next_set
        next_set = set()

    # print(visit_weight)
    print(visit_weight[node_num])







if __name__ == '__main__':
    main()

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]:
                q.append(u)
                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:
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 + 10):
    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 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):
    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
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:
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[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

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[u]):
            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[u]:
        flag = True
        break

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

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[u] and 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[u] and reachable[v]:
        flag = True
        break

if flag:
    print(-1)
else:
    print(max(-d[-1], 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] = P
    d[s] = 0
    count = 0
    while True:
        count += 1
        update = False
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != P 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 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()

ans = 0

s = res[0]
for r in res[1:]:
    ans += graph[s+1][r+1]
    s = r
print(max(0, ans - P * len(res[1::])))