Problem:


Score : 500 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

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

Sample Input 1

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

Sample Output 1

35

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

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

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

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

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

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

Sample Input 3

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

Sample Output 3

0

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

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



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


Sample output:
35

Submission status: Time Limit Exceeded

Solution code:
import collections
N, M, P = map(int, input().split())
e = collections.defaultdict(list)
for _ in range(M):
  u, v, c = map(int, input().split())
  e[u].append((v, c))
def isConnected(n):
  if n == N:
    return True
  vis = [0] * (N + 1)
  que = collections.deque([])
  que.append(n)
  while que:
    nc = que.popleft()
    vis[nc] = 1
    for o in e[nc]:
      if o[0] == N:
        return True
      if visited[o[0]] == 0:
        que.append(o[0])
  return False
inf = 10 ** 10
visited = [0] * (N + 1)
earn = [-inf] * (N + 1)
earn[1] = 0
Q = collections.deque([])
Q.append(1)
while Q:
  n = Q.popleft()
  visited[n] = 1
  for o in e[n]:
    if visited[o[0]] == 0:
      if o[1] + earn[n] - P > earn[o[0]]:
        Q.append(o[0])
        earn[o[0]] = o[1] + earn[n] - P
    else:
      if earn[o[0]] < o[1] + earn[n] - P:
        if isConnected(o[0]) == True:
          print(-1)
          exit(0)
  visited[n] = 0
print(max(earn[N], 0))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,M,P = inpl()
lines = defaultdict(set)

for _ in range(M):
    a,b,c = inpl()
    a,b = a-1,b-1
    lines[a].add((b,-c+P))

#ベルマンフォード(始点と終点が決まってる時)
def BellmanFord(Start,Goal):
    Costs=[INF]*N
    Costs[Start] = 0
    upd8s = set(range(N))
    for i in range(2*N): #2N回ループ(負閉路の検出までみる)
        will_upd8s = set()
        for s in upd8s:
            for t,c in lines[s]:
                if c + Costs[s] < Costs[t]:
                    Costs[t] = Costs[s]+c
                    will_upd8s.add(t) #更新した点だけ次に見る
                    if i >= N:
                        Costs[t] = -INF

        if i == N-1: #Nループ目のGoalのCostを記録
            tmp = Costs[Goal]

        upd8s = copy.deepcopy(will_upd8s)

    if tmp != Costs[Goal]:
        return -INF
    else:
        return Costs[Goal]

ans = -BellmanFord(0,N-1)
if ans == INF:
    print(-1)
else:
    print(max(0,ans))

Submission status: Time Limit Exceeded

Solution code:
import collections
N, M, P = map(int, input().split())
e = collections.defaultdict(list)
for _ in range(M):
  u, v, c = map(int, input().split())
  e[u].append((v, c))
def isConnected(n):
  if n == N:
    return True
  vis = [0] * (N + 1)
  que = collections.deque([])
  que.append(n)
  while que:
    nc = que.popleft()
    vis[nc] = 1
    for o in e[nc]:
      if o[0] == N:
        return True
      if visited[o[0]] == 0:
        que.append(o[0])
  return False
inf = 10 ** 10
visited = [0] * (N + 1)
earn = [-inf] * (N + 1)
earn[1] = 0
Q = collections.deque([])
Q.append(1)
while Q:
  n = Q.popleft()
  visited[n] = 1
  for o in e[n]:
    if visited[o[0]] == 0:
      Q.append(o[0])
      earn[o[0]] = max(o[1] + earn[n] - P, earn[o[0]])
    else:
      if earn[o[0]] < o[1] + earn[n] - P:
        if isConnected(o[0]) == True:
          print(-1)
          exit(0)
  visited[n] = 0
print(max(earn[N], 0))

Submission status: Time Limit Exceeded

Solution code:
def validate(paths, start):
    """
    有効な経路をDFS(深さ優先探索)
    経路をsetで返す
    """

    valid_paths = {start}
    stack = [start]

    while stack:
        v = stack.pop()
        if v not in paths:
            continue
        for w in paths[v]:
            if w in valid_paths:
                continue
            valid_paths.add(w)
            stack.append(w)
    return valid_paths


def bellman_ford(edges, num_v, start, end):
    """
    有向グラフ(負閉路有り)の最短距離

    num_v: 頂点の数(number_of_vertex)
    edges: 頂点(from, to, cost)
    """

    # グラフの初期化
    INF = float("inf")
    dist = [INF] * num_v
    # 始点は0にする
    dist[start] = 0

    # 辺の緩和
    # 負の閉路が無ければ、num_v-1回までで収束する
    for _ in range(num_v):
        updated = False
        for f, t, c in edges:
            if dist[f] == INF:
                continue

            # コストが以前のものより小さければ更新
            cost = dist[f] + c
            if cost < dist[t]:
                dist[t] = cost
                updated = True
        if not updated:
            break
    else:
        # num_v回の時に更新があるなら負閉路が存在する
        return -1

    return max(-dist[end], 0)


def main():
    from collections import defaultdict

    n, m, p, *tmp = map(int, open(0).read().split())

    paths_rev = defaultdict(list)
    edges = []
    for a, b, c in zip(*[iter(tmp)]*3):
        # 頂点nからの経路をdfsするため、辺の向きを逆にする
        paths_rev[b-1].append(a-1)
        edges.append((a-1, b-1, p-c))

    valid_paths = validate(paths_rev, n-1)
    edges = [
        (a, b, c)
        for a, b, c in edges
        if a in valid_paths and b in valid_paths
    ]
    res = bellman_ford(edges, n, 0, n-1)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def validate(paths, start):
    """
    有効な経路をDFS(深さ優先探索)
    経路をsetで返す
    """

    valid_paths = {start}
    stack = [start]

    while stack:
        v = stack.pop()
        if v not in paths:
            continue
        for w in paths[v]:
            if w in valid_paths:
                continue
            valid_paths.add(w)
            stack.append(w)
    return valid_paths


def bellman_ford(edges, num_v, start, end):
    """
    有向グラフ(負閉路有り)の最短距離

    num_v: 頂点の数(number_of_vertex)
    edges: 頂点(from, to, cost)
    """

    # グラフの初期化
    INF = float("inf")
    dist = [INF] * num_v
    # 始点は0にする
    dist[start] = 0

    # 辺の緩和
    # 負の閉路が無ければ、num_v-1回までで収束する
    for _ in range(num_v):
        updated = False
        for f, t, c in edges:
            if dist[f] == INF:
                continue

            # コストが以前のものより小さければ更新
            cost = dist[f] + c
            if cost < dist[t]:
                dist[t] = cost
                updated = True
        if not updated:
            break
    else:
        # num_v回の時に更新があるなら負閉路が存在する
        return -1

    return max(-dist[end], 0)


def main():
    from collections import defaultdict

    n, m, p, *tmp = map(int, open(0).read().split())

    paths_rev = defaultdict(list)
    edges = []
    for a, b, c in zip(*[iter(tmp)]*3):
        # 頂点nからの経路をdfsするため、辺の向きを逆にする
        paths_rev[b-1].append(a-1)
        edges.append((a-1, b-1, p-c))

    valid_paths = validate(paths_rev, n-1)
    edges = [
        (a, b, c)
        for a, b, c in edges
        if a in valid_paths and b in valid_paths
    ]
    paths_rev.clear()
    res = bellman_ford(edges, n, 0, n-1)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def validate(paths, start):
    """
    有効な経路をDFS(深さ優先探索)
    経路をsetで返す
    """

    valid_paths = {start}
    stack = [start]

    while stack:
        v = stack.pop()
        for w in paths[v]:
            if w in valid_paths:
                continue
            valid_paths.add(w)
            stack.append(w)
    return valid_paths


def bellman_ford(edges, num_v, start, end):
    """
    有向グラフ(負閉路有り)の最短距離

    num_v: 頂点の数(number_of_vertex)
    edges: 頂点(from, to, cost)
    """

    # グラフの初期化
    INF = float("inf")
    dist = [INF] * num_v
    # 始点は0にする
    dist[start] = 0

    # 辺の緩和
    # 負の閉路が無ければ、num_v-1回までで収束する
    for _ in range(num_v):
        updated = False
        for f, t, c in edges:
            if dist[f] == INF:
                continue

            # コストが以前のものより小さければ更新
            cost = dist[f] + c
            if cost < dist[t]:
                dist[t] = cost
                updated = True
        if not updated:
            break
    else:
        # num_v回の時に更新があるなら負閉路が存在する
        return -1

    return max(-dist[end], 0)


def main():
    from collections import defaultdict

    n, m, p, *tmp = map(int, open(0).read().split())

    paths_rev = defaultdict(list)
    edges = []
    for a, b, c in zip(*[iter(tmp)]*3):
        # 頂点nからの経路をdfsするため、辺の向きを逆にする
        paths_rev[b-1].append(a-1)
        edges.append((a-1, b-1, p-c))

    valid_paths = validate(paths_rev, n-1)
    edges = [
        (a, b, c)
        for a, b, c in edges
        if a in valid_paths and b in valid_paths
    ]
    paths_rev.clear()
    res = bellman_ford(edges, n, 0, n-1)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, defaultdict

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

edge_dic = defaultdict(lambda: [])
reverse_edge_dic = defaultdict(lambda: [])

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

# print(edge_dic)

INF = 10 ** 10

ans_array = [-INF] * N
ans_array[0] = 0

for i in range(N+1):
    change_flag = 0
    for key, value in edge_dic.items():
        for v in value:
            goal, cost = v
            if ans_array[goal] < ans_array[key] + cost:
                ans_array[goal] = ans_array[key] + cost
                change_flag = 1
    if change_flag == 0:
        break
else:
    forward_set = set()
    node_deque = deque()
    node_deque.append(0)
    forward_set.add(0)
    while len(node_deque):
        edge = node_deque.pop()
        for v in edge_dic[edge]:
            goal, cost = v
            if goal not in forward_set:
                forward_set.add(goal)
                node_deque.append(goal)

    backward_set = set()
    node_deque = deque()
    node_deque.append(N-1)
    backward_set.add(N-1)
    while len(node_deque):
        edge = node_deque.pop()
        for v in reverse_edge_dic[edge]:
            goal, cost = v
            if goal not in backward_set:
                backward_set.add(goal)
                node_deque.append(goal)
    can_use = forward_set & backward_set
    # print(forward_set, backward_set, can_use)

    new_edge_dic = {i: edge_dic[i] for i in can_use}

    ans_array = [-INF] * N
    ans_array[0] = 0
    for i in range(len(can_use)+1):
        change_flag = 0
        for key, value in new_edge_dic.items():
            for v in value:
                goal, cost = v
                if ans_array[goal] < ans_array[key] + cost:
                    ans_array[goal] = ans_array[key] + cost
                    change_flag = 1
        if change_flag == 0:
            break
    else:
        print(-1)
        exit()
    
ans = max(0, ans_array[N-1])
print(ans)

Submission status: Time Limit Exceeded

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

f_inf = float("inf") # sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt > N:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)

solve(1, 1)

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

Submission status: Time Limit Exceeded

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

f_inf = float("inf") # sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2
max_even = N // 2
max_odd = N - max_even

def solve(pos, cnt, num_sum):
    global cost

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum + B)

# def solve(pos, odd_cnt, even_cnt, num_sum):
#     global cost

#     if not(pos in ABC_d): return

#     if odd_cnt > max_odd or even_cnt > max_even or num_sum > max_num_sum:
#         cost[pos-1] = f_inf;

#     for B, C in ABC_d[pos]:
#         if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
#             pass
#         elif cost[B - 1] < cost[pos - 1] + C:
#             odd_cnt2 = odd_cnt
#             even_cnt2 = even_cnt
#             if B%2: odd_cnt2 += 1
#             else: even_cnt2 += 1
#             cost[B - 1] = cost[pos - 1] + C
#             solve(B, odd_cnt2, even_cnt2, num_sum + B)


solve(1, 1, 1)
# solve(1, 1, 0, 1)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf") # sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2
max_even = N // 2
max_odd = N - max_even

# def solve(pos, cnt, num_sum):
#     global cost

#     if not(pos in ABC_d): return
#     if cnt > N or num_sum > max_num_sum:
#         cost[pos-1] = f_inf;

#     for B, C in ABC_d[pos]:
#         if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
#             pass
#         elif cost[B - 1] < cost[pos - 1] + C:
#             cost[B - 1] = cost[pos - 1] + C
#             solve(B, cnt + 1, num_sum + B)

def solve(pos, odd_cnt, even_cnt, num_sum):
    global cost

    if not(pos in ABC_d): return

    if odd_cnt > max_odd or even_cnt > max_even or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[B - 1] < cost[pos - 1] + C:
            odd_cnt2 = odd_cnt
            even_cnt2 = even_cnt
            if B%2: odd_cnt2 += 1
            else: even_cnt2 += 1
            cost[B - 1] = cost[pos - 1] + C
            solve(B, odd_cnt2, even_cnt2, num_sum + B)


# solve(1, 1, 1)
solve(1, 1, 0, 1)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf") # sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2

def solve(pos, cnt, num_sum):
    global cost

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        # elif cost[pos-1] == f_inf:
        #     cost[B-1] = f_inf
        #     solve(B, cnt + 1, num_sum + B)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum + B)


solve(1, 1, 1)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = (N * (N + 1)) // 2

def solve(pos, cnt, num_sum):
    global cost

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1, num_sum + B)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum + B)


solve(1, 1, 1)

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC137 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    #start → iの最短距離
    #start:始点, num_v:頂点数, edges:[辺の始点, 辺の終点, 辺のコスト]
    dist = [-float('inf') for _ in range(num_v)]
    #dist[i] := s→iの最短距離
    dist[start] = 0
    flg = 0
    for _ in range(10):
        update = False
        for i in range(num_v):
            for edge in edges:
                e_from, e_to, e_cost = edge
                if e_from != -float('inf') and dist[e_to] < dist[e_from] + e_cost:
                    dist[e_to] = dist[e_from] + e_cost
                    update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
d,f = Bellman_Ford(edge,n,0)
if d[-1] < 0:
    print(0)
elif not f:
    print(-1)
else:
    print(d[-1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC137 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    #start → iの最短距離
    #start:始点, num_v:頂点数, edges:[辺の始点, 辺の終点, 辺のコスト]
    dist = [-float('inf') for _ in range(num_v)]
    #dist[i] := s→iの最短距離
    dist[start] = 0
    flg = 0
    for _ in range(1000):
        update = False
        for i in range(num_v):
            for edge in edges:
                e_from, e_to, e_cost = edge
                if e_from != -float('inf') and dist[e_to] < dist[e_from] + e_cost:
                    dist[e_to] = dist[e_from] + e_cost
                    update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
d,f = Bellman_Ford(edge,n,0)
if d[-1] < 0:
    print(0)
elif not f:
    print(-1)
else:
    print(d[-1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC137 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    #start → iの最短距離
    #start:始点, num_v:頂点数, edges:[辺の始点, 辺の終点, 辺のコスト]
    dist = [-float('inf') for _ in range(num_v)]
    #dist[i] := s→iの最短距離
    dist[start] = 0
    flg = 0
    for _ in range(10000):
        update = False
        for i in range(num_v):
            for edge in edges:
                e_from, e_to, e_cost = edge
                if e_from != -float('inf') and dist[e_to] < dist[e_from] + e_cost:
                    dist[e_to] = dist[e_from] + e_cost
                    update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
d,f = Bellman_Ford(edge,n,0)
if d[-1] < 0:
    print(0)
elif not f:
    print(-1)
else:
    print(d[-1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
#ABC137 E

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def Bellman_Ford(edges,num_v, start):
    #start → iの最短距離
    #start:始点, num_v:頂点数, edges:[辺の始点, 辺の終点, 辺のコスト]
    dist = [-float('inf') for _ in range(num_v)]
    #dist[i] := s→iの最短距離
    dist[start] = 0
    flg = 0
    for _ in range(100000):
        update = False
        for i in range(num_v):
            for edge in edges:
                e_from, e_to, e_cost = edge
                if e_from != -float('inf') and dist[e_to] < dist[e_from] + e_cost:
                    dist[e_to] = dist[e_from] + e_cost
                    update = True
        if not update:
            flg = 1
            break
    return dist, flg

n,m,p = LI()
edge = []
for _ in range(m):
    a,b,c = LI()
    edge.append([a-1,b-1,c-p])
d,f = Bellman_Ford(edge,n,0)
if d[-1] < 0:
    print(0)
elif not f:
    print(-1)
else:
    print(d[-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

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

cost = [-f_inf] * N
cost[0] = 0

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt > N: cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)

solve(1, 1)

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

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys
sys.setrecursionlimit(10000000)

f_inf = float("inf")

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

cost = [-f_inf] * N
# cost = np.empty(N, dtype = int) - f_inf
cost[0] = 0

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

#     if not(pos in ABC_d): return

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

def solve(pos, cnt):
    global cost

    if not(pos in ABC_d): return
    if cnt > N: cost[pos-1] = f_inf;
    # print (pos, cnt, N, cost[pos - 1])
    for B, C in ABC_d[pos]:
        # print (cost[B - 1], cost[pos - 1] + C)
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1)


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

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

Submission status: Time Limit Exceeded

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

f_inf = float("inf")

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

cost = [-f_inf] * N
# cost = np.empty(N, dtype = int) - f_inf
cost[0] = 0

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

    if not(pos in ABC_d): return

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

# def solve(pos, cnt):
#     global cost

#     if not(pos in ABC_d): return

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


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

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

Submission status: Time Limit Exceeded

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

f_inf = float("inf")

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

cost = [-f_inf] * N
# cost = np.empty(N, dtype = int) - f_inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return

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


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

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

Submission status: Time Limit Exceeded

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

f_inf = float("inf")

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

cost = [-f_inf] * N
# cost = np.empty(N, dtype = int) - f_inf
cost[0] = 0

def solve(pos, already):
    global cost

    if not(pos in ABC_d): return

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


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

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