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

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

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

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

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

Submission status: Runtime Error

Solution code:
n,m,p = map(int,input().split())
graph = [[] for _ in range(n)]
INF = float("inf")
dist = [INF]*n
dist[0] = 0

for _ in range(m):
	f,t,c = map(int,input().split())
	graph[f-1].append((t-1,p-c))
#print(graph)

for _ in range(n):
	update = False
	for f,e in enumerate(graph):
		for t,c in e:
			if dist[f] != INF and dist[t] > dist[f] + c:
				dist[t] = dist[f] + c
				update = True
	if not update:
		break
else:
	prev = dist[-1]
    for _ in range(n):
		for f,e in enumerate(graph):
			for t,c in e:
				if dist[f] != INF and dist[t] > dist[f] + c:
					dist[t] = -INF
	if dist[-1] != prev:
		print(-1)
		exit()
#print(dist)

print(max(0,dist[-1]*(-1)))

Submission status: Runtime Error

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

class Edge:
    def __init__(self, from_, to_, point):
        self.from_, self.to_, self.point = from_, to_, point
    
edge_list = [Edge(*[int(s)for s in input().split()]) for _ in range(M)]
end_point = max(edge.to_ for edge in edge_list)
end_edge_list = [edge for edge in edge_list if edge.to_ == end_point]


def backToStart(edge, T=1, via=[], infinite=False):
    if edge.from_ == 1:
        return edge, T, via, infinite
    if edge.to_ == edge.from_:
        if edge.point - P > 0:
            ls = [edge_ for edge_ in edge_list if edge_.to_ == edge.from_ and edge_.to_ != edge_.from_]
            if len(ls) == 1:
                return backToStart(ls[0], T+1, infinite=True)
            else:
                return [backToStart(edge, T+1, infinite=True) for edge in ls]
        else:
            return "DEADEND"
    edge_list_ = [edge_ for edge_ in edge_list if edge_.to_ == edge.from_]
    via_ = via[:]
    via_.append(edge)
    if len(edge_list_) == 1:
        return backToStart(edge_list_[0], T+1, via_)
    else:
        return [backToStart(edge, T+1, via_) for edge in edge_list_]

def multiEdges(edge_list):
    return [backToStart(edge) for edge in edge_list]

origin_edge_list = multiEdges(end_edge_list)

# print(origin_edge_list)

while True:
    if 'DEADEND' in origin_edge_list:
        origin_edge_list.remove('DEADEND')
    elif [] in origin_edge_list:
        origin_edge_list.remove([])
    else:
        break

def hoge():
    point_list = []
    for route in origin_edge_list:
        if route[3]:
            return -1
        ls = route[2][:]
        ls.append(route[0])
        point_list.append(sum(e.point for e in ls) - route[1] * P)
    return point_list

ans = hoge()
if isinstance(ans, int):
    print(ans)
else:
    ans.append(0)
    print(max(ans))

Submission status: Runtime Error

Solution code:
def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(M)]
    li = defaultdict(list)

    for i in range(M):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - P)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top.copy()
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                    li_top.append(e[0])
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]
                        li_top.append(e[0])

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(M)]
    li = defaultdict(list)

    for i in range(N):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - P)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top.copy()
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                    li_top.append(e[0])
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]
                        li_top.append(e[0])

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(M)]
    li = defaultdict(list)

    for i in range(N):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - P)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top.copy()
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                li_top.append(e[0])
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
from collections import defaultdict


def p_e():
    N, M, P = map(int, input().split())
    abc = [tuple(map(int, input().split())) for _ in range(N)]
    li = defaultdict(list)

    for i in range(N):
        li[abc[i][0]].append((abc[i][1], -(abc[i][2] - 10)))

    li_ans = defaultdict()
    li_ans[1] = 0
    li_top = [1]
    lt = []
    bf_n = -1
    while li_top and li_top != lt:
        lt = li_top.copy()
        li_top = []
        if N in li_ans.keys():
            bf_n = li_ans[N]

        for i in lt:
            for e in li[i]:
                li_top.append(e[0])
                if not e[0] in li_ans.keys():
                    li_ans[e[0]] = e[1] + li_ans[i]
                else:
                    if li_ans[e[0]] > e[1] + li_ans[i]:
                        li_ans[e[0]] = e[1] + li_ans[i]

    if li_top == lt and bf_n != li_ans[N]:
        print(-1)
    else:
        print(max(0, -li_ans[N]))


if __name__ == '__main__':
    p_e()

Submission status: Runtime Error

Solution code:
def BF(edges,n,s):
    inf=float("inf")
    d=[inf for i in range(n+1)]
    d[s]=0
    update=True
    cnt=0
    while 1:
      update=False
      for v,u,cost in edges:
        if cand[v]!=1 or cand[u]!=1:
          continue
        if d[v]!=inf and d[u]>d[v]+cost:
          d[u]=d[v]+cost
          update=True
      if update==False:
        break
      cnt+=1
      if cnt>n:
        return inf
    return -d[-1]

def DFS_1toN(v):
  for u in to[v]:
    if toflag[u]==0:
      toflag[u]=1
      DFS_1toN(u)
      
def DFS_Nto1(v):
  for u in ot[v]:
    if otflag[u]==0:
      otflag[u]=1
      DFS_Nto1(u)
    
n,m,p=map(int,input().split())
g=[]
to=[[] for _ in range(n+1)]
ot=[[] for _ in range(n+1)]
for _ in range(m):
  a,b,c=map(int,input().split())
  g.append([a,b,-(c-p)])
  to[a].append(b)
  ot[b].append(a)
toflag=[0]*(n+1)
toflag[1]=1
DFS_1toN(1)
otflag=[0]*(n+1)
otflag[n]=1
DFS_Nto1(n)
cand=[0]*(n+1)
for i in range(1,n+1):
  cand[i]=toflag[i]*otflag[i]
ans=BF(g,n,1)
if ans==float('inf'):
  print(-1)
else:
  print(max(ans,0))

Submission status: Runtime Error

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

def BellmanFord(Edges,num_v,start,goal):
    inf=float('inf')
    Dist=[inf]*num_v
    Dist[start]=0
    for _ in range(num_v):
        for fr,to,cost in Edges:
            if Dist[fr]!=inf and Dist[to]>Dist[fr]+cost:
                Dist[to]=Dist[fr]+cost
    d=Dist[goal]
    for _ in range(num_v):
        for fr,to,cost in Edges:
            if Dist[fr]!=inf and Dist[to]>Dist[fr]+cost:
                Dist[to]=-inf
    if d!=Dist[goal]:
        return -inf
    return d

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

Submission status: Runtime Error

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

from scipy.sparse.csgraph import bellman_ford, connected_components
from scipy.sparse import csr_matrix

N,M,P = map(int,input().split())
ABC = [[int(x) for x in input().split()] for _ in range(M)]
A,B,C = zip(*ABC)
C = [P-c for c in C]

graph = csr_matrix((C,(A,B)),(N+1,N+1))
graph2 = csr_matrix(([1]*(M+1),(A+(N,),B+(1,))),(N+1,N+1))
_,comp = connected_components(graph2, connection='strong')
select = (comp == comp[1])
graph = graph[select,:][:,select]

try:
    dist = bellman_ford(graph, indices=[0])
    answer = int((.5-dist[0,-1]) // 1)
    if answer < 0:
        answer = 0
except NegativeCycleError:
    answer = -1
print(answer)

Submission status: Runtime Error

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

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

    table = [MAX] * (N + 1)
    table[1] = 0
    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
    if -table[N] < 0:
        print(0)
        return
    score = -table[N]
    for a, b, c in ABC:
        if table[a] == MAX:
            continue
        if table[a] + c < table[b]:
            table[b] = table[a] + c
    if -table[N] != score:
        raise ValueError()
        print(-1)
        return
    print(-table[N])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque

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

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] = min(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: Runtime Error

Solution code:
from collections import defaultdict, deque

N, M, P = map(int, input().split())
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 = [None] * (N + 1)
dist[1] = 0
cnt = 0

success = True
for i in range(N + 10000):
    for p in range(1, N + 1):
        if reachable[p] == 0 or dist[p] is None:
            continue
        for q in G[p].keys():
            if reachable[q] == 0:
                pass
            elif dist[p] is None or dist[p] + G[p][q] < dist[q]:
                dist[q] = dist[p] + G[p][q]
                if i > N:
                    success = False


if not success:
    print(-1)
else:
    print(max(0, -dist[N]))

Submission status: Runtime Error

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]
d=[float("inf")]*n
d[0]=0
for i in range(n):
  e0,e1,e2=edge[i]
  if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
    d[e1]=d[e0]+e2
ans1=d[-1]
for i in range(n):
  e0,e1,e2=edge[i]
  if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
    d[e1]=d[e0]+e2
ans2=d[-1]
print(-1 if ans1!=ans2 else max(0,-ans2))

Submission status: Runtime Error

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=[]
  for i in range(2*n):
    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:
      if (i+1)%n==0 and len(ret)<2:
        ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Runtime Error

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 _ in range(M):
    A, B, C = map(int, input().split())
    if A not in G.keys():
        G[A] = dict()
    if B not in G_rev.keys():
        G_rev[B] = dict()
    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: Runtime Error

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=[]
  for i in range(2*n):
    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:
      if (i+1)%n==0:
        ret.append(d[-1])
  return ret
d1,d2=sp(0,n,m,edge)
print(-1 if d1!=d2 else max(0,-d2))

Submission status: Runtime Error

Solution code:
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: Runtime Error

Solution code:
from scipy.sparse import*
N,M,P,*E=map(int,open(0).read().split())
D=csgraph.bellman_ford(csr_matrix(([P-c for c in E[5::3]],(E[3::3],E[4::3])),[N+1]*2),1,1)[N]
print(int([max(-D,0),-1][D>9e9]))

Submission status: Runtime Error

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 = {*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: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import sys
N, M, P = [int(x) for x in input().split()]
forward = {}
backward = {}
for _ in range(M):
  A, B, C = [int(x) for x in input().split()]
  forward[A] = forward.get(A, {})
  if B in forward[A]:
    forward[A][B] = max(forward[A][B], C-P)
  else:
    forward[A][B] = C-P
  backward[B] = backward.get(B, {})
  if A in backward[B]:
    backward[B][A] = max(backward[B][A], C-P)
  else:
    backward[B][A] = C-P
#print(forward)
#print(backward)
reachable = set([N])
to_track = set([N])
while to_track:
  x = to_track.pop()
  if x not in backward:
    continue
  for y in backward[x]:
    if y not in reachable:
      to_track.add(y)
      reachable.add(y)
#print(reachable)
if 1 not in reachable:
  print(-1)
  sys.exit()

forward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
           for k, v in forward.items() if k in reachable}
#print(forward)
# backward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
#            for k, v in backward.items() if k in reachable}
#print(backward)


reached = [0]  # score is not negative
def dfs(x, point, visited):
  #print(x,point,visited)
  if x == N:
    reached.append(point)
  if x not in forward:
    visited[x].pop()
    return
  #print(forward[x])
  for y, p in forward[x].items():
    if y in visited and visited[y]:
      #print(y, p, 'visited')
      for q in visited[y]:
        if point+p > q:
    #      print(x, y, p, point, visited)
          print(-1)
          sys.exit()
      visited[x].pop()
      return
    else:
      #print(y, p, 'to_visit')
      visited[y] = visited.get(y, [])
      visited[y].append(point+p)
      dfs(y, point+p, visited)
  visited[x].pop()
  return
dfs(1, 0, {1: [0]})
#print(reached)
print(max(reached))

Submission status: Runtime Error

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

Submission status: Runtime Error

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

def BellmanFord(Edges,num_v,source):
    inf=float('inf')
    dist=[inf for _ in range(num_v)]
    dist[source]=0
    for i in range(num_v):
        for edge in Edges:
            if edge[0]!=inf and dist[edge[1]]>dist[edge[0]]+edge[2]:
                dist[edge[1]]=dist[edge[0]]+edge[2]
                if i==num_v-1:
                    before_dist=dist[num_v-1]
                    for i in range(num_v):
                        for edge in edges:
                            if edge[0]!=inf and dist[edge[1]] > dist[edge[0]]+edge[2]:
                                dist[edge[1]]=dist[edge[0]]+edge[2]
                    if before_dist!=dist[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
    Edges.append((a,b,-(c-p)))
d=BellmanFord(Edges,n,0)
print(-1 if d==-1 else max(0,-d[-1]))

Submission status: Runtime Error

Solution code:
import sys
N, M, P = [int(x) for x in input().split()]
forward = {}
backward = {}
for _ in range(M):
  A, B, C = [int(x) for x in input().split()]
  forward[A] = forward.get(A, {})
  if B in forward[A]:
    forward[A][B] = max(forward[A][B], C-P)
  else:
    forward[A][B] = C-P
  backward[B] = backward.get(B, {})
  if A in backward[B]:
    backward[B][A] = max(backward[B][A], C-P)
  else:
    backward[B][A] = C-P
#print(forward)
#print(backward)
reachable = set([N])
to_track = set([N])
while to_track:
  x = to_track.pop()
  if x not in backward:
    continue
  for y in backward[x]:
    if y not in reachable:
      to_track.add(y)
      reachable.add(y)
#print(reachable)
if 1 not in reachable:
  print(-1)
  sys.exit()

forward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
           for k, v in forward.items() if k in reachable}
#print(forward)
# backward = {k: {k2: v2 for k2, v2 in v.items() if k2 in reachable}
#            for k, v in backward.items() if k in reachable}
#print(backward)


reached = [0]  # score is not negative
def dfs(x, point, visited):
  #print(x,point,visited)
  if x == N:
    reached.append(point)
  if x not in forward:
    visited[x].pop()
    return
  #print(forward[x])
  for y, p in forward[x].items():
    if y in visited and visited[y]:
      #print(y, p, 'visited')
      for q in visited[y]:
        if point+p > q:
    #      print(x, y, p, point, visited)
          print(-1)
          sys.exit()
      visited[x].pop()
      return
    else:
      #print(y, p, 'to_visit')
      visited[y] = visited.get(y, [])
      visited[y].append(point+p)
      dfs(y, point+p, visited)
dfs(1, 0, {1: [0]})
#print(reached)
print(max(reached))

Submission status: Runtime Error

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

G = [[] for i in range(N+1)]

costs = {}

def loop(v):
    print(v)
    exit()

for i in range(M):
    a,b,c = map(int,input().split())
    c = c-P
    if a==b:
        if a == N:
            loop(-1)
        else:
            continue
    G[a].append(b)
    costs[(a,b)] = c

# print(G)

def bfs(node,depth,visited):
    val = -float("inf")
    # print(G[node],depth,visited)
    if len(G[node])==0:
        if node == N:
            return 0
        else:
            return val
    for n in G[node]:
        if n in visited:
            if val >=0:
                continue
            else:
                loop(-1)
        val = max(val,costs[node,n]+bfs(n,depth+1, tuple(visited+(n,))))
    return val

val = bfs(1,0,())

print(max(val,0))