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 sys
input = sys.stdin.readline
def bellman_ford(s, n, G, st):
    d = [float('inf')]*n
    d[s] = 0
    for i in range(n):
        update = False
        for x, y, z in G:
            if not y in st:
                continue
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
        if not update:
            break
        if i == n - 1:
            return None
    return d

def main():
    n, m, p = map(int, input().split())
    G = []
    U = [[] for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        G.append([a-1, b-1, -c+p])
        U[b-1].append(a-1)
    st = set()
    st.add(n-1)
    q = [n-1]
    while len(q) > 0:
        t = q.pop(-1)
        for v in U[t]:
            if not v in st:
                q.append(v)
                st.add(v)
    ans = bellman_ford(0, n, G, st)
    if ans is None:
        print(-1)
    else:
        print(max(0, -ans[n-1]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def bellman_ford(s, n, G, st):
    d = [float('inf')]*n
    d[s] = 0
    for i in range(n):
        update = False
        for x, y, z in G:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                if y in st:
                    update = True
        if not update:
            break
        if i == n - 1:
            return None
    return d

def main():
    n, m, p = map(int, input().split())
    G = []
    U = [[] for _ in range(n)]
    for _ in range(m):
        a, b, c = map(int, input().split())
        G.append([a-1, b-1, -c+p])
        U[b-1].append(a-1)
    st = set()
    st.add(n-1)
    q = [n-1]
    while len(q) > 0:
        t = q.pop(-1)
        for v in U[t]:
            if not v in st:
                q.append(v)
                st.add(v)
    ans = bellman_ford(0, n, G, st)
    if ans is None:
        print(-1)
    else:
        print(max(0, -ans[n-1]))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# Coins Respawn
import sys
sys.setrecursionlimit(10**7)
from collections import deque
N, M, P = map(int, input().split())
graph = []
d = deque()

# グラフの整形

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

for _ in range(M):
    a, b, c = map(int, input().split())
    from_1[a].append(b)
    from_N[b].append(a)
    d.append((a, b, P-c))


accessible_1 = [False for i in range(N+1)]
accessible_N = [False for i in range(N+1)]


def dfs_1(s):
    accessible_1[s] = True
    for node in from_1[s]:
        if accessible_1[node] == False:
            dfs_1(node)


def dfs_N(s):
    accessible_N[s] = True
    for node in from_N[s]:
        if accessible_N[node] == False:
            dfs_N(node)


dfs_1(1)
dfs_N(N)

isok = [False for i in range(N+1)]
for i in range(N+1):
    if accessible_1[i] and accessible_N[i]:
        isok[i] = True


while d:
    p, q, weight = d.popleft()
    if isok[p] and isok[q]:
        graph.append((p, q, weight))

# ベルマンフォード


def bellman_ford(s,n):
    dist = [10**20 for i in range(n+1)]
    dist[s] = 0
    for i in range(1, n+1):
        flag = False
        for some in graph:
            a, b, d = some[0], some[1], some[2]
            newlen = dist[a]+d
            if newlen < dist[b]:
                flag = True
                dist[b] = newlen
        if not flag:
            break
        if i == n:
            return False
    return dist

K=bellman_ford(1,N)
if K==False:
     print(-1)
else:
    print(max(0,-K[N]))

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
from collections import deque,defaultdict
edge1 = [[] for _ in range(N)]
edge2 = [[] for _ in range(N)]
for i in range(M):
    a,b,c= map(int, input().split())
    edge1[a-1].append([b-1,P-c])
    edge2[b-1].append([a-1,P-c])
edges1 = set()
d = deque([0])
visited1 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge1[v]:
        if visited1[(w,v,u)] == False:
            visited1[(w,v,u)] = True
            edges1.add((w,v,u))
            d.append(u)
edges2 = set()
d = deque([N-1])
visited2 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge2[v]:
        if visited2[(w,u,v)] == False:
            visited2[(w,u,v)] = True
            edges2.add((w,u,v))
            d.append(u)
new_edge = list(edges1&edges2)
d = [10**10]*N
d[0] = 0
n = 0
while True:
    n += 1
    update = False
    for w,v,u in new_edge:
        if d[u]>d[v]+w:
            d[u] = d[v]+w
            update = True
    if update == False:
        break
    if n==N and update==True:
        print(-1)
        exit()
print(max(0,-d[-1]))

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
from collections import deque,defaultdict
edge1 = [[] for _ in range(N)]
edge2 = [[] for _ in range(N)]
for i in range(M):
    a,b,c= map(int, input().split())
    edge1[a-1].append([b-1,P-c])
    edge2[b-1].append([a-1,P-c])
edges1 = []
d = deque([0])
visited1 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge1[v]:
        if visited1[(w,v,u)] == False:
            visited1[(w,v,u)] = True
            edges1.append([w,v,u])
            d.append(u)
edges2 = []
d = deque([N-1])
visited2 = defaultdict(lambda: False)
while len(d):
    v = d.popleft()
    for u,w in edge2[v]:
        if visited2[(w,u,v)] == False:
            visited2[(w,u,v)] = True
            edges2.append([w,u,v])
            d.append(u)
new_edge = []
for e in edges1:
    if e in edges2:
        new_edge.append(e)
d = [10**10]*N
d[0] = 0
n = 0
while True:
    n += 1
    update = False
    for w,v,u in new_edge:
        if d[u]>d[v]+w:
            d[u] = d[v]+w
            update = True
    if update == False:
        break
    if n==N and update==True:
        print(-1)
        exit()
print(max(0,-d[-1]))

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
from collections import deque
edge1 = [[] for _ in range(N)]
edge2 = [[] for _ in range(N)]
for i in range(M):
    a,b,c= map(int, input().split())
    edge1[a-1].append([b-1,P-c])
    edge2[b-1].append([a-1,P-c])
edges1 = []
d = deque([0])
visited1 = set()
while len(d):
    v = d.popleft()
    for u,w in edge1[v]:
        if (w,v,u) not in visited1:
            visited1.add((w,v,u))
            edges1.append([w,v,u])
            d.append(u)
edges2 = []
d = deque([N-1])
visited2 = set()
while len(d):
    v = d.popleft()
    for u,w in edge2[v]:
        if (w,u,v) not in visited2:
            visited2.add((w,u,v))
            edges2.append([w,u,v])
            d.append(u)
new_edge = []
for e in edges1:
    if e in edges2:
        new_edge.append(e)
d = [10**10]*N
d[0] = 0
n = 0
while True:
    n += 1
    update = False
    for w,v,u in new_edge:
        if d[u]>d[v]+w:
            d[u] = d[v]+w
            update = True
    if update == False:
        break
    if n==N and update==True:
        print(-1)
        exit()
print(max(0,-d[-1]))

Submission status: Time Limit Exceeded

Solution code:
N, M, P = map(int, input().split())
from collections import deque
edge1 = [[] for _ in range(N)]
edge2 = [[] for _ in range(N)]
for i in range(M):
    a,b,c= map(int, input().split())
    edge1[a-1].append([b-1,P-c])
    edge2[b-1].append([a-1,P-c])
edges1 = []
d = deque([0])
visited1 = {}
while len(d):
    v = d.popleft()
    for u,w in edge1[v]:
        if (w,v,u) not in visited1:
            visited1[(w,v,u)]=True
            edges1.append([w,v,u])
            d.append(u)
edges2 = []
d = deque([N-1])
visited2 = {}
while len(d):
    v = d.popleft()
    for u,w in edge2[v]:
        if (w,u,v) not in visited2:
            visited2[(w,u,v)]=True
            edges2.append([w,u,v])
            d.append(u)
new_edge = []
for e in edges1:
    if e in edges2:
        new_edge.append(e)
d = [float('inf')]*N
d[0] = 0
n = 0
while True:
    n += 1
    update = False
    for w,v,u in new_edge:
        if d[u]>d[v]+w:
            d[u] = d[v]+w
            update = True
    if update == False:
        break
    if n==N and update==True:
        print(-1)
        exit()
print(max(0,-d[-1]))

Submission status: Time Limit Exceeded

Solution code:
"""負辺ありの有向グラフの最短経路問題、ベルマンフォード法"""
import sys
sys.setrecursionlimit(10**6)

n,m,p = map(int, input().split())

INF = 1001001001

to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    """1から到達できる頂点の列挙"""
    if reachableFrom1[v]: return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    """Nに到達できる頂点の列挙"""
    if reachableToN[v]: return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

edges = []
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1; b -= 1
    c -= p
    c = -c
    edges.append((a,b,c))
    to[a].append(b) # 到達可能性を判定するための変数
    rto[b].append(a) # nに辿り着けるかを判定するための変数
    
dfs(0)
rdfs(n-1)
for i in range(n):
    ok[i] = reachableFrom1[i] & reachableToN[i] # okになっている頂点だけを考える
# ベルマンフォード
def main():
    global edges, ok
    d = [INF for _ in range(n)]
    d[0] = 0
    upd = True
    step = 0 # 負閉路検出用。更新回数がnステップを超えたら負閉路あり
    while upd:
        upd = False
        for i in range(m):
            a,b,c = edges[i]
            if not ok[a]: continue
            if not ok[b]: continue
            newD = d[a]+c
            if newD < d[b]:
                upd = True
                d[b] = newD
        step += 1
        if step > n:
            print(-1)
            return
    ans = -d[n-1]
    ans = max(ans,0)
    print(ans)
    return
    
main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
# from math import gcd
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n,m,p=map(int,input().split())
abc=[list(map(int,input().split())) for i in range(m)]

edge=defaultdict(list)
coin=defaultdict(int)
for i in range(m):
    a,b,c=abc[i]
    edge[a].append(b)
    coin[(a,b)]=max(coin[(a,b)],c)
# print(edge,coin)

itta=[-float('inf')]*(n+1)
d=deque([[1,0,itta[:]]])
infdic=defaultdict(int)
while d:
    now,c,itta=d.popleft()
    if itta[now]==-float('inf'):
        itta[now]=c
        for i in edge[now]:
            d.append([i,c+coin[(now,i)]-p,itta[:]])
    else:
        if itta[now]<c:
            infdic[now]=float('inf')

# print(infdic)

itta=[0]*(n+1)
d=deque([[1,0,itta[:]]])
ans=0
while d:
    now,c,itta=d.popleft()
    c=max(c,infdic[now])
    if now==n:
        ans=max(ans,c)
    
    if itta[now]==0:
        itta[now]=1
        for i in edge[now]:
            d.append([i,c+coin[(now,i)]-p,itta[:]])

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

Submission status: Time Limit Exceeded

Solution code:
n, m, p = map(int, input().split())
edge = []

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

d = [float("inf") for _ in range(n)]
d[0] = 0

check = [0 for _ in range(n)]

for i in range(n):
    for now, next, weight in edge:
        if d[next] > min(d[now] + weight + p, d[next]):
            d[next] = min(d[now] + weight + p, d[next])
            # n+1回目で更新された場合はループしているのでチェックを入れる
            if i == n-1:
                check[next] = 1
        if i == n-1:
            if check[now]:
                check[next] = 1
        # print(d)

# print(check)
if check[-1]:
    print("-1")
else:
    print(max(-d[-1], 0))

Submission status: Time Limit Exceeded

Solution code:
def main():
    # 入力
    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]

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

    # 前処理用のDFS
    def remove_edge(graph, start):
        q = [start]
        memo = [True for _ in range(n)]
        memo[start] = False
        while q:
            qq = q.pop()
            for i, j in graph[qq]:
                if memo[i]:
                    q.append(i)
                    memo[i] = False
        return {i for i, j in enumerate(memo) if j == True}

    # 前処理
    rmv = remove_edge(g, 0) | remove_edge(g2, n-1)
    for i in rmv:
        g[i] = []
    for i in range(n):
        for j in g[i]:
            if j[0] in rmv:
                g[i].remove(j)

    # ベルマンフォード
    dist = [-10**15 for _ in [0]*n]
    dist[0] = 0

    for k in range(n):
        for p in range(n):
            for i, j in g[p]:
                dist[i] = max(dist[i], dist[p]+j-r)
        if k == n-2:
            d1 = [t for t in dist]
        if k == n-1:
            d2 = [t for t in dist]

    # 1からでもnの間に負の閉路があるときは-1
    if d1 == d2:
        print(max(d1[-1], 0))
    else:
        print(-1)
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(200000)

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

INF = 10**10
# Bellman-Fordをするときは、辺集合を持つ
edges = [] 
# 1から行けない辺やNに到達できない辺を削除するための探索をする用
to = [[] for _ in range(2505)]
rto = [[] for _ in range(2505)]
reachableFrom1 = [False for _ in range(2505)]
reachableToN = [False for _ in range(2505)]
ok = [False for _ in range(2505)]

def dfs(v):
    if reachableFrom1[v]:
        return
    reachableFrom1[v] = True
    for u in to[v]:
        dfs(u)

def rdfs(v):
    if reachableToN[v]:
        return
    reachableToN[v] = True
    for u in rto[v]:
        rdfs(u)

for i in range(M):
    a, b, c = map(int, input().split())
    a -= 1; b -= 1
    c -= P
    c = -c # 最短路にするため符号を逆転
    edges.append([a, b, c])
    to[a].append(b)
    rto[b].append(a)

# 考えるべき頂点だけ洗い出し
dfs(0)
rdfs(N-1)
for i in range(N):
    ok[i] = reachableFrom1[i] & reachableToN[i]

# Bellman-Ford
d = [INF for _ in range(N)]
d[0] = 0
upd = True
step = 0
flag = True
while upd:
    upd = False
    for i in range(M):
        a, b, c = edges[i]
        if not ok[a]:
            continue
        if not ok[b]:
            continue
        newD = d[a]+c
        if newD < d[b]:
            upd = True
            d[b] = newD
    step += 1
    if step > N:
        flag = False
        break
if flag:
    ans = -d[N-1]
    ans = max(ans, 0)
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    inf = 10**17
    #mod = 10**9 + 7

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

    visited = [0]*n
    dq = deque([n-1])
    while dq:
        v = dq.popleft()
        visited[v] = 1
        for nv in adj[v]:
            if visited[nv] == 0:
                dq.append(nv)
    
    def bellmanford(n, s, edge):
        inf = 10**17
        d = [inf] * n
        d[s] = 0
        for i in range(n):
            for a,b,c in edge:
                if d[a] != inf and d[b] > d[a]+c:
                    d[b] = d[a] + c
                    if i == n-1 and visited[b] == 1:
                        return -inf
        return -d[-1]

    res = bellmanford(n,0,edge)
    if res == -inf:
        print(-1)
    elif res < 0:
        print(0)
    else:
        print(res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N,M,P,*L = map(int, open(0).read().split())
INF = 10**9
Els = []
dic = [[] for i in range(N+1)]
rdic = [[] for i in range(N+1)]
for a,b,c in zip(*[iter(L)]*3):
  dic[a].append((b,c-P))
  rdic[b].append((a,c-P))
  Els.append((a,b,-c+P))
ok1 = [False]*(N+1)
ok1[1] = True
q = deque([1])
while q:
  v = q.popleft()
  for p,c in dic[v]:
    if not ok1[p]:
      ok1[p] = True
      q.append(p)

ok2 = [False]*(N+1)
ok2[N] = True
q = deque([N])
while q:
  v = q.popleft()
  for p,c in rdic[v]:
    if not ok2[p]:
      ok2[p] = True
      q.append(p)

ok = [a&b for a,b in zip(ok1,ok2)]

dist = [INF]*(N+1)
dist[1] = 0
cnt = 0
while True:
  end = True
  for a,b,c in Els:
    if ok[a] and ok[b] and dist[a]!=INF and dist[b]>dist[a]+c:
      end = False
      dist[b] = dist[a]+c
  if end:
    print(max(0,-dist[N]))
    break
  cnt += 1
  if cnt>2*M:
    print(-1)
    break

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
input=sys.stdin.readline
N,M,P=map(int,input().split())

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

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

visited=[None]*(N+1)
def check_reachable(u):
  if u==N:
    reachable[u]=True
    return True
  
  visited[u]=True
  cnt=0
  for v in graph[u]:
    if not visited[v]:
      ret=check_reachable(v)
      if ret:        
        cnt+=1
        
  if cnt>0:
    reachable[u]=True
    return True
  else:
    #reachable[u]=False #入れるとエラー
    return False
  
reachable=[False]*(N+1)
for i in range(1,N+1):
  if not reachable[i]:
    visited=[False]*(N+1)
    check_reachable(i)
#print(reachable)

#関係の無い点に入る辺を削除
elist2=[]
for x,y,nc in elist:
  if reachable[y]:
    elist2.append((x,y,nc))
M2=len(elist2)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

res1=find_negative_loop(N+1,M2,elist2)
#print(res1)

if res1:
  print(-1)
else:
  res2=shortest_path(1,N+1,M2,elist2)
  #print(res2)
  print(max(-res2[N],0))

Submission status: Time Limit Exceeded

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

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  update_num=0
  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
        #ad hoc
        update_num+=1
    if not update or update_num==2*n:
      break
      
  return dist

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

res1=shortest_path(1,N+1,M,elist)
#print(res1)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

res2=find_negative_loop(N+1,M,elist)
#print(res2)

answer=-res1[N]
if answer<0:
  print(0)
elif res2:
  print(-1)
else:
  print(answer)

Submission status: Time Limit Exceeded

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

def shortest_path(s,n,w,es):
  #s→iの最短距離
  #s:始点, n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
  dist=[float("inf")]*n
  #d[i]: s→iの最短距離
  dist[s]=0

  while True:
    update=False
    for p,q,r in es:
      # e: 辺iについて [from,to,cost]
      if dist[p]!=float("inf") and dist[q]>dist[p]+r:
        dist[q]=dist[p]+r
        update=True
    if not update:
      break
      
  return dist

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

res1=shortest_path(1,N+1,M,elist1)
#print(res1)

#負の経路の検出
#n:頂点数, w:辺の数, es[i]:[辺の始点,辺の終点,辺のコスト]
def find_negative_loop(n,w,es):
  dist=[float("inf")]*n
  #この始点はどこでもよい
  dist[1]=0
  
  for i in range(n):
    for j in range(w):
      e=es[j]
      if dist[e[1]]>dist[e[0]]+e[2]:
        dist[e[1]]=dist[e[0]]+e[2]
        if i==n-1:
          return True
  return False

#elist2[i]: [辺の始点,辺の終点,辺のコスト]
elist2=[]
for i in range(M):
  x,y,z = elist1[i]
  elist2.append((x,y,-z))
  elist2.append((y,x,-z))
#print(elist2)

res2=find_negative_loop(N+1,2*M,elist2)
#print(res2)

print(max(-res1[N],0))

Submission status: Time Limit Exceeded

Solution code:
import sys


def input():
    return sys.stdin.readline().strip()


def bellman_ford(edges, N, start):
    dist = [float("inf") for _ in range(N)]
    dist[start] = 0
    # 辺の情報を見ることを1ループとすると
    # 1回のループで,最低でも1つの頂点について，スタートからの最短距離が求まる
    # つまり,スタートからの全ての頂点への距離は，
    # スタートを除いた頂点の数である,(N-1)回のループで求まる．
    for i in range(2 * N):
        for fro, to, cost in edges:
            if dist[to] > dist[fro] - cost:
                dist[to] = dist[fro] - cost
                # N回目に頂点の更新があると，負の経路がある
                if i == N - 1:
                    dist[to] = -float("inf")

    return dist


def main():
    N, M, P = map(int, input().split())
    edge = []
    for _ in range(M):
        A, B, C = map(int, input().split())
        edge.append((A - 1, B - 1, C - P))
    dist = bellman_ford(edge, N, 0)

    if dist[-1] == -float("inf"):
        print(-1)
    else:
        if dist[-1] > 0:
            print(0)
        else:
            print(-1 * dist[-1])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


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


def input():
    return sys.stdin.readline().strip()


def bellman_ford(edges, n_nodes, start, goal):
    dist = [float("inf") for _ in range(n_nodes)]
    dist[start] = 0

    for i in range(2 * n_nodes):
        for fro, to, cost in edges:
            if dist[to] > dist[fro] + cost:
                dist[to] = dist[fro] + cost
                if i == n_nodes - 1:
                    dist[to] = -float("inf")

    return -dist[goal]


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, -c + P))

    ans = bellman_ford(edges, N, 0, N - 1)
    if ans == float("inf"):
        print(-1)
    else:
        print(max(ans, 0))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import heapq
import sys
sys.setrecursionlimit(10**9)

# 全頂点からのゴールへの到達可能性を確認
# 頂点1からDFSしてNまできたら、それまでのパス全てについて到達可能に更新
# その後、到達可能な部分のみを新たな辺にして、ベルマンフォード
# 辺の重みは（C - P）
# 負閉路を検出したなら-1
# そうでなければNまでの距離


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

Edge = [[] for _ in range(N)]
for a,b,c in ABC:
    Edge[b-1].append(a-1)


reachable = [False]*N
reachable[N-1] = True

def dfs(v):
    for nv in Edge[v]:
        if reachable[nv]:
            continue
        else:
            reachable[nv] = True
            dfs(nv)
    return 

def BellmanFord(s, N, Edge):
    INF = 10**20
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        isUpdated = False
        for t in range(N):
            if dist[t] == INF:
                continue
            for v,c in Edge[t]:
                if dist[t]+c < dist[v]:
                    dist[v] = dist[t]+c
                    isUpdated = True
        if not isUpdated:
            break
        elif i==N-1:
            return -1
    return dist

                
dfs(N-1)
newEdge = [[] for _ in range(N)]
for a,b,c in ABC:
    if reachable[a-1]:
        newEdge[a-1].append([b-1, P-c])

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import heapq
import sys
sys.setrecursionlimit(10**9)

# 全頂点からのゴールへの到達可能性を確認
# 頂点1からDFSしてNまできたら、それまでのパス全てについて到達可能に更新
# その後、到達可能な部分のみを新たな辺にして、ベルマンフォード
# 辺の重みは（C - P）
# 負閉路を検出したなら-1
# そうでなければNまでの距離


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

Edge = [[] for _ in range(N)]
for a,b,c in ABC:
    Edge[a-1].append([b-1, -c+P])


reachable = [False]*N
reachable[0] = True
reachable[N-1] = True
visited = [False] * N
visited[0] = True

def dfs(v, visited, vlist):
    for nv,_ in Edge[v]:
        if nv == N-1:
            for r in vlist:
                reachable[r] |= True
            vlist = []

        if visited[nv]:
            continue
        else:
            visited[nv] = True
            vlist.append(nv)
            dfs(nv, visited, vlist)
            visited[nv] = False
            vlist.pop()
    return 

def BellmanFord(s, N, Edge):
    INF = 10**20
    dist = [INF] * N
    dist[s] = 0
    for i in range(N):
        isUpdated = False
        for t in range(N):
            if dist[t] == INF:
                continue
            for v,c in Edge[t]:
                if dist[t]+c < dist[v]:
                    dist[v] = dist[t]+c
                    isUpdated = True
        if not isUpdated:
            break
        elif i==N-1:
            return -1
    return dist

                
dfs(0, visited, [])
newEdge = [[] for _ in range(N)]
for a,b,c in ABC:
    if reachable[a-1]:
        newEdge[a-1].append([b-1, P-c])

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline

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

    INF = 10 ** 9
    #入力

    # 入力は1-index
    # 内部で0-indexにして処理
    G = []
    for _ in range(M): #M個の辺の情報を受け取る
        A, B, C = map(int, input().split()) #lからrへ重みsの辺が存在
        G += [[A - 1, B - 1, P - C]] #有向グラフのときはここだけ

    check = [False] * N
    d = [INF] * N #距離を記録

    def shortest_path(s): #S番目の頂点から各頂点への最短距離を求める
        s -= 1
        d[s] = 0
        j = 0
        while j < N - 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]
            j += 1
        
        j = 0
        while j < N:
            for i in range(M):
                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]
                    check[e[1]] = True
                if check[e[0]]:
                    check[e[1]] = True
            j += 1

    shortest_path(1)
    if check[N - 1]:
        print (-1)
    else:
        ans = d[N - 1]
        print (max(0, -ans))
    # print (d)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

edges = [[] for _ in range(N)]
edgesR = [[] for _ in range(N)]
E = []
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    E.append((fr, to, -(c - P)))
    edges[fr].append(to)
    edgesR[to].append(fr)

def dfs(edges, s):
    visited = [False] * N
    st = [s]
    visited[s] = True
    while st:
        for to in edges[st.pop()]:
            if not visited[to]:
                st.append(to)
                visited[to] = True
    return visited

canGo = dfs(edges, 0)
canBack = dfs(edgesR, N - 1)

minDist = [10**18] * N
minDist[0] = 0
for i in range(N + 1):
    for fr, to, c in E:
        d = minDist[fr] + c
        if minDist[to] > d:
            if i == N and canGo[fr] and canBack[to]:
                print('-1')
                exit()
            minDist[to] = d

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