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

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


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

def dfs2(v):
    for u in edge[v]:
        if u == n - 1:
            visited2[u] = 1
            break
        if visited2[u] == 0:
            visited2[u] = 1
            dfs2(u)
for i in range(1, n):
    visited2 = [0] * n
    visited2[i] = 1
    dfs2(i)
    if visited2[n-1] == 0 and flag[i] == 1:
        flag[i] = 0

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

q = deque()
q.append((0, 0))
visited3 = [0] * n
visited3[0] = 1
ans = [0] * n
iter = 0
impossible = False
while q:
    v, c = q.popleft()
    for u in edge[v]:
        if u not in target_v:
            continue
        if visited3[u] == 0:
            ans[u] = c + coin[v][u]
            visited3[u] = 1
            q.append((u, c + coin[v][u]))
        else:
            if ans[u] <= c + coin[v][u]:
                impossible = True
                break

    if impossible:
        break

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

Submission status: Runtime Error

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

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

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

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

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

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 5 + 5)


def omit(n, links, parents):
    def remove_child(v):
        for u in parents[v]:
            if u == v:
                continue
            links[u].remove(v)
            ps = links[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_child(u)

    def remove_parent(v):
        for u in links[v]:
            if u == v:
                continue
            parents[u].remove(v)
            ps = parents[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_parent(u)

    drop = [False] * n
    for v, s in enumerate(links):
        if v == n - 1:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_child(v)

    for v, s in enumerate(parents):
        if v == 0:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_parent(v)

    # print(drop)
    # print(links)
    # print(parents)

    return drop


n, m, p = list(map(int, input().split()))
INF = 10 ** 12
costs = [[INF] * n for _ in range(n)]
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    parents[b].add(a)
    costs[a][b] = min(costs[a][b], p - c)
drop = omit(n, links, parents)

remains = [v for v, f in enumerate(drop) if f == False]

dist = [INF] * n
dist[0] = 0
for _ in range(n + 1):
    updated = False
    for v in remains:
        d = dist[v]
        if d == INF:
            continue
        cv = costs[v]
        for u in links[v]:
            if dist[u] > d + cv[u]:
                dist[u] = d + cv[u]
                updated = True
    # print(dist, updated)
    if not updated:
        break
else:
    print(-1)
    exit()

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

Submission status: Runtime Error

Solution code:
n, m, p = [int(x) for x in input().split()]
es      = []
cs      = {}
fs      = []
vs      = []
ss      = {}

for i in range(0, n + 1):
	es.append([])
	fs.append(False)

for i in range(0, m):
	a, b, c = [int(x) for x in input().split()]
	
	if a != b:
		es[a].append(b)
		cs[(a, b)] = c
	else:
		ss[a] = c

def search(v, c, t, fs, vs):
	if v == n:
		return max(c - t * p, 0), vs[:]
	else:
		r  = -1
		xs = None
		
		for u in es[v]:
			if fs[u] == False:
				fs[u] = True
				vs.append(u)
				
				q, ys = search(u, c + cs[(v, u)], t + 1, fs, vs)
				
				fs[u] = False
				vs.pop()
				
				if r < q:
					r  = q
					xs = ys
					
					
		return r, xs

r, xs = search(1, 0, 0, fs, vs)

if r < 0:
	print(-1)
else:
	is_none = False

	for x in xs:
		if x in ss and p < ss[x]:
			print(-1)
			is_none = True
	
	if is_none == False:
		print(r)

Submission status: Runtime Error

Solution code:
import sys


def omit(n, links, parents):
    def remove_child(v):
        for u in parents[v]:
            if u == v:
                continue
            links[u].remove(v)
            ps = links[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_child(u)

    def remove_parent(v):
        for u in links[v]:
            if u == v:
                continue
            parents[u].remove(v)
            ps = parents[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_parent(u)

    drop = [False] * n
    for v, s in enumerate(links):
        if v == n - 1:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_child(v)

    for v, s in enumerate(parents):
        if v == 0:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_parent(v)

    # print(drop)
    # print(links)
    # print(parents)

    return drop


n, m, p = list(map(int, input().split()))
INF = 10 ** 12
costs = [[INF] * n for _ in range(n)]
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    parents[b].add(a)
    costs[a][b] = min(costs[a][b], p - c)
drop = omit(n, links, parents)

remains = [v for v, f in enumerate(drop) if f == False]

dist = [INF] * n
dist[0] = 0
for _ in range(n):
    updated = False
    for v in remains:
        d = dist[v]
        if d == INF:
            continue
        cv = costs[v]
        for u in links[v]:
            if dist[u] > d + cv[u]:
                dist[u] = d + cv[u]
                updated = True
    # print(dist, updated)
    if not updated:
        break
else:
    print(-1)
    exit()

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

Submission status: Runtime Error

Solution code:
import sys
import math


def solve(N, M, P, A, B, C):
    edges = []
    for a, b, c in zip(A, B, C):
        edges.append((a, b, P - c))

    prev = [-1] * (1 + N)

    cost = [math.inf] * (1 + N)
    cost[1] = 0

    infloop = True
    for _ in range(N):
        update = False
        for a, b, c in edges:
            if cost[a] != math.inf and cost[b] > cost[a] + c:
                update = True
                cost[b] = cost[a] + c
                prev[b] = a
        if not update:
            infloop = False
            break

    if infloop:
        v = N
        for _ in range(N + 1):
            v = prev[v]
            if v == 1:
                break
        else:
            return -1

    return max(0, -cost[N])


# -----------------------------------------------------------------------------
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()

    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))

    ans = solve(N, M, P, A, B, C)
    if ans is not None:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import math


def solve(N: int, M: int, P: int, A: "List[int]", B: "List[int]", C: "List[int]"):
    edges = []
    for a, b, c in zip(A, B, C):
        edges.append((a, b, P - c))

    prev = [-1] * (1 + N)

    cost = [math.inf] * (1 + N)
    cost[1] = 0

    for _ in range(N):
        update = False
        for a, b, c in edges:
            if cost[a] != math.inf and cost[b] > cost[a] + c:
                update = True
                cost[b] = cost[a] + c
                prev[b] = a
        if not update:
            break
    else:
        v = N
        for _ in range(N + 1):
            v = prev[v]
            if v == 1:
                break
        else:
            return - 1

    return max(0, -cost[N])


# -----------------------------------------------------------------------------
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()

    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))

    ans = solve(N, M, P, A, B, C)
    if ans is not None:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys


def omit(n, links, parents):
    def remove_child(v):
        for u in parents[v]:
            if u == v:
                continue
            links[u].remove(v)
            ps = links[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_child(u)

    def remove_parent(v):
        for u in links[v]:
            if u == v:
                continue
            parents[u].remove(v)
            ps = parents[u]
            if not ps or (len(ps) == 1 and list(ps)[0] == u):
                drop[u] = True
                remove_parent(u)

    drop = [False] * n
    for v, s in enumerate(links):
        if v == n - 1:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_child(v)

    for v, s in enumerate(parents):
        if v == 0:
            continue
        if not s or (len(s) == 1 and list(s)[0] == v):
            drop[v] = True
            remove_parent(v)

    # print(drop)
    # print(links)
    # print(parents)

    return drop


n, m, p = list(map(int, input().split()))
INF = 10 ** 9
costs = [[INF] * n for _ in range(n)]
links = [set() for _ in range(n)]
parents = [set() for _ in range(n)]
for line in sys.stdin:
    a, b, c = map(int, line.split())
    a -= 1
    b -= 1
    links[a].add(b)
    parents[b].add(a)
    costs[a][b] = min(costs[a][b], p - c)
drop = omit(n, links, parents)

remains = [v for v, f in zip(range(n), drop) if f == False]

dist = [INF] * n
dist[0] = 0
for _ in range(m):
    updated = False
    for v in remains:
        d = dist[v]
        if d == INF:
            continue
        cv = costs[v]
        for u in links[v]:
            if dist[u] > d + cv[u]:
                dist[u] = d + cv[u]
                updated = True
    if not updated:
        break
else:
    print(-1)
    exit()

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