Problem:


Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000 

1≤M≤min(N(N-1),2000) 

1≤a_i,b_i≤N (1≤i≤M) 

a_i≠b_i (1≤i≤M) 

a_i≠a_j or b_i≠b_j (1≤i<j≤M) 

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:  

N M  
a_1 b_1 c_1  
a_2 b_2 c_2
:  
a_M b_M c_M  

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.  

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000



Sample input:
3 3
1 2 4
2 3 3
1 3 5


Sample output:
7

Submission status: Runtime Error

Solution code:
N, M = map(int,input().split())
tree = {}

for i in range(M):
    a, b, c = map(int, input().split())
    v= tree.get(a,[])
    v.append([b, c])
    tree[a] = v

def has_loop(tree):
    pass

m = []
def cost(v, c, visited):
    if v in visited:
        print('inf')
        exit()
    b = tree.get(v, None)
    if b is None:
        return 
    elif len(b) == 1 and tree.get(b[0][0],None) == None:
        j = c+b[0][1]
        m.append(j)
    else:
        for b, c2 in b: 
            cost(b, c+c2, visited + [v])

if has_loop(tree):
    print('inf')
    exit()

cost(1, 0, [])
print(max(m))

Submission status: Runtime Error

Solution code:
N, M = map(int,input().split())
tree = {}

for i in range(M):
    a, b, c = map(int, input().split())
    v= tree.get(a,[])
    v.append([b, c])
    tree[a] = v

def has_loop(tree):
    pass

m = []
def cost(v, c, visited):
    if v in visited:
        print('inf')
        exit()
    global m
    b = tree[v]
    if len(b) == 1 and tree.get(b[0][0],None) == None:
        j = c+b[0][1]
        m.append(j)
    else:
        for b, c2 in b: 
            cost(b, c+c2, visited + [v])

if has_loop(tree):
    print('inf')
    exit()

cost(1, 0, [])
print(max(m))

Submission status: Runtime Error

Solution code:
# Score Attack
n,m =  list(map(int, input().split()))

a = []
b = []
c = []
for i in range(n):
    ia,ib,ic = list(map(int, input().split())) 
    a.append(ia)
    b.append(ib)
    c.append(-ic)


import sys
INF = sys.maxsize

dist = [INF for i in range(n)]
dist[0] = 0

for l in range(n-1):
    for i in range(m):
        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] 

ans = dist[n - 1];

negative = [False for i in range(n) ]

for loop in range(n):
    for i in range(m):
        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]):
    print("inf")
else:
    print(-ans)

Submission status: Runtime Error

Solution code:
def max_score(edge,N):
    inf =float("inf")
    w = [-inf for i in range(int(N)+1)]
    w[1] = 0;
    
    while True:
        update = False
        negative = False
        for e in edge:
        
 
            if e[0] > e[1] and e[2]>0:
       
                #update = True
                negative = True
                break

            elif w[e[0]] != -inf and w[e[1]] < w[e[0]]+e[2] and e[0] < e[1]:
                
                w[e[1]] = w[e[0]]+e[2]
              
                update = True

        if not update:
            break

        if not negative:
            return w[int(N)]
        else:
            return "inf"


N, M = raw_input().split()
edge = []
for i in range(int(M)):
    edge.append(map(int,raw_input().split()))#appendに配列いれると二次元になる．
#print edge
print max_score(edge,int(N))

Submission status: Runtime Error

Solution code:
import sys

sys.stdin = open('d1.in')

inf = 10 ** 20


def solve(n, m, weights):
    score = [-inf] * n
    score[0] = 0
    pred = [-1] * n

    for step in range(n):
        for edge, c in weights.items():
            a, b = edge
            if score[b] < score[a] + c:
                score[b] = score[a] + c
                pred[b] = a

    b = n - 1
    while b != 0:
        a = pred[b]
        c = weights[(a, b)]
        if score[b] < score[a] + c:
            return 'inf'
        b = a
    return score[n-1]


def solve2(n, m, weights):
    score = [-inf] * n
    score[0] = 0
    pred = [-1] * n

    for step in range(n):
        for edge, c in weights.items():
            a, b = edge
            if score[b] < score[a] + c:
                score[b] = score[a] + c
                pred[b] = a

    res = score[n-1]

    for step in range(n):
        for edge, c in weights.items():
            a, b = edge
            if score[b] < score[a] + c:
                score[b] = score[a] + c
                pred[b] = a

    if res < score[n-1]:
        return 'inf'
    return res


def main():
    n, m = map(int, input().split())
    weights = {}
    for _ in range(m):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        weights[(a, b)] = c

    res = solve2(n, m, weights)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

N, M = map(int, input().split())
score_list = [-float("inf")] * (N + 1)
score_list[1] = 0
m_list = []
for i in range(M):
    m_list.append(list(map(int, input().split())))

m_list.sort(key=lambda x: x[0])
score_keep = 0
for count in [0, 1]:
    for x in m_list:
        if score_list[x[0]] + x[2] > score_list[x[1]]:
            score_list[x[1]] = score_list[x[0]] + x[2]
    if count == 0:
        score_keep = score_list[N]

if score_keep == score_list[N]:
    print(int(score_list[N]))
else:
    print("inf")

Submission status: Runtime Error

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

from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import depth_first_order,bellman_ford
import numpy as np
from time import process_time as timer

G = lil_matrix((N,N), dtype='i4')

for i in range(M):
  a,b,c = map(int, input().split())
  G[a-1,b-1] = -c

# remove nodes unreachable from goal or start
n1 = set(depth_first_order(G, 0, return_predecessors=False))
n2 = set(depth_first_order(G.T, N-1, return_predecessors=False))
n = n1&n2
# N = len(nodes)
# nodes.sort()
# G = G[np.ix_(nodes,nodes)]

try:
  dist = bellman_ford(G,list(n))
  print(-int(dist[0,N-1]))
except NegativeCycleError:
  print('inf')

Submission status: Runtime Error

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

from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import *
import numpy as np
from time import process_time as timer

G = lil_matrix((N,N), dtype='i4')

for i in range(M):
  a,b,c = map(int, input().split())
  G[a-1,b-1] = -c

# remove nodes unreachable from goal or start
n1 = set(depth_first_order(G, 0, return_predecessors=False))
n2 = set(depth_first_order(G.T, N-1, return_predecessors=False))
n = n1&n2
# N = len(nodes)
# nodes.sort()
# G = G[np.ix_(nodes,nodes)]

try:
  dist = bellman_ford(G,list(n))
  print(-int(dist[0,N-1]))
except NegativeCycleError:
  print('inf')

Submission status: Runtime Error

Solution code:
import sys

n, m = map(int, input().split())
sys.setrecursionlimit(n)
edges = [set() for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    edges[a - 1].add((b - 1, c))

NINF = float('-inf')
dists = [NINF for _ in range(n)]
dists[0] = 0


def trace(v, updated):
    updated[v] = True
    for b, c in edges[v]:
        if not updated[b]:
            trace(b, updated)


def bellman_ford():
    for i in range(n - 1):
        updated = False
        for j in range(n):
            dj = dists[j]
            if dj == NINF:
                continue
            for b, c in edges[j]:
                if dists[b] >= dj + c:
                    continue
                dists[b] = dj + c
                updated = True
        if not updated:
            return dists[-1]

    n_updated = [False] * n
    for j in range(n):
        if n_updated[j]:
            continue
        dj = dists[j]
        if dj == NINF:
            continue
        for b, c in edges[j]:
            if dists[b] < dj + c:
                trace(b, n_updated)

    return 'inf' if n_updated[-1] else dists[-1]


print(bellman_ford())

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
edges = [set() for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    edges[a - 1].add((b - 1, c))

NINF = float('-inf')
dists = [NINF for _ in range(n)]
dists[0] = 0


def trace(v, updated):
    updated[v] = True
    for b, c in edges[v]:
        if not updated[b]:
            trace(b, updated)


def bellman_ford():
    for i in range(n - 1):
        updated = False
        for j in range(n):
            dj = dists[j]
            if dj == NINF:
                continue
            for b, c in edges[j]:
                if dists[b] >= dj + c:
                    continue
                dists[b] = dj + c
                updated = True
        if not updated:
            return dists[-1]

    n_updated = [False] * n
    for j in range(n):
        if n_updated[j]:
            continue
        dj = dists[j]
        if dj == NINF:
            continue
        for b, c in edges[j]:
            if dists[b] < dj + c:
                trace(b, n_updated)

    return 'inf' if n_updated[-1] else dists[-1]


print(bellman_ford())

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for x in range(m)]
nodes = [[] for x in range(n + 1)]

for a, b, c in abc:
    nodes[a].append([a, b, -c])

costs = [None for x in range(n + 1)]
costs[1] = 0
flg = True
for i in range(n):
    for node in nodes[1:]:
        for a, b, c in node:
            if costs[b] == None or costs[b] > costs[a] + c:
                flg = False
                costs[b] = costs[a] + c
            else:
                costs[b] = costs[b]
    if flg:
        print(-costs[n])
        break
    flg = True
else:
    print("inf")

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for x in range(m)]
nodes = [[] for x in range(n + 1)]

for a, b, c in abc:
    nodes[a].append([a, b, c])

costs = [None for x in range(n + 1)]
costs[1] = 0
flg = True
for i in range(n):
    for node in nodes[1:]:
        for a, b, c in node:
            if costs[b] == None or costs[b] < costs[a] + c:
                flg = False
                costs[b] = costs[a] + c
            else:
                costs[b] = costs[b]
    if flg:
        print(costs[n])
        break
    flg = True
else:
    print("inf")

Submission status: Runtime Error

Solution code:
import sys
N,M=map(int, input().split())
a=[]
b=[]
c=[]
for m in range (0,M):
  A,B,C=map(int, input().split() )
  a+=[A]
  b+=[B]
  c+=[C]
V=[0]+[-10**12]*(N-1)# iに到達するときの最大得点
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
      V[b[m]-1]=V[a[m]-1]+c[m]
 
moji2=[0]*N
for n in range(N):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji2[b[m]-1]=1
      if moji2[N-1]:
        print("inf")
        sys.exit()
print(V[N-1])

Submission status: Runtime Error

Solution code:
mport sys
N,M=map(int, input().split())
a=[]
b=[]
c=[]
for m in range (0,M):
  A,B,C=map(int, input().split() )
  a+=[A]
  b+=[B]
  c+=[C]
V=[0]+[-10**12]*(N-1)# iに到達するときの最大得点
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
      V[b[m]-1]=V[a[m]-1]+c[m]
 
moji2=[0]*N
for n in range(N):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji2[b[m]-1]=1
      if moji2[N-1]:
        print("inf")
        sys.exit()
print(V[N-1])

Submission status: Runtime Error

Solution code:
mport sys
N,M=map(int, input().split())
a=[]
b=[]
c=[]
for m in range (0,M):
  A,B,C=map(int, input().split() )
  a+=[A]
  b+=[B]
  c+=[C]
V=[0]+[-10**12]*(N-1)# iに到達するときの最大得点
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
      V[b[m]-1]=V[a[m]-1]+c[m]
 
moji2=[0]*N
for n in range(N):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:#共に有限の時はやる
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji2[b[m]-1]=1
      if moji2[N-1]:
        print("inf")
        sys.exit()
else:
  print(V[N-1])

Submission status: Runtime Error

Solution code:
class Edge:
    def __init__(self, fromE, to, cost):
        self.fromE = fromE
        self.to = to
        self.cost = cost


def min_path(_s):
    d[_s] = 0
    while True:
        update = False
        for i in range(0, N):
            edge = abc[i]
            if d[edge.fromE] != float("inf") and d[edge.to] > d[edge.fromE] + edge.cost:
                d[edge.to] = d[edge.fromE] + edge.cost
                update = True
        if not update:
            break;


def find_negative_loop():
    d = [0 for i in range(N + 1)]
    for i in range(0, N):
        for j in range(0, M):
            edge = abc[j]
            if d[edge.to] > d[edge.fromE] + edge.cost:
                d[edge.to] = d[edge.fromE] + edge.cost

                if i == N - 1:
                    return True

    return False


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

abc = []

for i in range(M):
    a, b, c = list(map(int, input().split()))
    abc.append(Edge(a, b, -c))

if find_negative_loop():
    print('inf')
else:
    d = [float("inf") for i in range(N + 1)]
    min_path(1)
    ans = -d[N]
    print(ans)

Submission status: Runtime Error

Solution code:
# Bellman-Ford
n, m = map(int, raw_bellman-input().split())
a, b, c = [], [], []
for i in xrange(m):
    at, bt, ct = map(int, raw_input().split())
    a.append(at - 1)
    b.append(bt - 1)
    c.append(ct)
# step1 : initialize
point = [-1e9 * m - 1] * n
point[0] = 0
pointl = [None] * n
# step2 : relaxation
for i in xrange(n-1):
    for j in xrange(m):
        if point[b[j]] < point[a[j]] + c[j]:
            point[b[j]] = point[a[j]] + c[j]
            pointl[b[j]] = a[j]
        print point
# step3 : check
flag = True
for j in xrange(m):
    if point[a[j]] + c[j] > point[b[j]]:
        flag = False
        break
if flag:
    print(point[n-1])
else:
    print("inf")

Submission status: Runtime Error

Solution code:
from collections import defaultdict
MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = -(10 ** 100)

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = defaultdict(list)
    result = INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]

        if (pos == N - 1):
            result = max(result, cost)

        if (pos in visited):
            visited_cost = visited[pos][0]
            visited_cnt = visited[pos][1]
            if (visited_cost >= cost):
                continue
            if (visited_cnt >= 2 * MAX_M):
                return (0, False)
            visited[pos] = [cost, visited_cnt + 1]
        else:
            visited[pos] = [cost, 0]


        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]
            if (nxt not in visited):
                que.append([nxt, nxt_cost + cost])
            elif(nxt_cost + cost > visited[nxt][0]):
                que.append([nxt, nxt_cost + cost])
    return (result, True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = defaultdict(list)
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        print ('inf')
    else:

Submission status: Runtime Error

Solution code:
from collections import defaultdict
MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = -(10 ** 100)

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = defaultdict(list)
    result = INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]

        if (pos in visited):
            visited_cost = visited[pos][0]
            visited_cnt = visited[pos][1]
            if (visited_cost >= cost):
                continue
            if (visited_cnt >= (10 ** 6)):
                return (0, False)
            visited[pos] = [cost, visited_cnt + 1]
        else:
            visited[pos] = [cost, 1]

        if (pos == N - 1):
            result = max(result, cost)

        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]
            if (nxt not in visited):
                que.append([nxt, nxt_cost + cost])
            elif(nxt_cost + cost > visited[nxt][0]):
                que.append([nxt, nxt_cost + cost])
    return (result, True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = defaultdict(list)
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        assert(False)
    else:
        print (res)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = -(10 ** 100)

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = defaultdict(list)
    result = INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]

        if (pos in visited):
            visited_cost = visited[pos][0]
            visited_cnt = visited[pos][1]
            if (visited_cost >= cost):
                continue
            if (visited_cnt >= MAX_N):
                return (0, False)
            visited[pos] = [cost, visited_cnt + 1]
        else:
            visited[pos] = [cost, 1]

        if (pos == N - 1):
            result = max(result, cost)

        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]
            if (nxt not in visited):
                que.append([nxt, nxt_cost + cost])
            elif(nxt_cost + cost > visited[nxt][0]):
                que.append([nxt, nxt_cost + cost])
    return (result, True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = defaultdict(list)
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        assert(False)
    else:
        print (res)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = -(10 ** 100)

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = defaultdict(list)
    result = INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]

        if (pos in visited):
            visited_cost = visited[pos][0]
            visited_cnt = visited[pos][1]
            if (visited_cost >= cost):
                continue
            if (visited_cnt >= 5 * MAX_N):
                return (0, False)
            visited[pos] = [cost, visited_cnt + 1]
        else:
            visited[pos] = [cost, 1]

        if (pos == N - 1):
            result = max(result, cost)

        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]
            if (nxt not in visited):
                que.append([nxt, nxt_cost + cost])
            elif(nxt_cost + cost > visited[pos][0]):
                que.append([nxt, nxt_cost + cost])
    return (result, True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = defaultdict(list)
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        assert(False)
    else:
        print (res)

Submission status: Runtime Error

Solution code:
def main():
    N, M = map(int, input().split())
    global abc
    abc = [None] * M
    for i in range(M):
        abc[i] = tuple(map(int, input().split()))
    global point
    point = -1000000000 * 2000
    point = dfs(0, N, 0)
    print(point)

def dfs(s, e, p):
    global point
    if abc[s][0] == 1:
        p = 0
    if abc[s][1] == 1:
        return 'inf'
    else:
        p += abc[s][2]
        if abc[s][1] == e:
            point = max(point, p)
        if len(abc) > s + 1:
            return dfs(s+1, e, p)
        return max(point, p)

main()

Submission status: Runtime Error

Solution code:
def calc_weight(pw, weights, max_n):
    new_pw = [[]] * max_n
    k = 0
    for p, w in pw:
        if p == len(weights) - 1:
            new_pw[k] = [p, w]
            k += 1
        li = weights[p]
        non_zero = [[i, x] for i, x in enumerate(li) if x != 0]
        for j, x in non_zero:
            new_pw[k] = [j, x + w]
            k += 1
    return new_pw[:k]

N, M = map(int, raw_input().split())
matrix = [[0 for i in range(N)] for j in range(N)]
for i in range(M):
    _a, _b, _c = map(int, raw_input().split())
    matrix[_a - 1][_b - 1] = _c

cur_pw = [[0, 0]]
for i in range(0, N):
    cur_pw = calc_weight(cur_pw, matrix, M)

ans = [[i, j] for i, j in cur_pw if i == N - 1]
non_ans = [[i, j] for i, j in cur_pw if i != N - 1]
if non_ans:
    print "inf"
else:
    ans.sort(key=lambda x:x[1], reverse=True)
    print ans[0][1]

Submission status: Runtime Error

Solution code:
def d():
    n, m = map(int, input().split())

    node = []
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        node.append([ai, bi, ci])
    node = sorted(node, key=lambda n: n[1])
    node = sorted(node, key=lambda n: n[0])
    route = []
    score = None
    for i in node:
        ai, bi, ci = i
        if ai == 1:
            route.append([[ai, bi], ci])
        elif 1 < ai < n:
            temp = []
            for j in route:
                if j[0][-1] == ai:
                    k = [j[0][:],j[1]]
                    k[0].append(bi); k[1]+=ci
                    temp.append(k)
            else:
                route.extend(temp)
        else:
            for j in route:
                if bi in j[0]:
                    print('inf')
                    return
    for i in route:
        if i[0][-1] == n:
            if score == None:
                score = k[1]
            else:
                score = max(score, k[1])
    print(score)
    # print(route)
    pass

d()

Submission status: Runtime Error

Solution code:
def d():
    n, m = map(int, input().split())

    node = []
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        node.append([ai, bi, ci])
    node = sorted(node, key=lambda n: n[1])
    node = sorted(node, key=lambda n: n[0])
    route = []
    score = None
    for i in node:
        ai, bi, ci = i
        if ai == 1:
            route.append([[ai, bi], ci])
        elif 1 < ai < n:
            for j in route:
                if j[0][-1] == ai:
                    k = j[:]
                    k[0].append(bi); k[1]+=ci
                    route.append(k)
        else:
            for j in route:
                if bi in j[0]:
                    print('inf')
                    return
    for i in route:
        if i[0][-1] == n:
            if score == None:
                score = k[1]
            else:
                score = max(score, k[1])
    # print(score)
    # print(route)
    pass

d()

Submission status: Runtime Error

Solution code:
def d():
    n, m = map(int, input().split())

    node = []
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        node.append([ai, bi, ci])
    node = sorted(node, key=lambda n: n[1])
    node = sorted(node, key=lambda n: n[0])
    route = []
    score = None
    for i in node:
        ai, bi, ci = i
        if ai == 1:
            route.append([[ai, bi], ci])
        elif 1 < ai < n:
            for j in route:
                if j[0][-1] == ai:
                    k = j[:]
                    k[0].append(bi); k[1]+=ci
                    route.append(k)
        else:
            for j in route:
                if bi in j[0]:
                    print('inf')
                    return
    for i in route:
        if i[0][-1] == n:
            if score == None:
                score = k[1]
            else:
                score = max(score, k[1])
    print(score)
    print(route)
    pass

d()

Submission status: Runtime Error

Solution code:
import sys

def set_enable_goal(cur_node, back_paths, enable_goal):
    if cur_node in back_paths:
        for next_node in back_paths[cur_node]:
            if enable_goal[next_node - 1] == 0:
                enable_goal[next_node - 1] = 1
                set_enable_goal(next_node, back_paths, enable_goal)


N, M = map(int, input().split())
MIN = float('-inf')
INF_LIMIT = 20000000000

back_paths = {}
all_paths = {}
for i in range(M):
    a, b, c = map(int, input().split())
    if b in back_paths:
        back_paths[b].append(a)
    else:
        back_paths[b] = [a]

    if a in all_paths:
        all_paths[a].append((b, c))
    else:
        all_paths[a] = [(b, c)]

enable_goal= [0 for i in range(N)]
enable_goal[N - 1] = 1
set_enable_goal(N, back_paths, enable_goal)

for a, paths in all_paths.items():
    if not enable_goal[a - 1]:
        all_paths[a] = []
    else:
        valid_paths = []
        for b, c in paths:
            if enable_goal[b - 1]:
                valid_paths.append((b, c))
        all_paths[a] = valid_paths


scores = [MIN for i in range(N)]
scores[0] = 0

is_inf = False
for n in range(N):
    for a in range(1, M + 1):
        if a in all_paths:
            for b, c in all_paths[a]:
                if scores[a - 1] + c > INF_LIMIT or scores[a - 1] + c < -INF_LIMIT:
                    is_inf = True
                    break
                else:
                    scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)

# loop check
if not is_inf:
    prev_scores = list(scores)
    for a in range(1, M + 1):
        if a in all_paths:
            for b, c in all_paths[a]:
                scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)
    for p, s in zip(prev_scores, scores):
        if p != s:
            is_inf = True
            break

if is_inf:
    print('inf')
else:
    print(scores[N - 1])

Submission status: Runtime Error

Solution code:
import sys

def set_enable_goal(cur_node, back_paths, enable_goal):
    if cur_node in back_paths:
        for next_node in back_paths[cur_node]:
            if enable_goal[next_node - 1] == 0:
                enable_goal[next_node - 1] = 1
                set_enable_goal(next_node, back_paths, enable_goal)


N, M = map(int, input().split())
MIN = float('-inf')

back_paths = {}
all_paths = {}
for i in range(M):
    a, b, c = map(int, input().split())
    if b in back_paths:
        back_paths[b].append(a)
    else:
        back_paths[b] = [a]

    if a in all_paths:
        all_paths[a].append((b, c))
    else:
        all_paths[a] = [(b, c)]

enable_goal= [0 for i in range(N)]
enable_goal[N - 1] = 1
set_enable_goal(N, back_paths, enable_goal)

for a, paths in all_paths.items():
    if not enable_goal[a - 1]:
        all_paths[a] = []
    else:
        valid_paths = []
        for b, c in paths:
            if enable_goal[b - 1]:
                valid_paths.append((b, c))
        all_paths[a] = valid_paths


scores = [MIN for i in range(N)]
scores[0] = 0

is_inf = False
for n in range(N):
    for a in range(1, M + 1):
        if a in all_paths:
            for b, c in all_paths[a]:
                scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)

# loop check
if not is_inf:
    prev_scores = list(scores)
    for a in range(1, M + 1):
        if a in all_paths:
            for b, c in all_paths[a]:
                scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)
    for p, s in zip(prev_scores, scores):
        if p != s:
            is_inf = True
            break

if is_inf:
    print('inf')
else:
    print(scores[N - 1])

Submission status: Runtime Error

Solution code:
def d():
    n, m = map(int, input().split())

    node = []
    for i in range(m):
        ai, bi, ci = map(int, input().split())
        node.append([ai, bi, ci])
    sorted(node, key=lambda n: n[1])
    sorted(node, key=lambda n: n[0])
    route = []
    score = None
    for i in node:
        ai, bi, ci = i
        if ai == 1:
            route.append([[ai, bi], ci])
        elif 1 < ai < n:
            for j in route:
                if j[0][-1] == ai:
                    k = j[:]
                    k[0].append(bi); k[1]+=ci
                    route.append(k)
        else:
            for j in route:
                if bi in j[0]:
                    print('inf')
                    return
    for i in route:
        if i[0][-1] == n:
            if score == None:
                score = k[1]
            else:
                score = max(score, k[1])
    print(score)
    print(route)
    pass

d()

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for x in range(m)]
 
nodemap = [[] for x in range(n + 1)]
 
for a, b, c in abc:
    nodemap[a].append([a, b, c])

changed = False

calced = [None for x in range(n + 1)]
calced[1] = 0

for i in range(n - 1):
    changed = False
    for nodes in nodemap:
        for node in nodes:
            now, nextnode, addvalue = node
            if calced[nextnode] == None or calced[nextnode] < calced[now] + addvalue:
                if calced[now] != None:
                    calced[nextnode] = calced[now] + addvalue
                changed = True
print("inf" if changed else calced[n])

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for x in range(m)]
 
nodemap = [[] for x in range(n + 1)]
 
for a, b, c in abc:
    nodemap[a].append([a, b, c])

changed = False

calced = [None for x in range(n + 1)]
calced[1] = 0

for i in range(n - 1):
    changed = False
    for nodes in nodemap:
        for node in nodes:
            now, nextnode, addvalue = node
            if calced[nextnode] == None or calced[nextnode] < calced[now] + addvalue:
                calced[nextnode] = calced[now] + addvalue
                changed = True
print("inf" if changed else calced[n])