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: Time Limit Exceeded

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 >= MAX_N):
                continue
            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])
    if (visited[N - 1][1] >= MAX_N):
        return (0, False)
    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:
        print (res)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == '__main__':

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

	a=[]
	b=[]
	c=[]
	for i in range(M):
		a_t, b_t, c_t = map(int, input().split())
		a.append(a_t)
		b.append(b_t)
		# コスト最大を求めたいが，cを正負反転することで最小を求める
		c.append(-c_t)

	# dist[i]には1からiの頂点までの最小コストが入る
	dist=[]
	for j in range(N):
		dist.append(float('inf'));

	dist[0]=0

	for loop in range(N-1):
		for i in range(M):
			if dist[a[i]-1] == float('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 = []

	for i in range(N):
		negative.append(False)

	for loop in range(N):
		for i in range(M):
			if dist[a[i]-1] == float('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: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys
import os
import math

N, M = map(int, input().split())
#print('N', N)
#print('M', M)

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

# 始点から到達不可能な頂点は除去する
visited = [False] * N
Q = [0]
while Q:
    i = Q.pop(0)
    visited[i] = True
    for edge in A[i]:
        to = edge[0]
        if not visited[to]:
            Q.append(to)
# 到達不可能な頂点
unreachable = []
reachable = []
for i in range(N):
    if visited[i]:
        reachable.append(i)
    else:
        unreachable.append(i)
#print('unreach', unreachable)
#for i in unreachable:
#    A[i] = []

dists = [float('inf')] * N
dists[0] = 0
def bellman_ford(A):
    for i in range(N):
        for v in range(N):
            for edge in A[v]:
                to = edge[0]
                cost = edge[1]
                if dists[v] != float('inf') and dists[to] > dists[v] + cost:
                    dists[to] = dists[v] + cost
                    if i == N - 1:
                        return True
    return False

is_loop = bellman_ford(A)

if is_loop:
    old = dists[N-1]
    bellman_ford(A)
    if old == dists[N-1]:
        print(-dists[N - 1])
    else:
        print('inf')
else:
    print(-dists[N-1])

Submission status: Time Limit Exceeded

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]*N# iに到達するときの最大得点
moji=[1]+[0]*(N-1)#infなら0をかえす
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if moji[b[m]-1]:
        V[b[m]-1]=max(V[b[m]-1],V[a[m]-1]+c[m])
      else:
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji[b[m]-1]=1
 
moji2=[0]*N
for n in range(N):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if V[a[m]-1]+c[m]>V[b[m]-1]:
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji2[b[m]-1]=1
    if moji2[a[m]-1]:
      moji2[b[m]-1]=1
if moji2[N-1]:
  print("inf")
else:
  print(V[N-1])

Submission status: Time Limit Exceeded

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]*N# iに到達するときの最大得点
moji=[1]+[0]*(N-1)#infなら0をかえす
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if moji[b[m]-1]:
        V[b[m]-1]=max(V[b[m]-1],V[a[m]-1]+c[m])
      else:
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji[b[m]-1]=1
 
moji2=[0]*N
for n in range(N):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if moji[b[m]-1]:
        if V[a[m]-1]+c[m]>V[b[m]-1]:
          V[b[m]-1]=V[a[m]-1]+c[m]
          moji2[b[m]-1]=1
    if moji2[a[m]-1]:
      moji2[b[m]-1]=1
if moji2[N-1]:
  print("inf")
else:
  print(V[N-1])

Submission status: Time Limit Exceeded

Solution code:
import math

INF = float("inf")

V, E = map(int, input().split())
es = []

for _ in range(E):
    a, b, c = map(int, input().split())
    es.append([a-1, b-1, -c])

d = [INF] * V
d[0] = 0

for _ in range(V - 1):
    updated = False
    for e in es:
        if math.isinf(d[e[0]]):
            continue
        if d[e[1]] > d[e[0]] + e[2]:
            d[e[1]] = d[e[0]] + e[2]
            updated = True
    if not updated:
        break

negative = [False] * V

for _ in range(V):
    for e in es:
        if math.isinf(d[e[0]]):
            continue
        if d[e[1]] > d[e[0]] + e[2]:
            negative[e[1]] = True
            d[e[1]] = d[e[0]] + e[2]
        elif negative[e[1]]:
            d[e[1]] = True
print(-d[V-1] if not negative[V-1] else "inf")

Submission status: Time Limit Exceeded

Solution code:
import math

INF = float("inf")

V, E = map(int, input().split())
edge = []

for _ in range(E):
    a, b, c = map(int, input().split())
    edge.append([a, b, -c])

d = [INF] * (V + 1)
d[1] = 0

for _ in range(V-1):
    update = False
    for e in edge:
        if not math.isinf(d[e[0]]) and d[e[1]] > d[e[0]] + e[2]:
            update = True
            d[e[1]] = d[e[0]] + e[2]
    if not update:
        break

negative = [False] * (V + 1)

for _ in range(V):
    for e in edge:
        if math.isinf(d[e[0]]):
            continue
        if d[e[1]] > d[e[0]] + e[2]:
            negative[e[1]] = True
            d[e[1]] = d[e[0]] + e[2]
        elif negative[e[1]]:
            d[e[1]] = True
print(-d[V] if not negative[V] else "inf")

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))
    g[i][2] *= -1

dist = np.zeros(n + 1)
for i in range(2, n + 1):
    dist[i] = float('inf')

for loop in range(n - 1):
    for i in range(m):
        if dist[g[i][0]] != 'inf':
            if dist[g[i][1]] > dist[g[i][0]] + g[i][2]:
                dist[g[i][1]] = dist[g[i][0]] + g[i][2]

ans = dist[n]

negative = np.zeros(n + 1)

for loop in range(n):
    for i in range(m):
        if dist[g[i][0]] != 'inf':
            if dist[g[i][1]] > dist[g[i][0]] + g[i][2]:
                dist[g[i][1]] = dist[g[i][0]] + g[i][2]
                negative[g[i][1]] = 1
            if negative[g[i][0]] == 1:
                negative[g[i][1]] = 1
        if negative[n] == 1:
            break
    if negative[n] == 1:
        break
if negative[n] == 1:
    print 'inf'
else:
    print int(-ans)

Submission status: Time Limit Exceeded

Solution code:
#coding=UTF-8


mozir=input()
hyo=mozir.split(' ')

N=int(hyo[0])
M=int(hyo[1])

A=[]
B=[]
Cost=[]
for idx in range(0,M,1):
    mozir=input()
    hyo=mozir.split(' ')
    A.append(int(hyo[0])-1)
    B.append(int(hyo[1])-1)
    Cost.append(int(hyo[2]))
    
#先ず得点が正になるループを探す
eipap=False
for idx in range(0,N,1):
    tansaku=[(idx,0)]
    while len(tansaku) > 0:
        next_tansaku=[]
        for mono in tansaku:
            for idy in range(0,M,1):
                if A[idy]==mono[0]:
                    #add only if better
                    appendp=True
                    for butu in next_tansaku:
                        if B[idy] == butu[0]:
                            #already exsists
                            appendp=False
                            if butu[1] > mono[1]+Cost[idy]:
                                butu[1]=mono[1]+Cost[idy]
                    if appendp:
                        next_tansaku.append([B[idy],mono[1]+Cost[idy]])
        #print(next_tansaku)
        
        for tenn in next_tansaku:
            if tenn[0]==idx and tenn[1]>0:
                eipap=True
                break

        if eipap:
            break
        else:
            tansaku=next_tansaku

if eipap:
    print('inf')
else:
    #無ければ、普通の経路探索のようなことをする
    tmp_score=[None]*N #マイナス点のときもある
    tmp_score[0]=0
    tansaku=[0]
    while len(tansaku) > 0:
        next_tansaku=[]
        for mono in tansaku:
            for idy in range(0,M,1):
                if A[idy]==mono:
                    kouho_ten=tmp_score[mono]+Cost[idy]
                    if tmp_score[B[idy]] == None or kouho_ten > tmp_score[B[idy]]:
                        tmp_score[B[idy]]=kouho_ten
                        next_tansaku.append(B[idy])

        tansaku=next_tansaku

    print(tmp_score[N-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))
    g[i][2] *= -1

dist = np.zeros(n + 1)
for i in range(2, n + 1):
    dist[i] = float('inf')

for loop in range(n - 1):
    for i in range(m):
        if dist[g[i][0]] != 'inf':
            if dist[g[i][1]] > dist[g[i][0]] + g[i][2]:
                dist[g[i][1]] = dist[g[i][0]] + g[i][2]

ans = dist[n]

negative = np.zeros(n + 1)

for loop in range(n):
    for i in range(m):
        if dist[g[i][0]] != 'inf':
            if dist[g[i][1]] > dist[g[i][0]] + g[i][2]:
                dist[g[i][1]] = dist[g[i][0]] + g[i][2]
                negative[g[i][1]] = 1
            if negative[g[i][0]] == 1:
                negative[g[i][1]] = 1
if negative[n] == 1:
    print 'inf'
else:
    print int(-ans)

Submission status: Time Limit Exceeded

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]*N# iに到達するときの最大得点
moji=[1]+[0]*(N-1)#infなら0をかえす
 
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if moji[b[m]-1]:
        V[b[m]-1]=max(V[b[m]-1],V[a[m]-1]+c[m])
      else:
        V[b[m]-1]=V[a[m]-1]+c[m]
        moji[b[m]-1]=1

W=V[:]
for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if moji[a[m]-1]:#共に有限の時はやる
      if moji[b[m]-1]:
        W[b[m]-1]=max(W[b[m]-1],W[a[m]-1]+c[m])
      else:
        W[b[m]-1]=W[a[m]-1]+c[m]
        moji[b[m]-1]=1
if V[N-1]==W[N-1]:
  print(V[N-1])
else:
  print("inf")

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

import sys
from collections import defaultdict

if __name__ == "__main__":
    N, M = map(int, input().split(" "))

    V = set()
    E = []
    for i in range(M):
        a, b, c = map(int, input().split(" "))
        V.add(a)
        V.add(b)
        E.append((a, b, -c))

    dist = defaultdict(lambda :10**20 + 1)
    pre = {}
    dist[1] = 0


    for i in range(1, len(V)):
        for edge in E:
            u = edge[0]
            v = edge[1]

            if dist[v] > dist[u] + edge[2]:
                dist[v] = dist[u] + edge[2]
                pre[v] = u

    is_cycle = False
    cycle_node = []
    for edge in E:
        u = edge[0]
        v = edge[1]
        if dist[u] + edge[2] < dist[v]:
            is_cycle = True
            cycle_node.append(u)

    is_inf = False
    if is_cycle:
        next_node = N
        route = []
        while next_node != 1:
            route.append(next_node)
            next_node = pre[N]
        route.append(1)

        for n in cycle_node:
            if n in route:
                is_inf = True
                break

    if is_inf:
        print ("inf")
    else:
        print (-dist[N])

Submission status: Time Limit Exceeded

Solution code:
#coding=UTF-8


mozir=input()
hyo=mozir.split(' ')

N=int(hyo[0])
M=int(hyo[1])

A=[]
B=[]
Cost=[]
for idx in range(0,M,1):
    mozir=input()
    hyo=mozir.split(' ')
    A.append(int(hyo[0])-1)
    B.append(int(hyo[1])-1)
    Cost.append(int(hyo[2]))
    
#先ず得点が正になるループを探す
eipap=False
for idx in range(0,N,1):
    tansaku=[(idx,0)]
    while len(tansaku) > 0:
        next_tansaku=[]
        for mono in tansaku:
            for idy in range(0,M,1):
                if A[idy]==mono[0]:
                    next_tansaku.append((B[idy],mono[1]+Cost[idy]))

        ##remove less hopeful thing
        tmp_tan=sorted(next_tansaku,key=lambda po:po[1])
        kirei_next_tan=sorted(tmp_tan,key=lambda po:po[0])
        #print(kirei_next_tan)
        
        for tenn in kirei_next_tan:
            if tenn[0]==idx and tenn[1]>0:
                eipap=True
                break

        if eipap:
            break
        else:
            tansaku=kirei_next_tan

if eipap:
    print('inf')
else:
    #無ければ、普通の経路探索のようなことをする
    tmp_score=[None]*N #マイナス点のときもある
    tmp_score[0]=0
    tansaku=[0]
    while len(tansaku) > 0:
        next_tansaku=[]
        for mono in tansaku:
            for idy in range(0,M,1):
                if A[idy]==mono:
                    kouho_ten=tmp_score[mono]+Cost[idy]
                    if tmp_score[B[idy]] == None or kouho_ten > tmp_score[B[idy]]:
                        tmp_score[B[idy]]=kouho_ten
                        next_tansaku.append(B[idy])

        tansaku=next_tansaku

    print(tmp_score[N-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))

graph = {}
for i in g:
    if i[0] not in graph:
        graph[i[0]] = [[i[1], i[2]]]
    else:
        graph[i[0]].append([i[1], i[2]])

table = np.zeros(n + 1) + 0.5
table[1] = 0
fp = [1]
for i in range(n):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n and fp not in [j[0]]:
                        fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
max = int(table[n])
fp.append(n)
flag = 0
for i in range(1):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
                if max < int(table[n]):
                    print"inf"
                    flag = 1
                    break
        if flag == 1:
            break

    if flag == 1:
        break
if flag != 1:
    print int(table[n])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))

graph = {}
for i in g:
    if i[0] not in graph:
        graph[i[0]] = [[i[1], i[2]]]
    else:
        graph[i[0]].append([i[1], i[2]])

table = np.zeros(n + 1) + 0.5
table[1] = 0
fp = [1]
for i in range(n):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n and fp not in [j[0]]:
                        fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
max = int(table[n])
fp.append(n)
flag = 0
for i in range(2):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
                if max < int(table[n]):
                    print"inf"
                    flag = 1
                    break
        if flag == 1:
            break

    if flag == 1:
        break
if flag != 1:
    print int(table[n])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))

graph = {}
for i in g:
    if i[0] not in graph:
        graph[i[0]] = [[i[1], i[2]]]
    else:
        graph[i[0]].append([i[1], i[2]])

table = np.zeros(n + 1) + 0.5
table[1] = 0
fp = [1]
for i in range(n):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n and fp not in [j[0]]:
                        fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
max = int(table[n])
fp.append(n)
flag = 0
for i in range(3):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
                if max < int(table[n]):
                    print"inf"
                    flag = 1
                    break
        if flag == 1:
            break

    if flag == 1:
        break
if flag != 1:
    print int(table[n])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, m = map(int, raw_input().split())
g = []
for i in range(m):
    g.append(map(int, raw_input().split()))

graph = {}
for i in g:
    if i[0] not in graph:
        graph[i[0]] = [[i[1], i[2]]]
    else:
        graph[i[0]].append([i[1], i[2]])

table = np.zeros(n + 1) + 0.5
table[1] = 0
fp = [1]
for i in range(n):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n and fp not in [j[0]]:
                        fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
max = int(table[n])
fp.append(n)
flag = 0
for i in range(n):
    for k in fp:
        if k in graph.keys():
            for j in graph[k]:
                if table[j[0]] < table[k] + j[1]:
                    table[j[0]] = table[k] + j[1]
                    fp.append(j[0])
                if table[j[0]] == 0.5:
                    table[j[0]] = table[k] + j[1]
                    if j[0] != n:
                        fp.append(j[0])
                if max < int(table[n]):
                    print"inf"
                    flag = 1
                    break
        if flag == 1:
            break

    if flag == 1:
        break
if flag != 1:
    print int(table[n])

Submission status: Time Limit Exceeded

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

    MAP = [[0]*N for x in range(N)]
    E = []
    for m in range(M):
        a,b,c = map(int, input().split())
        MAP[a-1][b-1] = c
        E.append((a-1,b-1,c))

    dp = [[-float('inf')]*N for x in range(2*N+1)]
    dp[0][0] = 0
    count = 1
    for i in range(2*N):  # N
        # for n in range(N):
        #     print(count,n)
        #     dp[count][n] = max(dp[count][n], dp[count-1][n])
        for e in E:
            a,b,c = e
            dp[count][b] = max(dp[count][b], dp[count-1][b], dp[count-1][a] + c)
        count += 1

    # print(dp[N-1][N-1], dp[N][N-1])
    if dp[2*N][N-1] == dp[N-1][N-1]:
        print(dp[N-1][N-1])
    else:
        print('inf')


if __name__ == "__main__":
    # global stime
    # stime = time.clock()
    main()

Submission status: Time Limit Exceeded

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

A = [0 for i in range(M)]
B = [0 for i in range(M)]
C = [0 for i in range(M)]
INF = 1000*1000*1000*1000*1000
d = [-INF for i in range(N)]
d[0] = 0

for i in range(M):
    A[i], B[i], C[i] = map(int, input().split())
    A[i] -= 1
    B[i] -= 1

for i in range(N-1):
    for j in range(M):
        d[B[j]] = d[A[j]] + C[j] if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j] else d[B[j]]

ans = d[N-1]

for i in range(N-1):
    for j in range(M):
        d[B[j]] = d[A[j]] + C[j] if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j] else d[B[j]]

if (ans < d[N-1]):
    print("inf")
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys

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

nodes = [[] for i in range(N)]

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

visited = [False for i in range(N)]
score = [None for i in range(N)]
from_node = [[] for i in range(N)]

visited[0] = True
score[0] = 0

current = [0]

while len(current) > 0:
    next_nodes = []
    for x in current:
        for e in nodes[x]:
            if not visited[e[0]]:
                visited[e[0]] = True
                score[e[0]] = score[x] + e[1]
                from_node[e[0]].append(x)
                next_nodes.append(e[0])
            else:
                if score[x] + e[1] > score[e[0]]:
                    if e[0] == N - 1 and x in from_node[e[0]]:
                        print('inf')
                        sys.exit()
                    score[e[0]] = score[x] + e[1]
                    if x not in from_node[e[0]]:
                        from_node[e[0]].append(x)
                    next_nodes.append(e[0])

    current = next_nodes

print(score[N - 1])

Submission status: Time Limit Exceeded

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

A = [0 for i in range(M)]
B = [0 for i in range(M)]
C = [0 for i in range(M)]
INF = 1000*1000*1000*1000*1000
d = [-INF for i in range(N)]
d[0] = 0

for i in range(M):
    A[i], B[i], C[i] = map(int, input().split())
    A[i] -= 1
    B[i] -= 1

for i in range(N-1):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

ans = d[N-1]

for i in range(N-1):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

if (ans < d[N-1]):
    print("inf")
else:
    print(ans)

Submission status: Time Limit Exceeded

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

A = [0 for i in range(M)]
B = [0 for i in range(M)]
C = [0 for i in range(M)]
INF = 1000*1000*1000*1000*1000
d = [-INF for i in range(N)]
d[0] = 0

for i in range(M):
    A[i], B[i], C[i] = map(int, input().split())
    A[i] -= 1
    B[i] -= 1

for i in range(N):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

ans = d[N-1]

for i in range(N):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

if (ans < d[N-1]):
    print("inf")
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter
 
inf = 1<<60
 
def solve():
    N, M = map(int, input().split())
    edges = [None]*M
 
    for i in range(M):
        ui, vi, ci = map(int, sys.stdin.readline().split())
        edges[i] = (ui-1, vi-1, -ci)
 
    ans = Bellmanford(N, M, edges)
 
    if ans is not None:
        print(-ans)
    else:
        print('inf')
 
def Bellmanford(N, M, edges):
    dist = [inf]*N
    dist[0] = 0
    flag = True
 
    while True:
        flag = False
 
        for (u, v, c) in edges:
            if dist[u] != inf and dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True
 
        # print(dist)
 
        if not flag or dist[0] < 0:
            break
 
    if dist[0] >= 0:
        return dist[N - 1]
    else:
        return None
 
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
# D
from collections import deque

# create graph
G = dict()
G_inv = dict()
N, M = map(int, input().split())
for n in range(1, N+1):
    G[n] = dict()
    G_inv[n] = dict()

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

# value
values = [-1000000000*2000]*(N+1)
values[1] = 0

reachable = [0]*(N+1)
reachable[N] = 1
# find reachble points
dr = deque([N])
while len(dr) > 0:
    b = dr.popleft()
    for a in G_inv[b].keys():
        if reachable[a] == 0:
            reachable[a] = 1
            dr.append(a)

# BFS
inc_cnt = 0
d = deque([1])
while len(d) > 0:
    a = d.popleft()
    for b in G[a].keys():
        if values[b] < values[a] + G[a][b]:
            values[b] = values[a] + G[a][b]
            if reachable[b] == 1:
                inc_cnt += 1
            d.append(b)
    if inc_cnt > 2000:
        break
if inc_cnt > 2000:
    print('inf')
else:
    print(values[N])

Submission status: Time Limit Exceeded

Solution code:
# D
from collections import deque

# create graph
G = dict()
N, M = map(int, input().split())
for n in range(1, N+1):
    G[n] = dict()

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

# value
values = [-1000000000*2000]*(N+1)
values[1] = 0
# BFS
inc_cnt = 0
d = deque([1])
while len(d) > 0:
    a = d.popleft()
    for b in G[a].keys():
        if values[b] < values[a] + G[a][b]:
            values[b] = values[a] + G[a][b]
            if b == N:
                inc_cnt += 1
            d.append(b)
    if inc_cnt > 50:
        break
if inc_cnt > 50:
    print('inf')
else:
    print(values[N])

Submission status: Time Limit Exceeded

Solution code:
# D
from collections import deque

# create graph
G = dict()
N, M = map(int, input().split())
for n in range(1, N+1):
    G[n] = dict()

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

# value
values = [-1000000000*2000]*(N+1)
values[1] = 0
# BFS
inc_cnt = 0
d = deque([1])
while len(d) > 0:
    a = d.popleft()
    for b in G[a].keys():
        if values[b] < values[a] + G[a][b]:
            values[b] = values[a] + G[a][b]
            if b == N:
                inc_cnt += 1
            d.append(b)
    if inc_cnt > 100:
        break
if inc_cnt > 100:
    print('inf')
else:
    print(values[N])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter

inf = 1<<60

def solve():
    N, M = map(int, input().split())
    edges = [None]*M

    for i in range(M):
        ui, vi, ci = map(int, sys.stdin.readline().split())
        edges[i] = (ui-1, vi-1, -ci)

    ans = Bellmanford(N, M, edges)

    if ans is not None:
        print(-ans)
    else:
        print('inf')

def Bellmanford(N, M, edges):
    dist = [inf]*N
    dist[0] = 0
    flag = True

    while True:
        flag = False

        for (u, v, c) in edges:
            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True

        # print(dist)

        if not flag or dist[0] < 0:
            break

    if dist[0] >= 0:
        return dist[N - 1]
    else:
        return None

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
INF = float("inf")

start = []
end = []
weight = []
node_cost = [-INF] * N
for _ in range(M):
    a, b, c = map(int, input().split())
    start.append(a - 1)
    end.append(b - 1)
    weight.append(c)

node_cost[0] = 0
for _ in range(N - 1):
    for i in range(M):
        new_cost = node_cost[start[i]] + weight[i]
        if new_cost > node_cost[end[i]]:
            node_cost[end[i]] = new_cost
ans = node_cost[N-1]
cycle = [False] * N
for _ in range(N):
    for i in range(M):
        if cycle[start[i]]:
            cycle[end[i]] = True
        new_cost = node_cost[start[i]] + weight[i]
        if new_cost > node_cost[end[i]]:
            cycle[end[i]] = True
if cycle[N-1]:
    ans = "inf"
print(ans)