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: Accepted

Solution code:
n,m,p=map(int,input().split())
data=[list(map(int,input().split())) for i in range(m)]
inf=float("inf")
dist=[-inf]*(n+1)
dist[1]=0
for i in range(n-1):
    for a,b,c in data:
        if dist[a]!=-inf:
            dist[b]=max(dist[b],dist[a]+c-p)
lst=[]
for a,b,c in data:
    if dist[b]<dist[a]+c-p:
        lst.append(b)

tag=[[] for i in range(n+1)]
for a,b,c in data:
    tag[a].append(b)
flag=[0]*(n+1)
for u in lst:
    if flag[u]==0:
        flag[u]=1
        que=[u]
        while que:
            h=que.pop()
            for v in tag[h]:
                if flag[v]==0:
                    que.append(v)
                    flag[v]=1
if flag[n]==1:
    print(-1)
else:
    print(max(0,dist[n]))

Submission status: Accepted

Solution code:
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];d=[0]*2+[9e99]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[d[a]-c+p,-9e99][i>n]
 if i==n:x=d[n]
print([max(-x,0),-1][d[n]!=x])

Submission status: Accepted

Solution code:
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];I=float('inf');d=[0]*2+[I]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[d[a]-c+p,-I][i>n]
 if i==n:x=d[n]
print([max(-x,0),-1][d[n]!=x])

Submission status: Accepted

Solution code:
(n,m,p),*l=[list(map(int,s.split()))for s in open(0)];I=float('inf');d=[0]*2+[I]*n
for i in range(n*2):
 for a,b,c in l:
  if d[b]>d[a]-c+p:d[b]=[min(d[b],d[a]-c+p),-I][i>n]
 if i==n:x=d[n]
print([max(-d[n],0),-1][d[n]!=x])

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
I=float('inf')
d=[0]*2+[I]*n
for i in range(n-1):
  for a,b,c in l:
    d[b]=min(d[b],d[a]-c+p)
x=d[n]
for i in range(n):
  for a,b,c in l:
    if d[b]>d[a]-c+p:d[b]=-I
print([max(-d[n],0),-1][d[n]!=x])

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
distance=[float('inf')]*n
distance[0]=0
for i in range(n-1):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=distance[l[j][0]-1]-l[j][2]+p
x=distance[n-1]
for i in range(n):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=-float('inf')
if distance[n-1]!=x:
  print(-1)
else:
  print(max(-distance[n-1],0))

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
distance=[float('inf')]*n
distance[0]=0
for i in range(n-1):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=distance[l[j][0]-1]-l[j][2]+p
x=distance[n-1]
for i in range(n):
  for j in range(m):
    if distance[l[j][1]-1]>distance[l[j][0]-1]-l[j][2]+p:
      distance[l[j][1]-1]=-float('inf')
if distance[n-1]!=x:
  print(-1)
elif x>0:
  print(0)
else:
  print(max(-distance[n-1],0))

Submission status: Accepted

Solution code:
INF = float("inf")

def bellman_ford(edges, n, s):
    d = [0] + [INF] * (n-1)
    for i in range(n):
        for f, t, c in edges:
            if d[f] == INF: continue
            if d[t] > d[f] + c:
                if i == n-1: d[t] = -INF
                else: d[t] = d[f] + c
    for i in range(n):
        for f, t, c in edges:
            if d[f] == INF: continue
            d[t] = min(d[t], d[f] + c)
    return d

n, m, p = map(int, input().split())
es = [None] * m
for i in range(m):
    f, t, c = map(int, input().split())
    es[i] = (f-1, t-1, -(c-p))

d = bellman_ford(es, n, 0)
print(-1 if d[n-1] == -INF else max(0, -d[n-1]))

Submission status: Accepted

Solution code:
from collections import deque
n,m,p=map(int,input().split())
edges=[None for i in range(m)]
natural=[[] for i in range(n)]
reverse=[[] for i in range(n)]
for i in range(m):
  a,b,c=map(int,input().split())
  a-=1;b-=1;c-=p
  natural[a].append(b)
  reverse[b].append(a)
  edges[i]=(a,b,-c)
from0=set([0])
fromG=set([n-1])
visited=[False]*n
visited[0]=True
queue=deque([0])
while queue:
  v=queue.popleft()
  for i in natural[v]:
    if visited[i]:continue
    visited[i]=True
    from0.add(i)
    queue.append(i)
for i in range(n):
  visited[i]=False
visited[-1]=True
queue.append(n-1)
while queue:
  v=queue.popleft()
  for i in reverse[v]:
    if visited[i]:continue
    visited[i]=True
    fromG.add(i)
    queue.append(i)
points=from0&fromG
use=[]
for i in edges:
  if i[0] in points and i[1] in points:
    use.append(i)
def BellmanFord(edges,num_v,source):
  #グラフの初期化
  inf=10**15
  global dist
  dist=[inf for i in range(num_v)]
  dist[source]=0
  Ncycle=False
  #辺の緩和
  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: return False
  
  return dist[-1]
flag=0
for i in use:
  if i[2]!=0:
    flag=1
    break
if flag==0:print(0);exit()
if BellmanFord(use,n,0)==False:print(-1)
else:
  print(max(0,-BellmanFord(use,n,0)))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#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():
    n = II()
    d = defaultdict(int)
    for _ in range(n):
        s = S()
        s.sort()
        d[tuple(s)] += 1
    ans = 0
    for i in d.values():
        ans += i * (i - 1) // 2
    print(ans)
    return

# D
# 解説AC
# 後方から見ていくのはわかったけど。。。
# i日前に選べるバイトの中から一番報酬が大きいを選んでいく
def D():
    n, m = LI()
    q = []
    d = defaultdict(list)
    ans = 0
    for _ in range(n):
        a, b = LI()
        d[a].append(b)
    for i in range(m):
        for di in d[i+1]:
            heappush(q, -di)
        if q:
            ans -= heappop(q)
    print(ans)
    return

#E
def E():
    n,m,p = LI()
    dag = [-inf] * n
    edg = LIR_(m)
    dag[0] = 0
    for i in range(n):
        for a, b, c in edg:
            c += 1
            c -= p
            if dag[a] + c > dag[b]:
                dag[b] = dag[a] + c
    ans = dag[n - 1]
    for i in range(n):
        for a, b, c in edg:
            c += 1
            c -= p
            if dag[a] + c > dag[b]:
                dag[b] = inf
    if ans != dag[n - 1]:
        print(-1)
    else:
        print(max(ans, 0))

    return

#F
def F():
    return

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

Submission status: Accepted

Solution code:
#負閉路あり最短経路(逆符号最長)
#aoj,grl1b
import sys
n,m,p = map(int, input().split( ))
E = [[] for _ in range(n)]
inf = 10**12
for _ in range(m):
    a,b,c = map(int, input().split( ))
    E[a-1].append([b-1,p-c])###


D = [inf for _ in range(n)]
D[0] = 0
for _ in range(n):
    for ve in range(n):
        for ed in E[ve]:
            D[ed[0]] = min(D[ed[0]], D[ve] + ed[1])
#上終わってから更新あったら負閉路
#print(*D)
for _ in range(n+10):
    for ve in range(n):
        for ed in E[ve]:
            if D[ed[0]] > D[ve] + ed[1] and D[ed[0]]<inf//10:##後半の条件は始点から到達できる、の意味
                #print(D[ed[0]], D[ve], ed[1])
                D[ed[0]] = -inf

"""
for i in range(n):
    if E[i]:
        for ed in E[i]:
            if D[i] + ed[1] < D[ed[0]] and D[ed[0]]<inf//10:
                print(-1)
                sys.exit()
"""
#print(*D)
if D[n-1]>-inf//10:
    print(max(0,-D[n-1]))
else:
    print(-1)

Submission status: Accepted

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


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

el = []
for _ in range(m):
    a,b,c = map(int,input().split())
    el.append((a-1,b-1,c-p))
cost = [-float("inf") for _ in range(n)]
cost[0] = 0
for i in range(2*n):
    for j in range(m):
        e = el[j]
        if cost[e[1]] < cost[e[0]] + e[2]:
            cost[e[1]] = cost[e[0]] + e[2]
            if i >= n:
                cost[e[1]] = float("inf")
    if i == n-1:
        ans = cost[-1]
        
              
if ans != cost[-1]:
    print(-1)
else:
    print(max(ans, 0))

Submission status: Accepted

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

def BFS(n, E, i0=0):
    Q = deque([i0])
    D = [-1] * n
    D[i0] = 0
    while Q:
        x = Q.popleft()
        for c, d in E[x]:
            if D[c] == -1:
                D[c] = D[x] + 1
                Q.append(c)
    return D

def bellman_ford_chk(n, E, s=0):
    D = [0] * n
    for k in range(n):
        for i in range(n):
            for j, c in E[i]:
                if D[j] > D[i] + c:
                    D[j] = D[i] + c
                    if k == n-1: return 1
    return 0
def bellman_ford_calc(n, E, s=0):
    D = [1<<100] * n
    D[s] = 0
    f = 1
    while f:
        f = 0
        for i in range(n):
            for j, c in E[i]:
                if D[i] < 1<<100 and D[j] > D[i] + c:
                    D[j] = D[i] + c
                    f = 1
    return D
D1 = BFS(N, E1, 0)
D2 = BFS(N, E2, N-1)
L = [i for i in range(N) if D1[i] >= 0 and D2[i] >= 0]

NN = len(L)
LL = [-1] * N
for i in range(NN):
    LL[L[i]] = i

E3 = [[(LL[a], c) for a, c in E1[i] if LL[a] >= 0] for i in range(N) if LL[i] >= 0]
if bellman_ford_chk(NN, E3, 0):
    print(-1)
else:
    print(max(-bellman_ford_calc(NN, E3, 0)[-1], 0))

Submission status: Accepted

Solution code:
N,M,P=map(int,input().split())
ABC=[list(map(int,input().split())) for i in range(M)]
c=[[] for i in range(N)]
v=[0]*N
for a,b,_ in ABC:
    c[a-1].append(b-1)
q=[0]
while q:
    p=q.pop()
    if v[p]==0:
        v[p]=1
        for n in c[p]:
            if n!=p:
                q.append(n)
inf=10**20
f=lambda i,j,w: [i-1,j-1,P-w]
edge=[f(i,j,w) for i,j,w in ABC if v[i-1]]
def bf(N,s):
    d=[inf]*N
    d[s]=0
    prev=[-1]*N
    for i in range(N-1):
        f=0
        for i,j,w in edge:
            if d[j]>d[i]+w:
                d[j]=d[i]+w
                prev[j]=i
                f=1
        if f==0:
            break
    while True:
        f=0
        for i,j,w in edge:
            if d[j]>d[i]+w and (d[j]!=-inf or d[i]!=-inf):
                d[i]=d[j]=-inf
                f=1
        if f==0:
            break
    return d
d=bf(N,0)
print(max(0,-d[-1]) if d[-1]>-inf else -1)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 18
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, m, p = LI()
G = [[] for _ in range(n)]
for i in range(m):
    a, b, c = LI()
    G[a - 1] += [(b - 1, c - p)]


def bellman_ford(G, start=0):
    n = len(G)
    costs = [-INF] * n
    costs[0] = 0
    v_nows = set([start])
    for _ in range(n):
        v_changeds = set()
        for u in v_nows:
            for v, c in G[u]:
                if costs[u] + c > costs[v]:
                    costs[v] = costs[u] + c
                    v_changeds.add(v)
        v_nows = v_changeds
    if not v_changeds:
        return costs[n - 1]

    for i in v_nows:
        costs[i] = -INF
    que = deque(v_nows)
    while que:
        u = que.popleft()
        for v, cost in G[u]:
            if costs[v] != -INF:
                costs[v] = -INF
                que += [v]
    return costs[n - 1]


cost = bellman_ford(G, 0)
if cost == -INF:
    print(-1)
else:
    print(max(0, cost))

Submission status: Accepted

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

adj = [list() for _ in range(N)]
inv = [list() for _ in range(N)]
edges = []

for _ in range(M):
    a,b,c = map(int,input().split())
    inv[b-1].append(a-1)
    adj[a-1].append(b-1)
    edges.append((a-1,b-1,P-c))

stack = [N-1]
reachable1 = {N-1}
while stack:
    v = stack.pop()
    for u in inv[v]:
        if u not in reachable1:
            stack.append(u)
            reachable1.add(u)

stack = [0]
reachable2 = {0}
while stack:
    v = stack.pop()
    for u in adj[v]:
        if u not in reachable2:
            stack.append(u)
            reachable2.add(u)

reachable = reachable1 & reachable2
edges = [(a,b,w) for a,b,w in edges if a in reachable and b in reachable]

dist = [float('inf')]*N
dist[0] = 0

for i in range(len(reachable)-1):
    for a,b,w in edges:
        dist[b] = min(dist[a]+w, dist[b])

# negative cycle
for a,b,w in edges:
    if dist[b] > dist[a] + w:
        print(-1)
        break
else:
    print(max(0,-dist[-1]))

Submission status: Accepted

Solution code:
#####コピペ
def BellmanFord(edges, num_v, source):
    # グラフの初期化
    inf = float("inf")
    dist = [-inf for i in range(num_v)]
    dist[source - 1] = 0

    # 辺の緩和
    buf = 0
    for i in range(num_v * 2):
        for edge in edges:
            if dist[edge[1] - 1] < dist[edge[0] - 1] + edge[2]:
                dist[edge[1] - 1] = dist[edge[0] - 1] + edge[2]
                if i >= num_v:
                    dist[edge[1] - 1] = inf
        if i == num_v - 1:
            buf = dist[-1]
    if dist[-1] != buf or dist[-1] == -inf:
        return -1
    return max(dist[-1], 0)
##########################################################################
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = []

N, M, P = LI()
cou = int(0)
maxC = 10000
d = [[float("inf") for i in range(N)] for i in range(N)]
#d[u][v] : 辺uvのコスト(存在しないときはinf)
V = []*M
for i in range(M):
    a, b, c = list(map(int,input().split()))
    V.append((a,b,c-P))
print(BellmanFord(V, N, 1))

#print(ans)

Submission status: Accepted

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#ライブラリインポート
from collections import defaultdict
import queue
import copy

INF = float("inf")

def getlist():
	return list(map(int, input().split()))

def Bellman_Ford(N, E, G, dist):
	for i in range(N):
		for a, b, w in G:
			if dist[b] > dist[a] + w:
				dist[b] = dist[a] + w

class Graph(object):
    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, a, b):
        self.graph[a].append(b)

    def get_nodes(self):
        return self.graph.keys()

class BFS(object):
	def __init__(self, graph, s, N):
		self.g = graph.graph
		self.Q = queue.Queue()
		self.Q.put(s)
		self.dist = [INF] * N
		self.dist[s] = 0
		self.visit = ["No"] * N
		self.visit[s] = "Yes"
		while not self.Q.empty():
			v = self.Q.get()
			for i in self.g[v]:
				if self.visit[i] == "No":
					self.dist[i] = self.dist[v] + 1
					self.Q.put(i)
					self.visit[i] = "Yes"

#処理内容
def main():
	N, M, P = getlist()
	dist = [INF] * N
	dist[0] = 0
	G = []
	D = Graph()
	Drev = Graph()
	for i in range(M):
		a, b, w = getlist()
		G.append([a - 1, b - 1, P - w])
		D.add_edge(a - 1, b - 1)
		Drev.add_edge(b - 1, a - 1)
	
	#BFS 0→N-1の経路判定
	BF = BFS(D, 0, N)
	BFrev = BFS(Drev, N - 1, N)
	check1 = BF.visit
	check2 = BFrev.visit
	judge = ["No"] * N
	for i in range(N):
		if check1[i] == "Yes" and check2[i] == "Yes":
			judge[i] = "Yes"

	#NM回、2NM回処理
	Bellman_Ford(N, M, G, dist)
	d1 = copy.copy(dist)
	Bellman_Ford(N, M, G, dist)
	d2 = dist

	#判定、出力

	judge_ans = "No"
	for i in range(N):
		if judge[i] == "Yes" and d1[i] != d2[i]:
			judge_ans = "Yes"
			break
	if judge_ans == "Yes":
		print(-1)
	else:
		print(max(-dist[-1] , 0))

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
#ABC137-D
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(N)
Visit[N]=1
while q:
	fro=q.popleft()
	for to in rev_al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)
			
Visit1=Visit

#スタートからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(1)
Visit[1]=1
while q:
	fro=q.popleft()
	for to in al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") ]*(N+1)	#頂点１からの距離 1-indexed
D[1]=0

#Bellman-Ford
for i in range(new_N):
	for a,b,c in fedge:
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque

N,M,P=map(int, sys.stdin.readline().split())

al=[ [] for i in range(N+1) ]		#隣接リスト
rev_al=[ [] for i in range(N+1) ]	#reverse隣接リスト
#辺のリスト
edge=[]

for i in range(M):
	a,b,c=map(int, sys.stdin.readline().split())
	al[a].append(b)
	rev_al[b].append(a)
	edge.append((a,b,c-P))


#ゴールからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(N)
Visit[N]=1
while q:
	fro=q.popleft()
	for to in rev_al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)
			
Visit1=Visit

#スタートからBFS
#訪問した頂点
Visit=[ 0 for _ in range(N+1) ]
q=deque()
q.append(1)
Visit[1]=1
while q:
	fro=q.popleft()
	for to in al[fro]:
		if Visit[to]==0:
			Visit[to]=1
			q.append(to)

Visit2=Visit

#1からもNからも到達可能な頂点の集合
V=[]
for v1,v2 in zip(Visit1,Visit2):
	V.append(v1&v2)

new_N=sum(V)

fedge=[]	#必要な要素だけをフィルターした辺集合
for a,b,c in edge:
	if V[a]==1 and V[b]==1:
		fedge.append((a,b,c))


D=[ float("-inf") ]*(N+1)	#頂点１からの距離 1-indexed
D[1]=0

#ベルマンフォード
for i in range(new_N):
	for a,b,c in fedge:
		if D[a]==float("-inf"): continue
		alt=D[a]+c
		if D[b]<alt:
			D[b]=alt
			if i==new_N-1:
				print -1
				quit()

print max(0,D[N])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)

ii = lambda: int(input())
miis = lambda: map(int, input().split())
lmiis = lambda: list(miis())

def reachable_nodeset(start, inc):
    reachable = set()
    reachable.add(start)
    nodes = [start]

    while nodes:
        n = nodes.pop()
        for i in inc[n]:
            if i not in reachable:
                nodes.append(i)
                reachable.add(i)

    return reachable

def bellmanford(num, start, goal, edges):
    cost = [float('inf')] * num
    cost[start] = 0

    for _ in range(num):
        updated = False
        for a, b, c in edges:
            if cost[b] > cost[a] + c:
                cost[b] = cost[a] + c
                updated = True
        if not updated: break
    else:
        return -1

    return max(0, -cost[goal])

def solve():
    N, M, P = miis()
    to = [[] for _ in range(N)]
    ot = [[] for _ in range(N)]
    edges = []

    for _ in range(M):
        a, b, c = miis()
        a -= 1
        b -= 1
        c = -(c - P)

        to[a].append(b)
        ot[b].append(a)
        edges.append((a,b,c))

    reachableFromZero = reachable_nodeset(0, to)
    reachableToN = reachable_nodeset(N-1, ot)
    ok = reachableFromZero.intersection(reachableToN)

    edges = tuple((a,b,c) for a, b, c in edges if a in ok and b in ok)

    print(bellmanford(N, 0, N-1, edges))

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N,M,P = map(int,readline().split())
ABC = np.array(read().split(),np.int64)

A = ABC[::3]
B = ABC[1::3]
C = ABC[2::3]

C = P-C

# bellman fordでAからBへの最短距離を求める

INF = 10**18
dist = np.full(N+1,INF,np.int64)
dist[1] = 0
for T in range(N+N+10):
    x = dist[A] + C
    update = (dist[B] > x) & (x < INF//2)
    b = B[update]; x = x[update]
    if T > N:
        dist[b] = -INF
    else:
        ind = x.argsort(); x = x[ind][::-1]; b=b[ind][::-1]
        dist[b] = x

answer = -dist[N]
if answer < 0:
    answer = 0
elif answer == INF:
    answer = -1
print(answer)

Submission status: Accepted

Solution code:
n,m,p=map(int,input().split())
A=[]
for i in range(m):
    a,b,c=map(int,input().split())
    A.append((a,b,c-p))

def BellmanFord(edges,num_v,source):
    #グラフの初期化
    inf=float("inf")
    dist=[-inf for i in range(num_v)]
    dist[source-1]=0
  
    #辺の緩和
    buf=0
    for i in range(num_v*2):
        for edge in edges:
            if dist[edge[1]-1] < dist[edge[0]-1] + edge[2]:
                dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
                if i>=num_v:
                    dist[edge[1]-1] =inf
        if i==num_v-1:
            buf=dist[-1]
    if dist[-1]!=buf or dist[-1]==-inf:
        return -1
    return max(dist[-1],0)

x=BellmanFord(A,n,1)
print(x)

Submission status: Accepted

Solution code:
"""解説を見てから解いたコード"""
N, M, P = map(int, input().split())
edges = []
for _ in range(M):
    a, b, c = map(int, input().split())
    edges.append((a, b, c-P))

INF = float('inf')

coin_map = [-INF] * (N+1)
coin_map[1] = 0

for i in range(2*N):
    for a, b, c in edges:
        if coin_map[b] < coin_map[a] + c:
            coin_map[b] = coin_map[a] + c
            if i >= N:
                coin_map[b] = INF

    if i == N - 1:
        ans = coin_map[N]

if ans != coin_map[N]:
    print(-1)
else:
    print(max(0, coin_map[N]))

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

def BELLMANFORD(point,n,d,p):
    cost       = [1e18]*(n+1)  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for nownode,nextnode,c in d:
            if cost[nextnode]>cost[nownode]+c+p:
                cost[nextnode]=cost[nownode]+c+p

    negative=[0]*(n+1)                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for nownode,nextnode,c in d:
            if negative[nownode]:
                negative[nextnode]=1
            if cost[nextnode]>cost[nownode]+c+p and cost[nextnode]<1e17 and cost[nownode]+c+p<1e17:
                cost[nextnode]=cost[nownode]+c+p
                #print(cost[nextnode],cost[nownode]+c+p)
                negative[nownode]=1
    #print(cost)
    #print(negative)
    return cost,negative

def main():    
    n,m,p=map(int,input().split())
    
    d=[]
    for i in [0]*m:
        a,b,c=map(int,input().split())
        d.append((a,b,-c))
    
    x,y=(BELLMANFORD(1,n,d,p))
    
    if y[n]==1:
        print(-1)
    else:
        print(max(-x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

def BELLMANFORD(point,n,d,p):
    cost       = [-float("inf")]*(n+1)  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for nownode,nextnode,c in d:
            if cost[nextnode]<cost[nownode]+c-p:
                cost[nextnode]=cost[nownode]+c-p

    negative=[0]*(n+1)                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for nownode,nextnode,c in d:
            if negative[nownode]==1:
                negative[nextnode]=1
            if cost[nextnode]<cost[nownode]+c-p:
                cost[nextnode]=cost[nownode]+c-p
                negative[nownode]=1
 
    return cost,negative

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

    d=[tuple(map(int,input().split()))for i in [0]*m]
    
    x,y=(BELLMANFORD(1,n,d,p))
    
    if y[n]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

def BELLMANFORD(point,n,d,p):
    cost       = [-float("inf")]*(n+1)  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p

    negative=[0]*(n+1)                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for now,lis in d.items():
            for nex,c in lis:
                if negative[now]==1:
                    negative[nex]=1
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    negative[now]=1
 
    return cost,negative

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

    d={}
    for s in range(m):
        a,b,c=map(int,input().split())
        if a in d:
            d[a].append((b,c))
        else:
            d[a]=[(b,c)]
    
    x,y=(BELLMANFORD(1,n,d,p))
    
    if y[n]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# ABC 137 E    E. Coins Respawn

import sys
input=sys.stdin.readline  #危険！基本オフにしろ！

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

d={}
for s in range(m):
    a,b,c=map(int,input().split())
    if a in d:
        d[a].append((b,c))
    else:
        d[a]=[(b,c)]

#print(d)


def BELLMANFORD(point,d,p):
    cost       = [-float("inf")]*(n+1)  #infじゃないと閉路検出がうまくいかない
    cost[point]= 0
    for i in range(n-1):                                  #経路の長さは最大n-1であるため
        for now,lis in d.items():
            for nex,c in lis:
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p

    negative=[0]*(n+1)                                        #負閉路の長さは最大nであるため
    
    for i in range(n):                  #閉路判定 negativeの1は閉路に入っている部分を表す
        for now,lis in d.items():
            for nex,c in lis:
                if negative[now]==1:
                    negative[nex]=1
                if cost[nex]<cost[now]+c-p:
                    cost[nex]=cost[now]+c-p
                    negative[now]=1
 
    return cost,negative

def main():
    x,y=(BELLMANFORD(1,d,p))
    
    if y[n]==1:
        print(-1)
    else:
        print(max(x[n],0))

    
if __name__ == '__main__':
    main()