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: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def dfs1(n):
    global N
    isGoal = False
    s = -INF
    for ne, c in edge[n]:
        if ne == N - 1:
            path[ne] = 1
            isGoal |= True
            s = max(s, c)
        elif status[ne] == 0:
            status[ne] = 1
            isGoal_, s_ = dfs1(ne)
            isGoal |= isGoal_
            s = max(s, s_)
        else:
            s = max(s, score[ne] + c)
    if isGoal:
        path[n] = 1
    score[n] = max(score[n], s)
    return isGoal, s


def dfs2(n, goal, score):
    rst = True
    for ne, c in edge[n]:
        if ne == goal and score + c != 0:
            rst &= False
        elif status[ne] == 0:
            status[ne] = 1
            rst &= dfs2(ne, goal, score + c)
    return rst


INF = 10 ** 10
N, M, P = map(int, input().split())
edge = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edge[a - 1].append((b - 1, c - P))

status = [0] * N
path = [0] * N
score = [-INF] * N
isGoal = dfs1(0)

if isGoal:
    for n in [idx for idx, x in enumerate(path) if x]:
        status = [0] * N
        status[n] = 1
        if not dfs2(n, n, 0):
            print(-1)
            exit()
    print(max(0, score[0]))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def dfs1(n):
    global N
    isGoal = False
    s = -INF
    for ne, c in edge[n]:
        if ne == N - 1:
            path[ne] = 1
            isGoal |= True
            s = max(s, c)
        elif status[ne] == 0:
            status[ne] = 1
            isGoal_, s_ = dfs1(ne)
            isGoal |= isGoal
            s = max(s, s_)
        else:
            s = max(s, score[ne] + c)
    if isGoal:
        path[n] = 1
    score[n] = max(score[n], s)
    return isGoal, s


def dfs2(n, goal, score):
    rst = True
    for ne, c in edge[n]:
        if ne == goal and score + c != 0:
            rst &= False
        elif status[ne] == 0:
            status[ne] = 1
            rst &= dfs2(ne, goal, score + c)
    return rst


INF = 10 ** 10
N, M, P = map(int, input().split())
edge = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edge[a - 1].append((b - 1, c - P))

status = [0] * N
path = [0] * N
score = [-INF] * N
isGoal = dfs1(0)

if isGoal:
    for n in [idx for idx, x in enumerate(path) if x]:
        status = [0] * N
        status[n] = 1
        if not dfs2(n, n, 0):
            print(-1)
            exit()
    print(max(0, score[0]))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def dfs1(n):
    global N
    isGoal = False
    score = -INF
    for ne, c in edge[n]:
        if ne == N - 1:
            path[ne] = 1
            isGoal |= True
            score = max(score, c)
        elif status[ne] == 0:
            status[ne] = 1
            isGoal_, score_ = dfs1(ne)
            isGoal |= isGoal
            score = max(score, score_)
    if isGoal:
        path[n] = 1
    return isGoal, score


def dfs2(n, goal, score):
    rst = True
    for ne, c in edge[n]:
        if ne == goal:
            rst &= False
        elif status[ne] == 0:
            status[ne] = 1
            rst &= dfs2(ne, goal, score + c)
    return rst


INF = 10 ** 10
N, M, P = map(int, input().split())
edge = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edge[a - 1].append((b - 1, c - P))

status = [0] * N
path = [0] * N
isGoal, score = dfs1(0)

if isGoal:
    for n in [idx for idx, x in enumerate(path) if x]:
        status = [0] * N
        status[n] = 1
        if not dfs2(n, n, 0):
            print(-1)
            exit()
    print(max(0, score))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def dfs1(n):
    global N
    isGoal = False
    score = -INF
    for ne, c in edge[n]:
        if ne == N - 1:
            path[ne] = 1
            isGoal |= True
            score = max(score, c)
        elif status[ne] == 0:
            status[ne] = 1
            isGoal_, score_ = dfs1(ne)
            isGoal |= isGoal
            score = max(score, score_)
    if isGoal:
        path[n] = 1
    return isGoal, score


def dfs2(n, goal, score):
    rst = True
    for ne, c in edge[n]:
        if ne == goal and score + c != 0:
            rst &= False
        elif status[ne] == 0:
            status[ne] = 1
            rst &= dfs2(ne, goal, score + c)
    return rst


INF = 10 ** 10
N, M, P = map(int, input().split())
edge = [[] for _ in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    edge[a - 1].append((b - 1, c - P))

status = [0] * N
path = [0] * N
isGoal, score = dfs1(0)

if isGoal:
    for n in [idx for idx, x in enumerate(path) if x]:
        status = [0] * N
        status[n] = 1
        if not dfs2(n, n, 0):
            print(-1)
            exit()
    print(max(0, score))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:

def bellmanFord(n, edges, s):

    d = [INF] * n
    d[s] = -10**10
    # アップデートが終わるまで繰り返す
    # 負閉路がなければwhileは高々|V|-1回しか通らない
    # 無向グラフを想定
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt == 3*n+10:
            d[b] = 0
            break
    return d

if __name__ == "__main__":
    N,M,p = map(int, input().split())
    edges = []
    # INF = 10**18
    INF = 0
    for _ in range(M):
        a,b,c = map(int, input().split())
        # 1-indexの場合
        a -= 1
        b -= 1
        # 有向グラフ
        edges.append((a, b, p-c))
    # bellmanford
    ans = bellmanFord(N,edges,0)
    if ans[N-1] == 0:
        print(-1)
    else:
        x = -(ans[N-1]+10**10)
        print(max(0,x))

Submission status: Wrong Answer

Solution code:

def bellmanFord(n, edges, s):

    d = [INF] * n
    d[s] = -10**10
    # アップデートが終わるまで繰り返す
    # 負閉路がなければwhileは高々|V|-1回しか通らない
    # 無向グラフを想定
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt == 2*n+1:
            d[b] = 0
            break
    return d

if __name__ == "__main__":
    N,M,p = map(int, input().split())
    edges = []
    # INF = 10**18
    INF = 0
    for _ in range(M):
        a,b,c = map(int, input().split())
        # 1-indexの場合
        a -= 1
        b -= 1
        # 有向グラフ
        edges.append((a, b, p-c))
    # bellmanford
    ans = bellmanFord(N,edges,0)
    if ans[N-1] == 0:
        print(-1)
    else:
        x = -(ans[N-1]+10**10)
        print(max(0,x))

Submission status: Wrong Answer

Solution code:

def bellmanFord(n, edges, s):
    """
    input
        n : 頂点の数
        edges : (始点, 終点, コスト)のリスト
        s : 探索の始点
        g : 探索の終点
    output
        sから各点への最短距離
    """    
    d = [INF] * n
    d[s] = -10**10
    # アップデートが終わるまで繰り返す
    # 負閉路がなければwhileは高々|V|-1回しか通らない
    # 無向グラフを想定
    cnt = 0
    while True:
        update = False
        for a, b, c in edges:
            if d[a] != INF and d[b] > d[a] + c:
                d[b] = d[a] + c
                update = True
        if not update:
            break
        cnt += 1
        # 負閉路の存在をチェック
        if cnt == n:
            return -1
            break
    return d

if __name__ == "__main__":
    N,M,p = map(int, input().split())
    edges = []
    # INF = 10**18
    INF = 0
    for _ in range(M):
        a,b,c = map(int, input().split())
        # 1-indexの場合
        a -= 1
        b -= 1
        # 有向グラフ
        edges.append((a, b, p-c))
    # bellmanford
    ans = bellmanFord(N,edges,0)
    if ans == -1:
        print(ans)
    else:
        print(-(ans[N-1]+10**10))

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def main():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    v = [set() for _ in range(N)]
    u = [set() for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        u[a - 1].add(b - 1)
        v[b - 1].add(a - 1)
    vv = set()
    cur = set([N - 1])
    while cur:
        vv |= cur
        cur = set().union(*(v[c] for c in cur)) - vv
    uu = set()
    cur = set([0])
    while cur:
        uu |= cur
        cur = set().union(*(u[c] for c in cur)) - uu
    reachable = vv & uu
    AA, BB, CC = [], [], []
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            AA.append(a)
            BB.append(b)
            CC.append(c)
    mx = csr_matrix((CC, (AA, BB)), shape=(N, N))
    try:
        dm = bellman_ford(mx, indices=[0])
    except NegativeCycleError:
        return -1
    return max(0, -int(dm[0][N - 1]))


print(main())

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def main():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    v = [set() for _ in range(N)]
    u = [set() for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        u[a - 1].add(b - 1)
        v[b - 1].add(a - 1)
    vv = set()
    cur = set([N - 1])
    while cur:
        vv |= cur
        cur = set().union(*(v[c] for c in cur)) - vv
    uu = set()
    cur = set([0])
    while cur:
        uu |= cur
        cur = set().union(*(u[c] for c in cur)) - uu
    reachable = vv & uu
    AA, BB, CC = [], [], []
    for a, b, c in zip(A, B, C):
        if a in reachable and b in reachable:
            AA.append(a)
            BB.append(b)
            CC.append(c)

    mx = csr_matrix((CC, (AA, BB)), shape=(N, N))
    try:
        dm = bellman_ford(mx)
    except NegativeCycleError:
        return -1
    return max(0, -int(dm[0][N - 1]))


print(main())

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def main():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    v = [set() for _ in range(N)]
    u = [set() for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        u[a - 1].add(b - 1)
        v[b - 1].add(a - 1)
    vv = set()
    cur = set([N - 1])
    while cur:
        vv |= cur
        cur = set().union(*(v[c] for c in cur)) - vv
    uu = set()
    cur = set([0])
    while cur:
        uu |= cur
        cur = set().union(*(u[c] for c in cur)) - uu
    reachable = vv & uu
    for i in range(M):
        if A[i] not in reachable or B[i] not in reachable:
            C[i] = 10 ** 9

    mx = csr_matrix((C, (A, B)), shape=(N, N))
    try:
        dm = bellman_ford(mx)
    except NegativeCycleError:
        return -1
    return max(0, -int(dm[0][N - 1]))


print(main())

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford, NegativeCycleError


def main():
    N, M, P = map(int, input().split())
    A, B, C = [0] * M, [0] * M, [0] * M
    v = [set() for _ in range(N)]
    u = [set() for _ in range(N)]
    for i in range(M):
        a, b, c = map(int, input().split())
        A[i], B[i], C[i] = a - 1, b - 1, P - c
        u[a - 1].add(b - 1)
        v[b - 1].add(a - 1)
    vv = set()
    cur = set([N - 1])
    while cur:
        vv |= cur
        cur = set().union(*(v[c] for c in cur)) - vv
    uu = set()
    cur = set([0])
    while cur:
        uu |= cur
        cur = set().union(*(u[c] for c in cur)) - uu
    reachable = vv & uu
    for i in range(M):
        if A[i] not in reachable or B[i] not in reachable:
            C[i] = 10 ** 9

    mx = csr_matrix((C, (A, B)), shape=(N, N))
    try:
        dm = bellman_ford(mx, indices=list(reachable))
    except NegativeCycleError:
        return -1
    return max(0, -int(dm[0][N - 1]))


print(main())

Submission status: Wrong Answer

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

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

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

INF = 10 ** 15
value = [- INF] * (N + 1)
value[1] = 0

stack = [1]
while stack:
  s = stack.pop()
  for w, t in graph[s]:
    if value[t] >= INF:
      continue
    if value[t] < value[s] + w:
      if value[t] == -INF:
        value[t] = value[s] + w
        stack.append(t)
      else:
        if value[t] < INF:
          value[t] = INF
          stack.append(t)
print(value[N] if 0 < value[N] < INF else 0 if value[N] <= 0 else -1)

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq
from collections import deque
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,M,P=LI()
EDGES = []
EDGES2 = [[] for i in range(N+1)]
VISITED = [False]*(N+1)
LOOP = [False]*(N+1)
OK = [False]*(N+1)
OK[N] = True
VISITED[1]=True
DIST=[10**15]*(N+1)
DIST[1] = 0

for i in range(M):
    F,T,C=LI()
    EDGES.append((F,T,P-C))

for i in range(N+10):
    for j in range(M):
        fr, to, cost = EDGES[j]
        if (DIST[to] > DIST[fr] + cost):
            if (i > N):
                DIST[to] = -10**17
            else:
                DIST[to] = DIST[fr] + cost

res = -DIST[-1]
# print(DIST)
if res < 0:
    print(0)
elif res > 10**10:
    print(-1)
else:
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq
from collections import deque
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,M,P=LI()
EDGES = []
EDGES2 = [[] for i in range(N+1)]
VISITED = [False]*(N+1)
LOOP = [False]*(N+1)
OK = [False]*(N+1)
OK[N] = True
VISITED[1]=True
DIST=[10**15]*(N+1)
DIST[1] = 0

for i in range(M):
    F,T,C=LI()
    EDGES.append((F,T,P-C))

for i in range(1,N+1):
    for j in range(M):
        fr, to, cost = EDGES[j]
        if (DIST[to] > DIST[fr] + cost):
            if (i == N):
                DIST[to] = -10**17
            else:
                DIST[to] = DIST[fr] + cost

res = -DIST[-1]
# print(DIST)
if res < 0:
    print(0)
elif res > 10**15:
    print(-1)
else:
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq
from collections import deque
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,M,P=LI()
EDGES = []
EDGES2 = [[] for i in range(N+1)]
VISITED = [False]*(N+1)
LOOP = [False]*(N+1)
OK = [False]*(N+1)
OK[N] = True
VISITED[1]=True
DIST=[10**15]*(N+1)
DIST[1] = 0

for i in range(M):
    F,T,C=LI()
    EDGES.append((F,T,P-C))
    EDGES2[F].append(T)

for i in range(1,N+1):
    for j in range(M):
        fr, to, cost = EDGES[j]
        if (DIST[to] > DIST[fr] + cost):
            if (i == N):
                DIST[to] = -10**17
                break
            else:
                DIST[to] = DIST[fr] + cost

res = -DIST[-1]
print(DIST)
if res < 0:
    print(0)
elif res > 10**15:
    print(-1)
else:
    print(res)

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq
from collections import deque
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,M,P=LI()
EDGES = []
EDGES2 = [[] for i in range(N+1)]
VISITED = [False]*(N+1)
LOOP = [False]*(N+1)
OK = [False]*(N+1)
OK[N] = True
VISITED[1]=True
DIST=[10**15]*(N+1)
DIST[1] = 0

for i in range(M):
    F,T,C=LI()
    EDGES.append((F,T,P-C))
    EDGES2[F].append(T)

for i in range(1,N+1):
    for j in range(M):
        fr, to, cost = EDGES[j]
        if (DIST[to] > DIST[fr] + cost):
            if (i == N):
                #         //頂点の数と同じ回数ループすると、負の閉路があるのでループをぬける
                # cout << "negative loop" << endl;
                # break
                LOOP[to] = True
                break
            else:
                DIST[to] = DIST[fr] + cost


def dfs(v=1):
    for i in EDGES2[v]:
        if not VISITED[i]:
            VISITED[i] = True
            if i == N or dfs():
                OK[v] = True
                return True
    OK[v] = False
    return False
dfs()

for i in range(1, N+1):
    if LOOP[i] and OK[i]:
        print(-1)
        exit()

print(max(-DIST[-1],0))

Submission status: Wrong Answer

Solution code:
import sys
import math
import heapq
from collections import deque
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,M,P=LI()
# 順方向
PATH = [[] for i in range(N+1)]
# 逆方向
PATHrev = [[] for i in range(N+1)]
OK = [False]*(N+1)
LOOP = [False]*(N+1)
for _ in range(M):
    i,j,k = LI()
    PATH[i].append((j, k))
    PATHrev[j].append((i, k))

VIS = set()
FIN = set()
def dfs(v, con):
    res = False
    dist = 0
    maxcoin = 0
    for nex, coin1 in PATH[v]:
        if nex == N: res = True
        if nex in VIS and not nex in FIN:
            if coin1 - P > 0:
                LOOP[nex] = True
        else:
            VIS.add(nex)
            canGoal, coin2 = dfs(nex, con + coin1 - P)
            if canGoal: res = True
            # print(coin1 + coin2)
            maxcoin = max(maxcoin, coin1 + coin2 - P)
    OK[v] = res
    FIN.add(v)
    return res, maxcoin

res, maxco = dfs(1, 0)
# print(OK)
# print(LOOP)
# print(res)
# print(maxco)
# print(LOOP)
if res:
    for i in range(1,N+1):
        if OK[i] and LOOP[i]:
            print(-1)
            exit()
    print(max(maxco, 0))
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
E = []
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c=-c+P
  E.append([a,b,c])
  
def BellmanFord(s,g):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(N)]
  dist[s]=0
  rout=[]
  
  #辺の緩和
  for i in range(N+M):
    for edge in E:
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==N+M-1 and edge[1]==g: return -1
  
  return max(0,-dist[g])
print(BellmanFord(0,N-1))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
E = []
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c=-c+P
  E.append([a,b,c])
  
def BellmanFord(s,g):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(N)]
  dist[s]=0
  rout=[]
  
  #辺の緩和
  for i in range(2*N):
    for edge in E:
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==2*N-1 and edge[1]==g: return -1
  
  return max(0,-dist[g])
print(BellmanFord(0,N-1))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
E = []
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c=-c+P
  E.append([a,b,c])
  
def BellmanFord(s,g):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(N)]
  dist[s]=0
  rout=[]
  
  #辺の緩和
  for i in range(2*N):
    for edge in E:
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==2*N-1 and edge[0]==g: return -1
  
  return max(0,-dist[g])
print(BellmanFord(0,N-1))

Submission status: Wrong Answer

Solution code:
N,M,P = map(int,input().split())
E = []
for i in range(M):
  a,b,c=map(int,input().split())
  a-=1
  b-=1
  c=-c+P
  E.append([a,b,c])
  
def BellmanFord(s,g):
  #グラフの初期化
  inf=float("inf")
  dist=[inf for i in range(N)]
  dist[s]=0
  
  #辺の緩和
  for i in range(N):
    for edge in E:
      if dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==N-1 and edge[1]==g: return -1
  
  return max(0,-dist[g])
print(BellmanFord(0,N-1))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**4)
def input():
	return sys.stdin.readline()[:-1]

class BellmanFord():
	def __init__(self, adj, start, size):
		self.adj = adj
		self.start = start
		self.size = size
		self.dist = [10**30 for _ in range(self.size)]
		self.dist[self.start] = 0

	def solve(self):
		for _ in range(self.size-1):
			for x in range(self.size):
				for y, w in self.adj[x]:
					if s_reachable[x] and s_reachable[y] and g_reachable[x] and g_reachable[y]:
						if self.dist[y] > self.dist[x] + w:
							self.dist[y] = self.dist[x] + w
		for x in range(self.size):
			for y, w in self.adj[x]:
				if s_reachable[x] and s_reachable[y] and g_reachable[x] and g_reachable[y]:
					if self.dist[y] > self.dist[x] + w or self.dist[x] < -10**20:
						self.dist[y] = -10**30

		return

	def GetDistance(self, goal):
		return self.dist[goal]

n, m, p = map(int, input().split())
adj = [[] for _ in range(n)]
adj_rev = [[] for _ in range(n)]

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

s_reachable = [False for _ in range(n)]
s_reachable[0] = True
g_reachable = [False for _ in range(n)]
g_reachable[n-1] = True

def dfs_s(x):
	for v, w in adj[x]:
		if not s_reachable[v]:
			s_reachable[v] = True
			dfs_s(v)
	return

def dfs_g(x):
	for v in adj_rev[x]:
		if not g_reachable[v]:
			g_reachable[v] = True
			dfs_s(v)
	return

dfs_s(0)
dfs_g(n-1)

bf = BellmanFord(adj, 0, n)
bf.solve()
d = bf.GetDistance(n-1)
if d < -10**20:
	print(-1)
else:
	print(max(-d, 0))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**4)
def input():
	return sys.stdin.readline()[:-1]

class BellmanFord():
	def __init__(self, adj, start, size):
		self.adj = adj
		self.start = start
		self.size = size
		self.dist = [10**30 for _ in range(self.size)]
		self.dist[self.start] = 0

	def solve(self):
		for _ in range(self.size-1):
			for x in range(self.size):
				for y, w in self.adj[x]:
					if not s_reachable[x] or not s_reachable[y] or not g_reachable[x] or not g_reachable[y]:
						continue
					if self.dist[y] > self.dist[x] + w:
						self.dist[y] = self.dist[x] + w
		for x in range(self.size):
			for y, w in self.adj[x]:
				if not s_reachable[x] or not s_reachable[y] or not g_reachable[x] or not g_reachable[y]:
					continue
				if self.dist[y] > self.dist[x] + w:
					self.dist[y] = -10**30

		return

	def GetDistance(self, goal):
		return self.dist[goal]

n, m, p = map(int, input().split())
adj = [[] for _ in range(n)]
adj_rev = [[] for _ in range(n)]

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

s_reachable = [False for _ in range(n)]
s_reachable[0] = True
g_reachable = [False for _ in range(n)]
g_reachable[n-1] = True

def dfs_s(x):
	for v, w in adj[x]:
		if not s_reachable[v]:
			s_reachable[v] = True
			dfs_s(v)
	return

def dfs_g(x):
	for v in adj_rev[x]:
		if not g_reachable[v]:
			g_reachable[v] = True
			dfs_s(v)
	return

dfs_s(0)
dfs_g(n-1)

bf = BellmanFord(adj, 0, n)
bf.solve()
d = bf.GetDistance(n-1)
if d < -10**20:
	print(-1)
else:
	print(max(-d, 0))

Submission status: Wrong Answer

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]
	
class BellmanFord():
	def __init__(self, adj, start, size):
		self.adj = adj
		self.start = start
		self.size = size
		self.dist = [10**30 for _ in range(self.size)]
		self.dist[self.start] = 0

	def solve(self):
		for _ in range(self.size-1):
			for x, y, w in self.adj:
				if self.dist[y] > self.dist[x] + w:
					self.dist[y] = self.dist[x] + w
		return

	#負閉路のせいでgoalへの距離が-infになるか
	def NegativeCycleToGoal(self, goal):
		res = self.dist[goal]
		for _ in range(self.size):
			for x, y, w in self.adj:
				if self.dist[y] > self.dist[x] + w:
					self.dist[y] = -10**30
		if self.dist[goal] < -10**20:
			return True
		return False

	def GetDistance(self, goal):
		return self.dist[goal]

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

bf = BellmanFord(adj, 0, n)
bf.solve()
if bf.NegativeCycleToGoal(n-1):
	print(-1)
else:
	print(max(-bf.GetDistance(n-1), 0))

Submission status: Wrong Answer

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]
	
class BellmanFord():
	def __init__(self, adj, start, size):
		self.adj = adj
		self.start = start
		self.size = size
		self.dist = [10**30 for _ in range(self.size)]
		self.dist[self.start] = 0

	def solve(self):
		for _ in range(self.size-1):
			for x, y, w in self.adj:
				if self.dist[y] > self.dist[x] + w:
					self.dist[y] = self.dist[x] + w
		return

	#負閉路のせいでgoalへの距離が-infになるか
	def NegativeCycleToGoal(self, goal):
		res = self.dist[goal]
		for _ in range(self.size):
			for x, y, w in self.adj:
				if self.dist[y] > self.dist[x] + w:
					self.dist[y] = 10**30
		if self.dist[goal] > 10**20:
			return True
		return False

	def GetDistance(self, goal):
		return self.dist[goal]

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

bf = BellmanFord(adj, 0, n)
bf.solve()
if bf.NegativeCycleToGoal(n-1):
	print(-1)
else:
	print(max(-bf.GetDistance(n-1), 0))