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:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    # FORWARD = defaultdict(lambda: [])
    # BACK = defaultdict(lambda: [])
    # for a, b, c in ABC:
    #     t = FORWARD[a]
    #     t.append((b, c))
    #     FORWARD[a] = t
    #
    #     t = BACK[b]
    #     t.append((a, c))
    #     BACK[b] = t

    # mem = {N}
    # q = [N]
    # while len(q) != 0:
    #     t = q.pop()
    #     for t2, _ in BACK[t]:
    #         if t2 in mem:
    #             continue
    #         q.append(t2)
    #         mem.add(t2)
    #
    # ABC = [(a, b, P - c) for a, b, c in ABC if a in mem and b in mem]

    ABC = [(a, b, P - c) for a, b, c in ABC]

    table = [MAX] * (N + 1)
    # history_table = [set() for _ in range(N + 1)]
    table[1] = 0
    # history_table[1] = {1}
    # table2 = [-1] * N
    for _ in range(N):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                # if b in history_table[a]:
                #     print(-1)
                #     return
                table[b] = table[a] + c
                # h2 = set(history_table[a])
                # h2.add(b)
                # history_table[b] = h2
    if -table[N] < 0:
        print(0)
        return
    score = -table[N]
    for _ in range(N):
        for a, b, c in ABC:
            if table[a] == MAX:
                continue
            if table[a] + c < table[b]:
                table[b] = table[a] + c
    # for a, b, c in ABC:
    #     if table[a] == MAX:
    #         continue
    #     if table[a] + c < table[b]:
    #         print(-1)
    #         return
    if -table[N] != score:
        print(-1)
        return
    print(-table[N])


if __name__ == '__main__':
    main()

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))
G = dict()
G_rev = dict()

for i in range(1, N + 1):
    G[i] = dict()
    G_rev[i] = dict()

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

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000 for i in range(N + 1)]
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > N:
        res = -1
        break

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

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

    inf = 10**10
    scores = [inf] * n
    scores[0] = 0
    # bellman-ford
    for loop in range(2):
        for i in range(n):
            for next_node in graph[i]:
                scores[next_node] = min(scores[next_node], scores[i] + coins[(i, next_node)])

        if loop == 0:
            ans = scores[n-1]

    print(-1 if ans != scores[n-1] else -ans)  # n 回移動した時点よりスコアが良くなってたら無限に上げられる


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from pprint import pprint

def solve(n, m, p, e):
  for i in range(m):
    e[i] = (e[i][0], e[i][1], -1 * e[i][2] + p)

  dist = BellmanFord(e, n, 1)
  # pprint(dist)
  if dist == -1:
    print -1
  else:
    print max(0, -1 * dist[n-1])


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 -1
        if i==num_v-1 and edge[1] == n: return -1

  return dist


if __name__ == '__main__':

    n, m, p = map(int, sys.stdin.readline().strip().split(" "))
    e = []
    for _ in range(m):
        e.append(map(int, sys.stdin.readline().strip().split(" ")))
    solve(n, m, p, e)

Submission status: Wrong Answer

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

import numpy as np
from scipy.sparse.csgraph import bellman_ford, csgraph_from_dense, connected_components

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

mat = np.full((N+1,N+1), np.inf)
for a,b,c in ABC:
    mat[a][b] = P - c

x = mat[N][1]
mat[N][1] = 1
_,comp = connected_components(mat != np.inf, connection='strong')
mat[N][1] = x
select = (comp == comp[1])

mat = mat[select][:,select]

try:
    dist = bellman_ford(csgraph_from_dense(mat), indices=[0])
    answer = int(.5-dist[0,-1])
    if answer < 0:
        answer = 0
except:
    answer = -1
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))
G = dict()
G_rev = dict()

for i in range(1, N + 1):
    G[i] = dict()
    G_rev[i] = dict()

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

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > 2*N:
        res = -1
        break

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

Submission status: Wrong Answer

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

import numpy as np
from scipy.sparse.csgraph import bellman_ford, csgraph_from_dense, connected_components

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

mat = np.full((N+1,N+1), np.inf)
for a,b,c in ABC:
    mat[a][b] = P - c

mat[N][1] = 1
_,comp = connected_components(mat != np.inf, connection='strong')
mat[N][1] = np.inf
select = (comp == comp[1])

mat = mat[select][:,select]

try:
    dist = bellman_ford(csgraph_from_dense(mat), indices=[0])
    answer = int(.5-dist[0,-1])
    if answer < 0:
        answer = 0
except:
    answer = -1
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))
G = dict()
G_rev = dict()

for i in range(1, N + 1):
    G[i] = dict()
    G_rev[i] = dict()
    
for _ in range(M):
    A, B, C = map(int, input().split())
    G[A][B] = P - C
    G_rev[B][A] = 1

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > N:
        res = -1
        break

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

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
INF = float('inf')
for i in range(2*N+100):
    for a,b,c in ABC:
        x = dist[a] + P - c
        if dist[b] > x:
            dist[b] = x
            if i > N:
                dist[b] = -INF

answer = -dist[N]
if answer == INF:
    answer = -1
elif 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] = P - C
    G_rev[B][A] = 1

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > N:
        res = -1
        break

if res == -1:
    print(res)
else:
    assert dist[N] < 10000000000
    print(max(0, -dist[N]))

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] = P - C
    G_rev[B][A] = 1

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > N:
        res = -1
        break

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

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]["keiro"] = set([0])
	tree[i]["score"] = -1000000000000000
	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

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

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] = P - C
    G_rev[B][A] = 1

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

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

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

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

reachable = [reachable_1[i] * reachable_N[i] for i in range(N + 1)]

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > 10000:
        res = -1
        break

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

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]["keiro"] = set([0])
	tree[i]["score"] = -1000000000000000
	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

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

print(tree)
for i in range(N):
	print(tree[i]["score"])

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]["keiro"] = set([0])
	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

stack = [0]
tree[0]["keiro"].add(0)
while len(stack) > 0:
	node = stack.pop()
	for edge in tree[node]["eda"]:
		if tree[edge[1]]["reach"] == 1:
			if edge[1] in tree[edge[1]]["keiro"]:
				if tree[edge[0]]["score"] + edge[2] - P > tree[edge[1]]["score"]:
					print(-1)
					exit()
			else:
				if tree[edge[1]]["score"] < tree[edge[0]]["score"] + edge[2] - P:
					tree[edge[1]]["score"] = tree[edge[0]]["score"] + edge[2] - P
					stack.append(edge[1])
					tree[edge[1]]["keiro"] = copy.deepcopy(tree[edge[0]]["keiro"])
					tree[edge[1]]["keiro"].add(edge[1])
print(max(tree[N - 1]["score"],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
  ret=[]
  while count<n*2:
    update=False
    for i in range(w):
      e0,e1,e2=es[i]
      if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
        d[e1]=d[e0]+e2
        update=True
    if not update:
      ret=[d[-1],d[-1]]
      break
    else:
      count+=1
      if count%n==0:
        ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(max(0,-d2))

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] = P - 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

dist = [10000000000] * (N + 1)
res = 0
dist[1] = 0
queue = deque([1])
cnt = 0

update = True

while update:
    update = False
    for p in range(1, N + 1):
        if reachable[p] == 0:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                update = True
    cnt += 1
    if cnt > 10000:
        res = -1
        break
        
if res == -1:
    print(res)
else:
    print(max(0, -dist[N]))

Submission status: Wrong Answer

Solution code:
N, M, P = map(int, input().split())
E = [list(map(int, input().split())) for _ in range(M)]
A = [-float("inf")] * (N+1)
A[1] = 0
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
A_copy = A[:]
for v in range(N):
    for a, b, c in E:
        t = A[a] + c - P
        if t > A[b]:
            A[b] = t
if A_copy!=A:
    print(-1)
else:
    print(max(0, A[-1]))

Submission status: Wrong Answer

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

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


    for _ in range(M):
        A,B,C = map(int,input().split())
        edges.append([A-1,B-1,P-C])

    reachable_from = [False for _ in range(N)]
    reachable_from[0] = True
    reachable_to = [False for _ in range(N)]
    reachable_to[N-1] = True

    for i in range(N-1):
        for edge in edges:
            if reachable_from[edge[0]]:
                reachable_from[edge[1]] = True
            if reachable_to[edge[1]]:
                reachable_to[edge[0]] = True

    edges2 = []
    for edge in edges:
        if reachable_from[edge[0]] and reachable_to[edge[1]]:
            edges2.append(edge)

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N):
        for edge in edges2:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
                if i==N-1:
                    print(-1)
        else:
            continue
        break
    else:
        print(max(0,-1*dist[N-1]))

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())
    edges = []


    for _ in range(M):
        A,B,C = map(int,input().split())
        edges.append([A-1,B-1,P-C])

    reachable_from = [False for _ in range(N)]
    reachable_from[0] = True
    reachable_to = [False for _ in range(N)]
    reachable_to[N-1] = True

    for i in range(N-1):
        for edge in edges:
            if reachable_from[edge[0]]:
                reachable_from[edge[1]] = True
            if reachable_to[edge[1]]:
                reachable_to[edge[0]] = True

    edges2 = []
    for edge in edges:
        if reachable_from[edge[0]] and reachable_to[edge[0]]:
            edges2.append(edge)

    inf = 10000*(10**5)
    dist = [inf for _ in range(N)]
    dist[0] = 0

    for i in range(N):
        for edge in edges2:
            if dist[edge[1]] > dist[edge[0]] + edge[2]:
                dist[edge[1]] = dist[edge[0]]+edge[2]
                if i==N-1:
                    print(-1)
        else:
            continue
        break
    else:
        print(max(0,-1*dist[N-1]))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    FORWARD = defaultdict(lambda: [])
    BACK = defaultdict(lambda: [])
    for a, b, c in ABC:
        t = FORWARD[a]
        t.append((b, c))
        FORWARD[a] = t

        t = BACK[b]
        t.append((a, c))
        BACK[b] = t

    mem = {N}
    q = [N]
    while len(q) != 0:
        t = q.pop()
        for t2, _ in BACK[t]:
            if t2 in mem:
                continue
            q.append(t2)
            mem.add(t2)

    # print(mem)
    poss = [(1, 0, {1})]

    table = [MIN] * N
    # table2 = [-1] * N
    for _ in range(5001):
        local_table = [(MIN, None)] * N
        for pos, score, history in poss:
            for nxt, s2 in FORWARD[pos]:
                if nxt not in mem:
                    continue
                if nxt in history and score + s2 - P > table[nxt - 1]:
                    print(-1)
                    return
                if score + s2 - P > local_table[nxt - 1][0]:
                    h2 = set(history)
                    h2.add(nxt)
                    local_table[nxt - 1] = score + s2 - P, h2
                # table2[nxt - 1] = history
                table[nxt - 1] = max(score + s2 - P, table[nxt - 1])
        newposs = []
        for i, (s, his) in enumerate(local_table):
            if s == MIN:
                continue
            newposs.append((i + 1, s, his))
        poss = newposs
    print(max(0, table[N - 1]))


if __name__ == '__main__':
    main()

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] = P - 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

dist = [10000000000] * (N + 1)
res = 0
dist[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 dist[p] + G[p][q] < dist[q]:
            dist[q] = dist[p] + G[p][q]
            queue.append(q)
            cnt += 1
    if cnt > 1000000:
        res = -1
        break

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque
import sys
import heapq
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


def main():
    # N = int(input())
    N, M, P = [int(a) for a in input().split()]
    ABC = [
        [int(a) for a in input().split()]
        for _ in range(M)
    ]

    FORWARD = defaultdict(lambda: [])
    BACK = defaultdict(lambda: [])
    for a, b, c in ABC:
        t = FORWARD[a]
        t.append((b, c))
        FORWARD[a] = t

        t = BACK[b]
        t.append((a, c))
        BACK[b] = t

    mem = {N}
    q = [N]
    while len(q) != 0:
        t = q.pop()
        for t2, _ in BACK[t]:
            if t2 in mem:
                continue
            q.append(t2)
            mem.add(t2)

    # print(mem)
    poss = [(1, 0, set())]

    table = [MIN] * N
    # table2 = [-1] * N
    for _ in range(5001):
        local_table = [(MIN, None)] * N
        for pos, score, history in poss:
            for nxt, s2 in FORWARD[pos]:
                if nxt not in mem:
                    continue
                if nxt in history and score + s2 - P > table[nxt - 1]:
                    print(-1)
                    return
                table[nxt - 1] = max(score + s2 - P, table[nxt - 1])
                history.add(nxt)
                local_table[nxt - 1] = table[nxt - 1], history
                # table2[nxt - 1] = history
        newposs = []
        for i, (s, his) in enumerate(local_table):
            if s == MIN:
                continue
            newposs.append((i + 1, s, his))
        poss = newposs
    print(max(0, table[N - 1]))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

for i in range(M):
    A, B, C = map(int, input().split())
    edge.append((A, B, P-C))

inf = float('inf')
cost = [inf] * (N+1)
cost[1] = 0
for i in range(N-1):
    for e in edge:
        a, b, c = e
        if cost[a] + c < cost[b]:
            cost[b] = cost[a] + c

for e in edge:
    a, b, c = e
    if cost[a] + c < cost[b]:
        if b == N:
            print(-1)
            exit()
        cost[b] = cost[a] + c
        
print(max(-cost[N], 0))