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: Time Limit Exceeded

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]


cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            # if cost[B - 1] == np.inf:
            #     pass
            # elif cost[B - 1] < cost[pos - 1] + C:
            #     cost[B - 1] = np.inf
            #     solve(B, already)
            if cost[B - 1] == np.inf:
                pass
            elif cost[pos-1] == np.inf or cost[B - 1] < cost[pos - 1] + C:
                cost[B-1] = np.inf
                solve(B, already)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            already2 = already.copy()
            already2[B - 1] = True
            solve(B, already2)


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse import*
m=csr_matrix
n,_,p,*t=map(int,open(0).read().split())
s=[n+1]*2
r,c,d=t[::3],t[1::3],[p-c for c in t[2::3]]
u=set(csgraph.depth_first_order(m((d,(r,c)),s),1,1,0))
v=set(csgraph.depth_first_order(m((d,(c,r)),s),n,1,0))
u&=v
E=[(r,c,d)for r,c,d in zip(r,c,d)if r in u and c in u]
D=[10**9]*(n+1)
D[1]=0
for _ in'_'*n:
	for a,b,c in E:D[b]=min(D[b],D[a]+c)
ans=D[n]
for a,b,c in E:
	if D[b]>D[a]+c:
		print(-1)
		exit()
print(max(-ans,0))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
# ABC = [list(map(int, input().split())) for _ in range(M)]
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

# print (ABC_d)

cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0

def solve(pos, already):
    global cost
    global already2

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = np.inf
                solve(B, already)
        else:
            if cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = cost[pos - 1] + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, already2)


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
sys.setrecursionlimit(10000000)

N, M, P = map(int, input().split())
# ABC = [list(map(int, input().split())) for _ in range(M)]
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

# print (ABC_d)

cost = np.empty(N, dtype = int) - np.inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return
    # print (already)

    for B, C in ABC_d[pos]:
        if already[B - 1] == True:
            if cost[B - 1] == np.inf:
                pass
            elif cost[B - 1] < cost[pos - 1] + C:
                # looped = True
                cost[B - 1] = np.inf
                solve(B, already)
            # else:
            #     pass
        else:
            if cost[B - 1] < cost[pos - 1] + C:
                cost[B - 1] = cost[pos - 1] + C
                already2 = already.copy()
                already2[B - 1] = True
                solve(B, already2)
            # else:
            #     pass


already = np.zeros(N, dtype = bool)
already[0] = True
solve(1, already)

if (cost[-1] == np.inf):
    print (-1)
else:
    print (max(0, int(cost[-1])))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict as dd
import sys
sys.setrecursionlimit(6000)
N, M, P = map(int, input().split())
edges = []
revedgedict = dd(dict)
for _ in range(M):
  f, t, c = map(int, input().split())
  edges.append((f-1, t-1, -(c-P)))
  revedgedict[t-1][f-1] = 1

# Nに到達できない頂点を削除
visited = [False] * N
def dfs(f):
  visited[f] = True
  for t in revedgedict[f].keys():
    if not visited[t]:
      dfs(t)
dfs(N-1)

# ベルマンフォード
INF = float('inf')
d = [float('inf')] * N
d[0] = 0
for i in range(N):
  updated = False
  for f, t, c in edges:
    if d[f] != INF and visited[t] and d[t] > d[f] + c:
      d[t] = d[f] + c
      updated = True
  if not updated:
    break
else:
  print(-1)
  exit()
print(max(-d[-1], 0))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit((10 ** 6))
input = sys.stdin.readline
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))

check = [False] * N
used = [False] * N


def dfs(u):
    if used[u]:
        return
    used[u] = True
    for w, c in G[u]:
        dfs(w)


def dfs2(u, dest):
    dfs(u)
    check[u] = used[dest]


dist = [INF] * N
for i in range(N):
    used = [False] * N
    dfs2(i, N - 1)

dist[0] = 0
for i in range(N):
    update = False
    for e in range(N):
        if not check[e]:
            continue
        for w, c in G[e]:
            if not check[w]:
                continue
            if dist[e] != INF and dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                update = True

    if not update:
        break
    if i == N - 1:
        print(-1)
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit((10 ** 6))
input = sys.stdin.readline
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))

check = [False] * N


def dfs(u, used):
    if used[u]:
        return
    used[u] = True
    for w, c in G[u]:
        dfs(w, used)


def dfs2(u, dest):
    used = [False] * N
    dfs(u, used)
    check[u] = used[dest]


dist = [INF] * N
for i in range(N):
    dfs2(i, N - 1)

dist[0] = 0
for i in range(N):
    update = False
    for e in range(N):
        if not check[e]:
            continue
        for w, c in G[e]:
            if not check[w] or dist[e] == INF:
                continue
            if dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                update = True

    if not update:
        break
    if i == N - 1:
        print(-1)
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit((10 ** 6))
input = sys.stdin.readline
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))

check = [False] * N


def dfs(u, used):
    if used[u]:
        return
    used[u] = True
    for w, c in G[u]:
        dfs(w, used)


def dfs2(u, dest):
    used = [False] * N
    dfs(u, used)
    check[u] = used[dest]


dist = [INF] * N
for i in range(N):
    dfs2(i, N - 1)

dist[0] = 0
for i in range(N):
    update = False
    for e in range(N):
        for w, c in G[e]:
            if not check[e] or not check[w] or dist[e] == INF:
                continue
            if dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                update = True

    if not update:
        break
    if i == N - 1:
        print(-1)
        exit()

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def BellmanFord(adjList, vSt, INF):
    numV = len(adjList)
    negINF = -INF
    costs = [INF] * numV
    costs[vSt] = 0
    vNows = set([vSt])

    for _ in range(numV):
        vChangeds = set()
        for vFr in vNows:
            costFr = costs[vFr]
            for vTo, wt in adjList[vFr]:
                c2 = costFr + wt
                if c2 < costs[vTo]:
                    costs[vTo] = c2
                    vChangeds.add(vTo)
        if not vChangeds:
            return costs
        vNows = vChangeds

    for v in vNows:
        costs[v] = negINF

        Q = deque(vNows)
    while Q:
        vFr = Q.popleft()
        for vTo, wt in adjList[vFr]:
            if costs[vTo] == negINF: continue
            costs[vTo] = negINF
            Q.append(vTo)

    return costs


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

costs = BellmanFord(adjL, 0, float('inf'))

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit((10 ** 6))
N, M, P = map(int, input().split())
INF = float('inf')
G = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b, c = a - 1, b - 1, c - P
    G[a].append((b, -c))

check = [False] * N


def dfs(u, used):
    if used[u]:
        return
    used[u] = True
    for w, c in G[u]:
        dfs(w, used)


def dfs2(u, dest):
    used = [False] * N
    dfs(u, used)
    check[u] = used[dest]


dist = [INF] * N
for i in range(N):
    dfs2(i, N - 1)

dist[0] = 0
for i in range(N):
    update = False
    for e in range(N):
        for w, c in G[e]:
            if not check[e] or not check[w] or dist[e] == INF:
                continue
            if dist[w] > dist[e] + c:
                dist[w] = dist[e] + c
                update = True

    if not update:
        break
    if i == N - 1:
        print(-1)
        exit()

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

Submission status: Time Limit Exceeded

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

N, M, P = [int(item) for item in input().split()]

from collections import defaultdict
next_b = defaultdict(lambda: [])

for i in range(M):
    a, b, c = [int(item) for item in input().split()]
    next_b[a].append([b, c - P])

max_sc = [0] + [int(-1e30)] * (N - 1)

pos_n = [0]
flag = 1
changed_on_N = []

for loop in range(N + 1):
    # print(max_sc)
    if not flag:
        print(max(max_sc[N - 1], 0))
        break
    flag = 0
    add_n = []
    for i in pos_n:
        for d, scr in next_b[i + 1]:
            # print(route, d - 1, i)
            new_sc = max_sc[i] + scr
            if new_sc > max_sc[d - 1]:
                max_sc[d - 1] = new_sc
                add_n.append(d - 1)
                flag = 1
                if loop == N:
                    changed_on_N.append(d)
    pos_n = pos_n + add_n
else:
    affected_n = [0] * N
    loop_flag = 0
    while len(changed_on_N) > 0:
        c = changed_on_N.pop()
        if affected_n[c - 1] == 0:
            affected_n[c - 1] = 1
            for d, _ in next_b[c]:
                changed_on_N.append(d)
            if c == N:
                loop_flag = 1
                break
    if loop_flag:
        print(-1)
    else:
        print(max(max_sc[N - 1], 0))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

def main():

    import sys

    def input(): return sys.stdin.readline().strip()
    def list2d(a, b, c): return [[c] * b for i in range(a)]
    def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
    def ceil(x, y=1): return int(-(-x // y))
    def INT(): return int(input())
    def MAP(): return map(int, input().split())
    def LIST(): return list(map(int, input().split()))
    def Yes(): print('Yes')
    def No(): print('No')
    def YES(): print('YES')
    def NO(): print('NO')
    sys.setrecursionlimit(10 ** 9)
    INF = float('inf')
    MOD = 10 ** 9 + 7

    def bellman_ford(N: int, edges: list, src: int) -> list:
        """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

        # 頂点[ある始点からの最短距離] (経路自体を知りたい時はここに前の頂点も持たせる)
        res = [INF] * N
        res[src] = 0
        # 各辺によるコストの置き換えを頂点数N-1回繰り返す
        for i in range(N-1):
            for src, dest, cost in edges:
                if res[dest] > res[src] + cost:
                    res[dest] = res[src] + cost
        # 頂点Nが負の閉路に含まれていないかチェックする
        for i in range(N):
            for src, dest, cost in edges:
                if res[dest] > res[src] + cost:
                    # 検出した負閉路はすぐに-INFにする
                    res[dest] = -INF
                    if dest == N-1:
                        # 該当していたら空リストを返却
                        return []
        # 問題なければ頂点リストを返却
        return res

    N, M, P = MAP()
    edges = []
    for i in range(M):
        a, b, c = MAP()
        # Pは最後に請求される、だけど、ようは動く度に支払ってると思ってもいい
        edges.append((a-1, b-1, -c+P))

    res = bellman_ford(N, edges, 0)
    if not len(res):
        print(-1)
    else:
        # 正負を直す
        ans = -res[N-1]
        # スコアがマイナスなら0
        print(max(0, ans))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

def bellman_ford(N: int, edges: list, src: int) -> list:
    """ ベルマンフォード(頂点数, 辺集合(0-indexed), 始点) """

    # 頂点[ある始点からの最短距離] (経路自体を知りたい時はここに前の頂点も持たせる)
    res = [INF] * N
    res[src] = 0
    # 各辺によるコストの置き換えを頂点数N-1回繰り返す
    for i in range(N-1):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                res[dest] = res[src] + cost
    # 頂点Nが負の閉路に含まれていないかチェックする
    for i in range(N):
        for src, dest, cost in edges:
            if res[dest] > res[src] + cost:
                # 検出した負閉路はすぐに-INFにする
                res[dest] = -INF
                if dest == N-1:
                    # 該当していたら空リストを返却
                    return []
    # 問題なければ頂点リストを返却
    return res

N, M, P = MAP()
edges = []
for i in range(M):
    a, b, c = MAP()
    # Pは最後に請求される、だけど、ようは動く度に支払ってると思ってもいい
    edges.append((a-1, b-1, -c+P))

res = bellman_ford(N, edges, 0)
if not len(res):
    print(-1)
else:
    # 正負を直す
    ans = -res[N-1]
    # スコアがマイナスなら0
    print(max(0, ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def solve():
    N, M, P = map(int, input().split())
    G = [[] for i in range(N)]
    RG = [[] for i in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        G[a-1].append((b-1, P-c))
        RG[b-1].append((a-1, P-c))

    def chk(s, G):
        P = [0]*N
        que = deque([s])
        used = [0]*N
        used[s] = 1
        while que:
            v = que.popleft()
            P[v] = 1
            for w, c in G[v]:
                if used[w]:
                    continue
                que.append(w)
                used[w] = 1
        return P
    P0 = chk(0, G); P1 = chk(N-1, RG)
    F = [P0[i] == P1[i] == 1 for i in range(N)]
    I = [i for i in range(N) if F[i]]

    G0 = [[] for i in range(N)]
    for v in range(N):
        if not F[v]:
            continue
        for w, c in G[v]:
            if not F[w]:
                continue
            G0[v].append((w, c))

    dist = [10**18]*N
    dist[0] = 0
    L = len(I)
    for i in range(L):
        update = 0
        for v in I:
            d = dist[v]
            for w, c in G0[v]:
                if d + c < dist[w]:
                    dist[w] = d + c
                    update = 1
        if not update:
            break
    else:
        print("-1")
        return

    print(max(-dist[N-1], 0))
solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, M, P = map(int, input().split())
G = [[] for i in range(N)]
RG = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    G[a-1].append((b-1, P-c))
    RG[b-1].append((a-1, P-c))

def chk(s, G):
    P = [0]*N
    que = deque([s])
    used = [0]*N
    used[s] = 1
    while que:
        v = que.popleft()
        P[v] = 1
        for w, c in G[v]:
            if used[w]:
                continue
            que.append(w)
            used[w] = 1
    return P
P0 = chk(0, G); P1 = chk(N-1, RG)
I = []
for i in range(N):
    if P0[i] == P1[i] == 1:
        I.append(i)

dist = [10**18]*N
dist[0] = 0
L = len(I)
for i in range(L+1):
    update = 0
    for v in I:
        d = dist[v]
        for w, c in G[v]:
            if d + c < dist[w]:
                dist[w] = d + c
                update = 1
    if not update:
        break
else:
    print("-1")
    exit(0)

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

Submission status: Time Limit Exceeded

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

edge_array = []

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

INF = 10 ** 10

ans_array = [-INF] * N

ans_array[0] = 0
last_ans_change = -1

for i in range(N*2):
    change_flag = 0
    for edge in edge_array:
        a, b, c = edge
        if ans_array[b] < ans_array[a] + c:
            ans_array[b] = ans_array[a] + c
            change_flag = 1
            if b == N - 1:
                last_ans_change = i
    if change_flag == 0:
        break

if last_ans_change >= N:
    ans = -1
else:
    ans = max(0, ans_array[N-1])

print(ans)

Submission status: Time Limit Exceeded

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

edge_array = []

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

INF = 10 ** 10

ans_array = [-INF] * N

ans_array[0] = 0
last_ans_change = -1

for i in range(N*3):
    change_flag = 0
    for edge in edge_array:
        a, b, c = edge
        if ans_array[b] < ans_array[a] + c:
            ans_array[b] = ans_array[a] + c
            change_flag = 1
            if b == N - 1:
                last_ans_change = i
    if change_flag == 0:
        break

if last_ans_change >= N * 2:
    ans = -1
else:
    ans = max(0, ans_array[N-1])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, p = [ int(v) for v in input().split() ]
node_list = []
for i in range(m):
    a, b, c = [ int(v) for v in input().split() ]
    node_list.append((a-1,b-1,p-c))
distance_list = [ 10**15 for i in range(n) ]
parent_list = [ -1 for i in range(n) ]

distance_list[0] = 0
parent_list[0] = -1



for i in range(n-1):
    new_distanece_list = distance_list
    for j in node_list:
        a, b, c = j
        if distance_list[a] != 10**15:
            if new_distanece_list[b] > distance_list[a] + c:
                new_distanece_list[b] = distance_list[a] + c
                parent_list[b] = a
                change_log = 1
    distance_list = new_distanece_list
distance_list_1 = [ i for i in distance_list]

for i in range(n):
    new_distanece_list = distance_list
    for j in node_list:
        a, b, c = j
        if distance_list[a] != 10**15:
            if new_distanece_list[b] > distance_list[a] + c:
                new_distanece_list[b] = distance_list[a] + c
                parent_list[b] = a
                change_log = 1
    distance_list = new_distanece_list
distance_list_2 = distance_list



if distance_list_1[-1] == distance_list_2[-1]:
    print(-min(0,distance_list_1[-1]))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

def Bellman_Ford(g,start):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    a0 = float("inf")
    negative = [False]*n
    for i in range((2*n)):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if negative[v]: negative[to] = True
                if dist[to] <= dist[v] + cost: continue
                dist[to] = dist[v] + cost
                updated = True
                if i >= n:
                    negative[to] = True
        if not updated: break
    if negative[-1]: return None, False
    return dist, True
 

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m,p = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
for i in range(m):
    a,b,c = [int(i) for i in readline().split()]
    g[a-1].append((b-1,-c+p))
#    g[b-1].append((a-1,c))

dist, TF = Bellman_Ford(g, 0)

if TF: print(max(-dist[-1],0))
else: print(-1)

Submission status: Time Limit Exceeded

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 = [INF] * N #最短距離を記録しておくリスト
# prev = [-1] * N
negative = [False] * N
def restore(g): #gまでの最短経路を復元
    path = []
    g -= 1 #0-indexに直す
    path.append(g)
    g = prev[g]
    count = 0
    while g != -1:
        # print ('C')
        path.append(g)
        g = prev[g]
        count += 1
        if count == N + 2:
            break
    path.reverse()
    return path

def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
    s -= 1
    for i in range(N):
        d[i] = INF
    d[s] = 0
    count = 0
    while count < N - 1:
        count += 1
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
    
    count = 0
    while count < N:
        count += 1
        for i in range(M): #無向グラフのときは辺は実質的には2倍
            e = G[i]
            if d[e[0]] == INF:
                continue
            if d[e[0]] != INF and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                negative[e[1]] = True
            if negative[e[0]]:
                negative[e[1]] = True


#呼び出しスタート地点を入れる
shortest_path(1)
if negative[N - 1]:
    print (-1)
    # print (d)
    exit()
# print (d)
else:
    print (max(0, -d[N - 1]))

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res

def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    a,b = LI()
    print(max(a+b,a-b,a*b))
    return

#B
def B():
    k,x = LI()
    ans = []
    for i in range(x-k+1,x+k):
        ans.append(i)
    print(*ans)
    return

#C
def C():
    def f(s):
        res = [0]*m
        for i in s:
            res[alp.index(i)] += 1
        return res
    alp = list("abcdefghijklmnopqrstuvwxyz")
    m = len(alp)
    n = I()
    s = [input() for i in range(n)]
    d = defaultdict(lambda : 0)
    for i in s:
        d[tuple(f(i))] += 1
    ans = 0
    for i in d.values():
        ans += (i*(i-1))//2
    print(ans)
    return

#D
def D():
    n,m = LI()
    g = LIR(n)
    g.sort(key = lambda x:x[0])
    ans = 0
    f = [1]*n
    j = 0
    q = []
    for i in range(m)[::-1]:
        while j < n and m-g[j][0] >= i:
            a,b = g[j]
            heappush(q,(-b,a))
            j += 1
        if q:
            x,a = heappop(q)
            if i+a <= m:
                ans -= x
    print(ans)
    return

#E
def E():
    def dfs(x,f):
        for y,w in v[x]:
            if f[y]:
                if dp[y] < dp[x]+w:
                    f[y] = 0
                    dp[y] = dp[x]+w
                    dfs(y,f)
                    f[y] = 1
            else:
                if dp[y] < dp[x]+w:
                    dp[y] = float("inf")
                    dfs(y,f)
    n,m,p = LI()
    v = [[] for i in range(n)]
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        v[a].append((b,c-p))
    f = [1]*n
    dp = [-float("inf")]*n
    dp[0] = 0
    f[0] = 0
    dfs(0,f)
    ans = dp[n-1]
    if ans == float("inf") or ans == -float("inf"):
        print(-1)
    elif ans < 0:
        print(0)
    else:
        print(ans)
    return

#F
def F():

    return

#Solve
if __name__ == "__main__":
    E()

Submission status: Time Limit Exceeded

Solution code:
def shortest_path(s,n,w,es):
    #s→iの最短距離
    # s:始点, n:頂点数, w:辺の数, es[i]: [辺の始点,辺の終点,辺のコスト]
    d = [float("inf")] * n
    #d[i] : s→iの最短距離
    d[s] = 0
    for _ in range(n*w+1):
        updata = False
        for p,q,r in es:
            # e: 辺iについて [from,to,cost]
            if d[p] != float("inf") and d[q] > d[p] + r:
                d[q] = d[p] + r
                updata = True
        if not updata:
            break
    return d

def main():
    import sys
    input = sys.stdin.readline
    n,m,p = map(int,input().split())
    es = []
    for _ in range(m):
        a,b,c = map(int,input().split())
        es.append([a-1,b-1,p-c])

    d = shortest_path(0,n,m,es)

    kouho = d[-1]

    for _ in range(5):
        updata = True
        for i in range(m):
            e = es[i]
            # e: 辺iについて [from,to,cost]
            if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                updata = True
        if not updata:
            break

    res = d[-1]

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
inf = float('inf')
V,E,P = map(int,input().split())
edge = []
edge_rev = []
for i in range(E):
    A,B,C = map(int,input().split())
    edge_rev.append([B-1,A-1,P-C])
    edge.append([A-1,B-1,P-C])

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

d_rev = [inf]*V
d_rev[V-1] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge_rev[j]
        if d_rev[From] != inf and d_rev[To]>d_rev[From]+cost:
            d_rev[To]=d_rev[From]+cost
            update = True
    if not update:
        break

d_ = [x for x in d]
d_rev_ = [x for x in d_rev]

for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge_rev[j]
        if d_rev[From] != inf and d_rev[To]>d_rev[From]+cost:
            d_rev[To]=d_rev[From]+cost
            update = True
    if not update:
        break

loop = False
for i in range(V):
    if d[i] != 0 and d_rev[i] != 0:
        loop = (d[i]+d_rev[i] != d_[i]+d_rev_[i]) or loop

if loop:
    print(-1)

else:
    ans = -d[-1]
    print(max(0,ans))