Problem:


Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.



Sample input:
3 3 10
1 2 20
2 3 30
1 3 45


Sample output:
35

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from scipy.sparse import csgraph
input = sys.stdin.readline
dfs = csgraph.depth_first_order
n, m, p = map(int, input().split())
g = np.zeros((n,n))
rev = np.zeros((n,n))
for _ in range(m):
    a, b, c = map(int, input().split())
    g[a-1, b-1] = p - c
    rev[b-1, a-1] = 1
use = np.intersect1d(dfs(g, 0, True, False), dfs(rev, n-1, True, False))
not_use = np.setdiff1d(np.arange(n), use)
g[not_use, :] = g[:, not_use] = 0
try:
    print(max(0, -int(csgraph.bellman_ford(g)[0, n-1])))
except csgraph._shortest_path.NegativeCycleError:
    print(-1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(5001)

n, m, p = map(int, input().split())
edges = []
to = [[] for _ in range(n)]
rto = [[] for _ in range(n)]
reachable_from_1 = [False] * n
reachable_to_n = [False] * n

def main():
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        ai -= 1
        bi -= 1
        ci = -ci + p
        edges.append((ai, bi, ci))
        to[ai].append(bi)
        rto[bi].append(ai)
    dfs(0)
    rdfs(n-1)
    ok = [reachable_from_1[i] and reachable_to_n[i] for i in range(n)]

    d = [float('inf')] * n
    d[0] = 0
    upd = True
    step = 0
    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)

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

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(5001)

n, m, p = map(int, input().split())
edges = []
to = [[] for _ in range(n)]
rto = [[] for _ in range(n)]
reachable_from_1 = [False] * n
reachable_to_n = [False] * n

def main():
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        ai -= 1
        bi -= 1
        ci = -ci + p
        edges.append((ai, bi, ci))
        to[ai].append(bi)
        rto[bi].append(ai)
    dfs(0)
    rdfs(n-1)
    ok = [reachable_from_1[i] and reachable_to_n[i] for i in range(n)]

    print(reachable_from_1, reachable_to_n, ok)
    d = [float('inf')] * n
    d[0] = 0
    upd = True
    step = 0
    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]
    print(d)
    ans = max(ans, 0)
    print(ans)

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

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

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

# グラフ定義
class Edge:
    def __init__(self, f: int, t: int, cost: int):
        self._t = t
        self._cost = cost
        self._f = f

    @property
    def t(self):
        return self._t

    @property
    def f(self):
        return self._f

    @property
    def cost(self):
        return self._cost


INF = 1 << 28


# ここから本実装
def bellman_ford(n: int, edges, s: int):
    dist = [INF for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for e in edges:

            if dist[e.t] > dist[e.f] + e.cost:
                dist[e.t] = dist[e.f] + e.cost
                if i == n - 1:
                    return None

    return dist


def visitable_node(n, g, rg):

    vis = [False] * n

    def dfs(idx):
        vis[idx] = True
        for e in g[idx]:
            if not vis[e]:
                dfs(e)

    dfs(0)

    rvis = [False] * n

    def rdfs(idx):
        rvis[idx] = True
        for e in rg[idx]:
            if not rvis[e]:
                rdfs(e)

    rdfs(n - 1)

    return [vis[i] & rvis[i] for i in range(n)]


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

edges = []
g = [[] for _ in range(n)]
rg = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append(Edge(a, b, -c + p))
    g[a].append(b)
    rg[b].append(a)

visitable = visitable_node(n, g, rg)
updated = [e for e in edges if visitable[e.f] and visitable[e.t]]

dist = bellman_ford(n, edges, 0)

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

Submission status: Runtime Error

Solution code:

# グラフ定義
class Edge:
    def __init__(self, f: int, t: int, cost: int):
        self._t = t
        self._cost = cost
        self._f = f

    @property
    def t(self):
        return self._t

    @property
    def f(self):
        return self._f

    @property
    def cost(self):
        return self._cost


INF = 1 << 28


# ここから本実装
def bellman_ford(n: int, edges, s: int):
    dist = [INF for _ in range(n)]
    dist[s] = 0

    for i in range(n):
        for e in edges:

            if dist[e.t] > dist[e.f] + e.cost:
                dist[e.t] = dist[e.f] + e.cost
                if i == n - 1:
                    return None

    return dist


def visitable_node(n, g, rg):

    vis = [False] * n

    def dfs(idx):
        vis[idx] = True
        for e in g[idx]:
            if not vis[e]:
                dfs(e)

    dfs(0)

    rvis = [False] * n

    def rdfs(idx):
        rvis[idx] = True
        for e in rg[idx]:
            if not rvis[e]:
                rdfs(e)

    rdfs(n - 1)

    return [vis[i] & rvis[i] for i in range(n)]


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

edges = []
g = [[] for _ in range(n)]
rg = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append(Edge(a, b, -c + p))
    g[a].append(b)
    rg[b].append(a)

visitable = visitable_node(n, g, rg)

updated = [e for e in edges if visitable[e.f] and visitable[e.t]]

dist = bellman_ford(n, updated, 0)

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

Submission status: Runtime Error

Solution code:

# グラフ定義
class Edge:
    def __init__(self, f: int, t: int, cost: int):
        self._t = t
        self._cost = cost
        self._f = f

    @property
    def t(self):
        return self._t

    @property
    def f(self):
        return self._f

    @property
    def cost(self):
        return self._cost


INF = 1 << 28


# ここから本実装
def bellman_ford(n: int, edges, s: int):
    m = len(edges)
    dist = [INF for _ in range(n)]
    looped = [False] * n

    dist[s] = 0

    for i in range(2 * n):
        for e in edges:

            if dist[e.t] > dist[e.f] + e.cost:
                dist[e.t] = dist[e.f] + e.cost
                if i >= n - 1:
                    return None

    return dist


def visitable_node(n, g, rg):

    vis = set()
    def dfs(idx):
        vis.add(idx)
        for e in g[idx]:
            if e in vis:
                continue
            dfs(e)

    dfs(0)

    rvis = set()
    def rdfs(idx):
        rvis.add(idx)
        for e in rg[idx]:
            if e in rvis:
                continue
            rdfs(e)

    rdfs(n - 1)

    return vis & rvis


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

edges = []
g = [[] for _ in range(n)]
rg = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    edges.append(Edge(a, b, -c + p))
    g[a].append(b)
    rg[b].append(a)

visitable = visitable_node(n, g, rg)

updated = [e for e in edges if e.f in visitable and e.t in visitable]


dist = bellman_ford(n, updated, 0)

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

Submission status: Runtime Error

Solution code:
from array import array
N,M,P = map(int,input().split())
make_Edge = lambda xs:[int(xs[0])-1,int(xs[1])-1,P-int(xs[2])] 
Edges =[make_Edge(input().split()) for i in range(M)]

def bellman_ford(N,edges):
    #各点の重み
    inf = 10**6
    dist = array('I',[inf]*N)
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e[0]] != inf and dist[e[1]] > dist[e[0]]+e[2]:
                dist[e[1]] = dist[e[0]]+e[2]
                if i==N-1 and e[1] == N-1:
                    return None
    return -dist[N-1]
  
ans = bellman_ford(N,Edges)
if ans is None:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
make_Edge = lambda xs:[int(x[0])-1,int(x[1])-1,P-int(x[2])] 
Edges =[make_Edge(input().split()) for i in range(M)]

def bellman_ford(N,edges):
    #各点の重み
    inf = 10**6
    dist = [inf for i in range(N)]
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e[0]] != inf and dist[e[1]] > dist[e[0]]+e[2]:
                dist[e[1]] = dist[e[0]]+e[2]
                if i==N-1 and e[1] == N-1:
                    return None
    return -dist[N-1]
  
ans = bellman_ford(N,Edges)
if ans is None:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
make_Edge = lambda xs:[int(x[0])-1,int(x[1])-1,P-int(x[2])] 
Edges =[make_Edge(input().split()) for i in range(M)]

def bellman_ford(N,edges):
    #各点の重み
    inf = 10**6
    dist = [inf]*N
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e[0]] != inf and dist[e[1]] > dist[e[0]]+e[2]:
                dist[e[1]] = dist[e[0]]+e[2]
                if i==N-1 and e[1] == N-1:
                    return None
    return -dist[N-1]

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
make_Edge = lambda xs:[int(x[0])-1,int(x[1])-1,P-int(x[2])] 
Edges =[make_Edge(input().split()) for i in range(M)]

def bellman_ford(N,edges):
    #各点の重み
    inf = 10**6
    dist = [inf]*N
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e[0]] != inf and dist[e[1]] > dist[e[0]]+e[2]:
                dist[e[1]] = dist[e[0]]+e[2]
                if i==N-1 and e[1] == N-1:
                    return None
    return -dist[N-1]

ans = bellman_ford(N,Edges)
if ans is None:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
from array import array
N,M,P = map(int,input().split())
make_Edge = lambda xs:[int(x[0])-1,int(x[1])-1,P-int(x[2])] 
Edges =[make_Edge(input().split()) for i in range(M)]

def bellman_ford(N,edges):
    #各点の重み
    inf = 10**6
    dist = array('I',[inf]*N)
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e[0]] != inf and dist[e[1]] > dist[e[0]]+e[2]:
                dist[e[1]] = dist[e[0]]+e[2]
                if i==N-1 and e[1] == N-1:
                    return None
    return -dist[N-1]

ans = bellman_ford(N,Edges)
if ans is None:
    print(-1)
elif ans < 0:
    print(0)
else:
    print(ans)

Submission status: Runtime Error

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

  #辺の緩和
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        if i==num_v-1 and edge[1]==num_v : return -1
  return dist

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

li = BellmanFord(gp,M,1)
if(li==-1):
    print(-1)
else:
    print(max(0,-li[N-1]))

Submission status: Runtime Error

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

  #辺の緩和
  for i in range(num_v):
    for edge in edges:
      if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
        dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
        if i==num_v-1 and edge[1]==num_v : return -1
  return dist

N,M,P = [int(x) for x in input().split()]
gp = []
for _ in range(M):
    A,B,C = [int(x) for x in input().split()]
    gp.append([A,B,min(P-C,0)])

li = BellmanFord(gp,M,1)
if(li==-1):
    print(-1)
else:
    print(-li[N-1])

Submission status: Runtime Error

Solution code:
from collections import namedtuple
#Edge v1,v2,cost
Edge = namedtuple('Edge','v1 v2 score') 
N,M,P = map(int,input().split())
Edges =[]
for i in range(M):
    v1,v2,score = map(int,input().split())
    #インデックスを合わせるために-1,最大化のために-(score-P)
    Edges.append(Edge(v1-1,v2-1,P-score))

def bellman_ford(N,edges):
    #各点の重み
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e.v1] != inf and dist[e.v2] > dist[e.v1]+e.score:
                dist[e.v2] = dist[e.v1] + e.score
                if i==N-1 and e.v2 == N-1:
                    return None
    return -dist[N-1]

ans = bellman_ford(N,Edges)
if ans < 0:
	print(0)
elif ans is None:
	print(-1)
else:
	print(ans)

Submission status: Runtime Error

Solution code:
from collections import namedtuple
#Edge v1,v2,cost
Edge = namedtuple('Edge','v1 v2 score') 
N,M,P = map(int,input().split())
Edges =[]
for i in range(M):
    v1,v2,score = map(int,input().split())
    #インデックスを合わせるために-1,最大化のために-(score-P)
    Edges.append(Edge(v1-1,v2-1,P-score))

def bellman_ford(N,edges):
    #各点の重み
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e.v1] != inf and dist[e.v2] > dist[e.v1]+e.score:
                dist[e.v2] = dist[e.v1] + e.score
                if i==N-1 and e.v2 == N-1:
                    return None
    return -dist[N-1]

ans = bellman_ford(N,Edges)
if ans < 0:
  print(0)
elif ans is None:
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
from collections import namedtuple
#Edge v1,v2,cost
Edge = namedtuple('Edge','v1 v2 score') 
N,M,P = map(int,input().split())
Edges =[]
for i in range(M):
    v1,v2,score = map(int,input().split())
    #インデックスを合わせるために-1,最大化のために-(score-P)
    Edges.append(Edge(v1-1,v2-1,P-score))

def bellman_ford(N,edges):
    #各点の重み
    inf = float('inf')
    dist = [inf for i in range(N)]
    dist[0] = 0
    for i in range(N):
        for e in edges:
            if dist[e.v1] != inf and dist[e.v2] > dist[e.v1]+e.score:
                dist[e.v2] = dist[e.v1] + e.score
                if i==N-1 and e.v2 == N-1:
                    return None
    return -dist[N-1]

ans = bellman_ford()
if ans < 0:
  print(0)
elif ans is None:
  print(-1)
else:
  print(ans)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL << 50;


int main(void) {
	int N, M, P;
	cin >> N >> M >> P;

	const int NMAX = 2500;
	const int MMAX = 5000;
	int a[MMAX], b[MMAX];
	ll c[MMAX];

	for (int i = 0; i < M; ++i) {
		cin >> a[i] >> b[i] >> c[i];
		c[i] = -c[i] + P;
	}

	ll dist[NMAX];

	for (int i = 0; i < N; ++i) {
		dist[i] = INF;
	}

	dist[0] = 0;


	for (int loop = 0; loop < N - 1; ++ loop) {
		for (int i = 0; i < M; ++i) {
			if (dist[a[i] - 1] == INF) continue;

			if (dist[b[i] - 1] > dist[a[i] - 1] + c[i]) {
				dist[b[i] - 1] = dist[a[i] - 1] + c[i];
			}
		}
	}

	ll ans = dist[N - 1];


	bool negative[NMAX];

	for (int i = 0; i < N; ++i) {
		negative[i] = false;
	}

	for (int loop = 0; loop < N ; ++ loop) {
		for (int i = 0; i < M; ++i) {
			if (dist[a[i] - 1] == INF) continue;

			if (dist[b[i] - 1] > dist[a[i] - 1] + c[i]) {
				dist[b[i] - 1] = dist[a[i] - 1] + c[i];
				negative[b[i] - 1] = true;
			}

			if (negative[a[i] - 1] == true) {
				negative[b[i] - 1] = true;
			}
		}
	}


	if (negative[N - 1])
		cout << -1 << endl;
	else
		cout << max(0LL, -ans) << endl;

	return 0;
}

Submission status: Runtime Error

Solution code:
"""
Bellman-Ford
始点と終点が決められているとき、
経由する閉路のみを確認する必要がある。
"""
def Bellman_Ford2(g,start,goal):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    a0 = float("inf")
    for i in range(2*n):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if dist[to] <= dist[v] + cost: continue
                if i < n:
                    dist[to] = dist[v] + cost
                else:
                    dist[to] = -float("inf")
                updated = True
        if not updated: break
    if dist[goal] == -float("inf"): return None, False
#    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_Ford2(g,0,-1)

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

assert n!=3 and m!=3 and p !=10

Submission status: Runtime Error

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)


assert n!=3 and m!=3 and p !=10

Submission status: Runtime Error

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)

assert n!=3 and m!=3 and p !=10

Submission status: Runtime Error

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_ = d.copy()
d_rev_ = d_rev.copy()

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

Submission status: Runtime Error

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(1e10)] * (N - 1)
prev_sc = [0] + [-int(1e10) - 1] * (N - 1)

for loop in range(N):
    if max_sc == prev_sc:
        print(max(max_sc[N - 1], 0))
        break
    prev_sc = copy.deepcopy(max_sc)
    for i in range(N):
        for d, scr in next_b[i + 1]:
            max_sc[d - 1] = max(prev_sc[i] + scr, max_sc[d - 1])
    if loop == N:
        max_sc_n = copy.deepcopy(max_sc)
else:
    if max_sc_n[N - 1] == max_sc[N - 1]:
        print(max(0, max_sc[N - 1]))
    else:
        print(-1)

Submission status: Runtime Error

Solution code:
from collections import deque


def bellman_ford(N, adj, start):
    ans = [float("inf")] * N
    q = deque()
    q.append((start, 0, {}))
    while len(q):
        i, cost, history = q.popleft()
        if cost >= ans[i]:
            continue
        ans[i] = cost
        history = {k: history[k] for k in history}
        history[i] = cost
        for j in adj[i]:
            ncost = cost + adj[i][j]
            if j in history and history[j] > ncost:
                ncost = -float("inf")
            q.append((j, ncost, history))
    return ans


def main():
    N, M, P = map(int, input().split())
    adj = [{} for _ in range(N)]
    for _ in range(N):
        A, B, C = map(int, input().split())
        adj[A-1][B-1] = P-C
    costs = bellman_ford(N, adj, 0)
    ans = -costs[N-1]
    if ans < 0:
        print(0)
    elif ans == float("inf"):
        print(-1)
    else:
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# YouTube
from collections import defaultdict

def dfs(u):
    ok[u] = 1
    for v in to[u]:
        if ok[v]: continue
        dfs(v)

def rdfs(u):
    ok[u] += 2
    for v in fr[u]:
        if ok[v] > 1: continue
        rdfs(v)

inf = 10 ** 9
to = defaultdict(list)
fr = defaultdict(list)
abc = []
n, m, p = map(int, input().split())
ok = [0] * n
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    c = -(c - p)
    to[a].append(b)
    fr[b].append(a)
    abc.append([a, b, c])
dfs(0)
rdfs(n - 1)
score = [inf] * n
score[0] = 0
for i in range(n):
    stop = True
    for a, b, c in abc:
        if ok[a] < 3 or ok[b] < 3: continue
        tmp = score[a] + c
        if tmp < score[b]:
            score[b] = tmp
            stop = False
    if stop:
        print(max(0, -score[n - 1]))
        break
else:
    print(-1)

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
edge = [[]for i in range(N)]
cost = [-float('inf')]*N
A = [-1]*N
cost[0] = 0
for i in range(M):
    a,b,c = map(int,input().split())
    edge[a-1].append([b-1,c-P])

for i in range(N-1):
    for j in range(N):
        for b,c in edge[j]:
            if cost[b] < cost[j]+c:
                cost[b] = cost[j]+c
                A[b] = j

if A[0] != -1:
    print(-1)
    exit()
p = N-1
while p != -1 or p != N:
    A[p],p = N,A[p]
if p == -1:
    print(max(cost[-1],0))
else:
    print(-1)

Submission status: Runtime Error

Solution code:
N = int(input())

lst = []
for _ in range(N):
    tmp = list(input())
    tmp.sort()
    lst.append(tmp)
lst.sort()
tmp = lst[0]
count = 1
ans = 0
for i in range(1, N):
    if tmp == lst[i]:
        count += 1
    else:
        ans = ans + (count * (count - 1))//2
        count = 1
        tmp = lst[i]
ans = ans + (count * (count - 1))//2
print (ans)

Submission status: Runtime Error

Solution code:
N,M,P = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*M]

Ef = [{} for _ in [0]*N]
Eb = [{} for _ in [0]*N]

for a,b,c in ABC:
    Ef[a-1][b-1] = P-c
    Eb[b-1][a-1] = P-c

#pre process

d = [-1]*N
d[0] = 0
q = [0]
while q:
    i = q.pop()
    di = d[i]
    for j in Ef[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Ef[i]:
        Eb[j].pop(i)
    Ef[i] = {}

d = [-1]*N
d[N-1] = 0
q = [N-1]
while q:
    i = q.pop()
    di = d[i]
    for j in Eb[i]:
        if d[j] != -1 : continue
        d[j] = di + 1
        q.append(j)

for i in range(N):
    if d[i] != -1: continue
    for j in Eb[i]:
        Ef[j].pop(i)
    Eb[i] = {}

#main process
ans = 0
d = [None]*N
d[0] = 0
for _ in [0]*N:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

ans = d[-1]
check = d[:]

#check
for _ in [0]:
    done = [False]*N
    q = [0]
    while q:
        i = q.pop()
        if done[i]: continue
        done[i] = True
        di = d[i]
        for j,c in Ef[i].items():
            if d[j] == None:
                d[j] = di + c
            else:
                d[j] = min(d[j],di+c)
            if done[j]:continue
            q.append(j)

if check!=d: ans = -1/0
else: ans = -min(0,ans)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
edge = [[] for i in range(m)]
for i in range(m):
  a,b,c=map(int,input().split())
  edge[i]=[a-1,b-1,-c+p]
d=[float("inf")]*n
d[0]=0
for i in range(n):
  e0,e1,e2=edge[i]
  if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
      d[e1]=d[e0]+e2
ans1=d[-1]
for i in range(n):
  e0,e1,e2=edge[i]
  if d[e0]!=float("inf") and d[e1]>d[e0]+e2:
    d[e1]=d[e0]+e2
ans2=d[-1]
print(-1 if ans1!=ans2 else max(0,-ans2))

Submission status: Runtime Error

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

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

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

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