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

Solution code:
# -*- coding: utf-8 -*-
import sys
import heapq
N,M=map(int,raw_input().split())
a=[[] for _ in range(N+1)]
for i in range(M):
	x,y,z=map(int,raw_input().split())
	#print x,y,z
	a[x].append((-z,y))

#print a

if len(a[N])!=0:
	print "inf"
	sys.exit()

def djk(n):
	Start=n
	d=[0 for i in range(N+1)]
	d[Start]=0

	#優先度付きキューに[距離,頂点の番号]を格納する
	#スタート地点には距離0を入れる
	q=[]
	heapq.heappush(q, [0,Start])

	while len(q)!=0:

		#距離が最小の頂点を取り出し
		l,u=heapq.heappop(q)
		for i in a[u]:
			v=i[1]
			l_u_v=i[0]
			#print v, l_u_v
			if (d[v]>d[u]+l_u_v) or d[v]==0:
				d[v]=d[u]+l_u_v
				heapq.heappush(q, [d[v],v])

	return -1*d[N]


print djk(1)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://abc061.contest.atcoder.jp/tasks/abc061_d
TLE
"""
import sys
from sys import stdin
from collections import namedtuple
input = stdin.readline


def solve(s, N, E):
    d = [float('inf')] * (N+1)
    d[s] = 0
    count = 0

    while True:
        update = False
        count += 1
        if count > (N*len(E)):
            return 'inf'
        for e in E:
            if d[e.f] != float('inf') and d[e.t] > d[e.f] + e.c:
                d[e.t] = d[e.f] + e.c
                update = True
        if update is False:
            break

    return -d[-1]


edge = namedtuple('edge', ['f', 't', 'c'])
def main(args):
    N, M = map(int, input().split())
    E = []

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

    result = solve(1, N, E)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://abc061.contest.atcoder.jp/tasks/abc061_d
TLE
"""
import sys
from sys import stdin
from collections import namedtuple
input = stdin.readline


def solve(s, N, E):
    d = [float('inf')] * (N+1)
    d[s] = 0
    count = 0

    while True:
        update = False
        count += 1
        if count > (N+1):
            return 'inf'
        for e in E:
            if d[e.f] != float('inf') and d[e.t] > d[e.f] + e.c:
                d[e.t] = d[e.f] + e.c
                update = True
        if update is False:
            break

    return -d[-1]


edge = namedtuple('edge', ['f', 't', 'c'])
def main(args):
    N, M = map(int, input().split())
    E = []

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

    result = solve(1, N, E)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://abc061.contest.atcoder.jp/tasks/abc061_d
TLE
"""
import sys
from sys import stdin
from collections import namedtuple
input = stdin.readline


def solve(s, N, E):
    d = [float('inf')] * (N+1)
    d[s] = 0
    count = 0

    while True:
        update = False
        count += 1
        if count > N:
            return 'inf'
        for e in E:
            if d[e.f] != float('inf') and d[e.t] > d[e.f] + e.c:
                d[e.t] = d[e.f] + e.c
                update = True
        if update is False:
            break

    return -d[-1]


edge = namedtuple('edge', ['f', 't', 'c'])
def main(args):
    N, M = map(int, input().split())
    E = []

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

    result = solve(1, N, E)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://abc061.contest.atcoder.jp/tasks/abc061_d
TLE
"""
import sys
from sys import stdin
from collections import namedtuple
from heapq import heappush, heappop
input = stdin.readline


def solve(s, N, E):
    best_score = float('-inf')
    count = 0
    
    d = [float('-inf')] * (N+1)
    d[s] = 0
    while True:
        count += 1
        update = False
        for e in E:
            if d[e.f] != float('-inf') and d[e.t] < d[e.f] + e.c:
                d[e.t] = d[e.f] + e.c
                update = True
                
                if e.t == N:
                    best_score = max(best_score, d[e.t])
                if count > 50000 and e.f == N:
                    return 'inf'
                if count > 6000:
                    return best_score

        if update is False:
            break
    return d[-1]



edge = namedtuple('edge', ['f', 't', 'c'])
def main(args):
    N, M = map(int, input().split())
    E = []

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

    result = solve(1, N, E)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
http://abc061.contest.atcoder.jp/tasks/abc061_d
TLE
"""
import sys
from sys import stdin
from collections import namedtuple
from heapq import heappush, heappop
input = stdin.readline


def dijkstra(s, G):
    best_score = float('-inf')
    count = 0
    d = [float('-inf')] * len(G)
    d[s] = 0

    pq = []
    heappush(pq, (0, s))

    while pq:
        count += 1
        c, v = heappop(pq)
        if v == len(G)-1 and count > 100000:
            if d[-1] > 0:
                return 'inf'
            else:
                return best_score
        if d[v] > c:
            continue

        for e in G[v]:
            if d[e.t] < d[v] + e.c:
                d[e.t] = d[v] + e.c
                if e.t == len(G)-1:
                    best_score = max(d[e.t], best_score)
                heappush(pq, (d[e.t], e.t))
    return d[len(G)-1]


edge = namedtuple('edge', ['t', 'c'])
def main(args):
    N, M = map(int, input().split())


    G = [[] for _ in range(N+1)]

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

    result = dijkstra(1, G)
    print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Wrong Answer

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

inf = float('inf')

def bellman_ford():
    d = [inf] * N
    d[0] = 0
    negative = False
    for i in range(N):
        for j in range(M):
            e = es[j]
            if d[e[0]] != inf and d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == N - 1:
                    negative = True
    return float('inf') if negative else -d[N - 1]


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

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

print(bellman_ford())

Submission status: Wrong Answer

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

def find_negative_loop():
    d = [0] * N
    for i in range(N):
        for j in range(M):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
            if i == N - 1:
                return True
    return False


def bellman_ford():
    d = [float('inf')] * N
    d[0] = 0
    negative = False
    for i in range(N):
        for j in range(M):
            e = es[j]
            if d[e[1]] > d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == N - 1:
                    negative = True
    return float('inf') if negative else -d[N - 1]


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

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

print(bellman_ford())

Submission status: Wrong Answer

Solution code:
from collections import deque
def bfs(E,S,G):
    Q = deque()
    VIS = []
    Q.append([S,0])
    VIS.append(S)
    while len(Q):
        ans = float('-inf')
        F,T = Q.popleft()
        if F == G:
            continue
        for i in range(len(E[F])):
            TO ,C= E[F][i]
            if TO == G:
                ans = max(ans,T+C)
                continue
            if TO in VIS:
                return 'inf'
            else:
                Q.append([TO,T+C])
    return ans

n,m = map(int,input().split())
e= [[] for i in range(n)]
for i in range(m):
    f,t,c = list(map(int,input().split()))
    f -= 1
    t -= 1
    e[f].append([t,c])
print(bfs(e,0,n-1))

Submission status: Wrong Answer

Solution code:
from collections import deque
def bfs(E,S,G):
    Q = deque()
    VIS = []
    Q.append([S,0])
    VIS.append(S)
    while len(Q):
        ans = 0
        F,T = Q.popleft()
        if F == G:
            continue
        for i in range(len(E[F])):
            TO ,C= E[F][i]
            if TO == G:
                ans = max(ans,T+C)
                continue
            if TO in VIS:
                return 'inf'
            else:
                Q.append([TO,T+C])
    return ans

n,m = map(int,input().split())
e= [[] for i in range(n)]
for i in range(m):
    f,t,c = list(map(int,input().split()))
    f -= 1
    t -= 1
    e[f].append([t,c])
print(bfs(e,0,n-1))

Submission status: Wrong Answer

Solution code:
from collections import deque
def bfs(E,S,G):
    Q = deque()
    VIS = []
    Q.append([S,0])
    VIS.append(S)
    while len(Q):
        F,T = Q.popleft()
        for i in range(len(E[F])):
            TO ,C= E[F][i]
            if TO == G:
                ans = T+C
            if TO in VIS:
                return 'inf'
            else:
                Q.append([TO,T+C])
    return ans

n,m = map(int,input().split())
e= [[] for i in range(n)]
for i in range(m):
    f,t,c = list(map(int,input().split()))
    f -= 1
    t -= 1
    e[f].append([t,c])
print(bfs(e,0,n-1))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)
N, M = [int(n) for n in input().split()]

edges = [[] for n in range(N)]
for m in range(M):
  a, b, c = [int(w) for w in input().split()]
  a -= 1
  b -= 1
  edges[a].append((b, c))

import sys

def dfs(cur, score, hist):
  if cur in hist and hist[cur] >= score:
    return score
  if cur in hist and hist[cur] < score:
    print("inf")
    sys.exit()


  res = -10000000000000000000
  if cur == N-1:
    res = max(res, score)
  for edge in edges[cur]:
    b, c = edge
    newhist = hist.copy()
    newhist[cur] = score
    res = max(res, dfs(b, score+c, newhist))
  return res

print(dfs(0, 0, {}))

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for _ in range(M)]
tree = []
for abc in ABC:
    tree.append([abc[0]-1,abc[1]-1,-1*abc[2]])

def shortest_path(listG, source):
    INF = float("inf")
    d = [INF for _ in range(N)]
    d[source] = 0;
    cnt=0
    while True:
        update = False  #update flag
        for edge in listG:
            if d[edge[0]] != INF and d[edge[1]] > d[edge[0]] + edge[2]:
                d[edge[1]] = d[edge[0]] + edge[2]
                update = True
        if cnt >= N-1 and edge[1] == N-1:
            return "inf"
        if not update:
            break
        cnt += 1;
    return d[N-1]*-1

print(shortest_path(tree,0))

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for _ in range(M)]
tree = []
for abc in ABC:
    tree.append([abc[0]-1,abc[1]-1,-1*abc[2]])

def shortest_path(listG, source):
    INF = float("inf")
    d = [INF for _ in range(N)]
    d[source] = 0;
    cnt=0
    while True:
        update = False  #update flag
        for edge in listG:
            if d[edge[0]] != INF and d[edge[1]] > d[edge[0]] + edge[2]:
                d[edge[1]] = d[edge[0]] + edge[2]
                update = True
        if cnt == N-1 and edge[1] == N-1:
            return "inf"
        if not update:
            break
        cnt += 1;
    return d[N-1]*-1

print(shortest_path(tree,0))

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for _ in range(M)]
tree = []
for abc in ABC:
    tree.append([abc[0]-1,abc[1]-1,-1*abc[2]])

def shortest_path(listG, source):
    INF = float("inf")
    d = [INF for _ in range(N)]
    d[source] = 0;
    cnt=0
    while True:
        update = False  #update flag
        for edge in listG:
            if d[edge[0]] != INF and d[edge[1]] > d[edge[0]] + edge[2]:
                d[edge[1]] = d[edge[0]] + edge[2]
                update = True
        if cnt == N :
            return "inf"
        if not update:
            break
        cnt += 1;
    return d[N-1]*-1

print(shortest_path(tree,0))

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for _ in range(M)]
tree = []
for abc in ABC:
    tree.append([abc[0]-1,abc[1]-1,-1*abc[2]])

def shortest_path(listG, source):
    INF = float("inf")
    d = [INF for _ in range(N)]
    d[source] = 0;
    cnt=0
    while True:
        update = False  #update flag
        for edge in listG:
            if d[edge[0]] != INF and d[edge[1]] > d[edge[0]] + edge[2]:
                d[edge[1]] = d[edge[0]] + edge[2]
                update = True
        if cnt == N - 1 :
            return "inf"
        if not update:
            break
        cnt += 1;
    return d[N-1]*-1

print(shortest_path(tree,0))

Submission status: Wrong Answer

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

INF = 10**10
def solve():
    d = [INF for i in range(N)]
    d[0] = 0
    for i in range(N):
        for fr,to,cost in es:
            if d[fr] == INF: continue
            if d[to] > d[fr] + cost:
                d[to] = d[fr] + cost
                if i == N-1 and to == N-1: return 'inf'
    return -d[N-1]

print(solve())

Submission status: Wrong Answer

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

INF = 10**10
def solve():
    d = [INF for i in range(N)]
    d[0] = 0
    for i in range(N):
        for fr,to,cost in es:
            if d[to] > d[fr] + cost:
                d[to] = d[fr] + cost
                if i == N-1 and to == N-1: return 'inf'
    return -d[N-1]

print(solve())

Submission status: Wrong Answer

Solution code:
import sys

INF = float('inf')

def Bellmanford(n, edges, r): #r: 始点
    d = [INF] * n
    d[r] = 0
    
    for i in range(n):
        #flag = False
        
        for (u, v, c) in edges:
            if d[u] != INF and d[u] + c < d[v]:
                d[v] = d[u] + c
                #flag = True
        
            if i == n-1 and v == n-1:
                return 'inf'
    
    return -d[n-1]
    

N, M = map(int, sys.stdin.readline().split())
Edges = [None] * M

for i in range(M):
    ai, bi, ci = map(int, sys.stdin.readline().split())
    Edges[i] = (ai-1, bi-1, -ci)
    
ans = Bellmanford(N, Edges, 0)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

INF = float('inf')

def Bellmanford(n, edges, r): #r: 始点
    d = [INF] * n
    d[r] = 0
    
    for i in range(n):
        #flag = False
        
        for (u, v, c) in edges:
            if d[u] != INF and d[u] + c < d[v]:
                d[v] = d[u] + c
                #flag = True
        
        if i == n-1 and v == n-1:
            return 'inf'
    
    return -d[n-1]
    

N, M = map(int, sys.stdin.readline().split())
Edges = [None] * M

for i in range(M):
    ai, bi, ci = map(int, sys.stdin.readline().split())
    Edges[i] = (ai-1, bi-1, -ci)
    
ans = Bellmanford(N, Edges, 0)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
 
INF = float('inf')
 
def Bellmanford(n, edges, r): #r: 始点
    d = [INF] * n
    d[r] = 0
    
    for i in range(n):
        flag = False
        
        for (u, v, c) in edges:
            if d[u] != INF and d[u] + c < d[v]:
                d[v] = d[u] + c
                flag = True
        
        if flag and i == n-1 and v == n-1:
            return 'inf'
    
    return -d[n-1]
    
 
N, M = map(int, sys.stdin.readline().split())
Edges = [None] * M
 
for i in range(M):
    ai, bi, ci = map(int, sys.stdin.readline().split())
    Edges[i] = (ai-1, bi-1, -ci)
    
ans = Bellmanford(N, Edges, 0)
 
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

INF = float('inf')

def Bellmanford(n, edges, r): #r: 始点
    d = [INF] * n
    d[r] = 0
    
    for i in range(n):
        flag = False
        
        for (u, v, c) in edges:
            if d[u] != INF and d[u] + c < d[v]:
                d[v] = d[u] + c
                flag = True
        
        if flag and i == n-1:
            return 'inf'
    
    return -d[n-1]
    

N, M = map(int, sys.stdin.readline().split())
Edges = [None] * M

for i in range(M):
    ai, bi, ci = map(int, sys.stdin.readline().split())
    Edges[i] = (ai-1, bi-1, -ci)
    
ans = Bellmanford(N, Edges, 0)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys 

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

for _ in range(M):
    a, b, c = list(map(int, input().split()))
    a_list.append(a)
    b_list.append(b)
    c_list.append(-c)

inf = sys.maxsize
dist = [inf for _ in range(N)]
dist[0] = 0

for loop in range(N):
    for i in range(M):
        if dist[a_list[i]-1] == inf:
            continue
        if dist[b_list[i]-1] > dist[a_list[i]-1] + c_list[i]:
            dist[b_list[i]-1] = dist[a_list[i]-1] + c_list[i]
            if loop == N - 1 and b_list[i] == N - 1:
                print('inf')
                sys.exit()

print(-dist[N-1])

Submission status: Wrong Answer

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

graph = [list() for _ in range(N+1)]

for _ in range(M):
    a, b, c = list(map(int, input().split(" ")))
    graph[a].append([b, c])
    
def search(start):
    dist = [-float("inf") for i in range(N+1)]
    dist[1] = 0
    
    for i in range(N*2):
        for j in range(1, N+1):
            for u in graph[j]:
                if (dist[j]+u[1] > dist[u[0]]) and i > N:
                    return ("inf")
                
                dist[u[0]] = max(dist[j]+u[1], dist[u[0]])
                
    return dist[-1]

print(search(N))

Submission status: Wrong Answer

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

graph = [list() for _ in range(N+1)]

for _ in range(M):
    a, b, c = list(map(int, input().split(" ")))
    graph[a].append([b, c])
    
def search(start):
    dist = [-float("inf") for i in range(N+1)]
    dist[1] = 0
    
    for i in range(N):
        for j in range(1, N+1):
            for u in graph[j]:
                if (dist[j]+u[1] > dist[u[0]]) and i == N-1:
                    return ("inf")
                
                dist[u[0]] = max(dist[j]+u[1], dist[u[0]])
                
    return dist[-1]

print(search(N))

Submission status: Wrong Answer

Solution code:
INF = float('inf')

def bellmanford(edges, start, N):
    costs = [INF] * N
    costs[start] = 0
    for i in range(N):
        update = False
        for f, t, c in edges:
            if costs[f] != INF and costs[f] + c < costs[t]:
                costs[t] = costs[f] + c
                update = True

                if i == N - 1:
                    return 'inf'
        if not update:
            break
    return -costs[N-1]

N, M = map(int, input().split())
edges = []
for _ in range(M):
    f, t, c = map(int, input().split())
    edges.append((f-1, t-1, -c))

print(bellmanford(edges, 0, N))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import count


def bellman_ford(edges, start_node, node_size):
    INF = float("inf")
    cost_table = [INF] * node_size
    cost_table[start_node] = 0
    for no in count(0):
        update = False
        for e in edges:
            f, t, c = e
            if cost_table[f] != INF and cost_table[f] + c < cost_table[t]:
                cost_table[t] = cost_table[f] + c
                update = True
        if not update:
            break

        if no > node_size + 5:
            return None

    return cost_table


def main():
    N, M = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a - 1, b - 1, -c))
    cost_table = bellman_ford(edges, 0, N)
    if cost_table is None:
        print("inf")
    else:
        print(-1 * cost_table[-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict


def bellman_ford(edges, start_node, node_size):
    INF = float("inf")
    cost_table = [INF] * node_size
    cost_table[start_node] = 0
    for i in range(node_size):
        update = False
        for e in edges:
            f, t, c = e
            if cost_table[f] != INF and cost_table[f] + c < cost_table[t]:
                cost_table[t] = cost_table[f] + c
                update = True
        if not update:
            break
    else:
        return None

    return cost_table


def main():
    N, M = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a - 1, b - 1, -c))
    cost_table = bellman_ford(edges, 0, N)
    if cost_table is None:
        print("inf")
    else:
        print(-1 * cost_table[-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict


def bellman_ford(edges, start_node, node_size):
    INF = float("inf")
    cost_table = [INF] * node_size
    cost_table[start_node] = 0
    for i in range(node_size):
        update = False
        for e in edges:
            f, t, c = e
            if cost_table[f] != INF and cost_table[f] + c < cost_table[t]:
                cost_table[t] = cost_table[f] + c
                update = True
        if not update:
            break

    if i == node_size - 1:
        return None
    else:
        return cost_table


def main():
    N, M = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a - 1, b - 1, -c))
    cost_table = bellman_ford(edges, 0, N)
    if cost_table is None:
        print("inf")
    else:
        print(-1 * cost_table[-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
INF = 10 ** 10


def bellman_ford(edges, start_node, node_size):
    cost_table = [INF] * node_size
    cost_table[start_node] = 0
    for i in range(node_size):
        update = False
        for e in edges:
            f, t, c = e
            if cost_table[f] != INF and cost_table[t] > cost_table[f] + c:
                cost_table[t] = cost_table[f] + c
                update = True
        if not update:
            break
    if i == node_size - 1:
        return None
    else:
        return cost_table


def main():
    N, M = map(int, input().split())
    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        edges.append((a - 1, b - 1, -c))
    cost_table = bellman_ford(edges, 0, N)
    if cost_table is None:
        print("inf")
    else:
        print(-1 * cost_table[-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

print max_score(edge,int(N))

Submission status: Wrong Answer

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

routes = list()
for i in range(M):
    routes.append(list(map(int,input().split())))

score = [0,0] + [10**11] * (N-1)
negative = [False] * (N+1)

for i in range(N-1):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c

ans = -score[N]
            
for i in range(N):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c
            negative[b] = True
        if(negative[a] == True):
            negative[b] = True

if(negative[N] == True):
    print("inf")
else:
    print(ans)

Submission status: Wrong Answer

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

routes = list()
for i in range(M):
    routes.append(list(map(int,input().split())))

score = [0,0] + [10**10] * (N-1)
negative = [False] * (N+1)

for i in range(N-1):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c

ans = -score[N]
            
for i in range(N):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c
            negative[b] = True
        if(negative[a] == True):
            negative[b] = True

if(negative[N] == True):
    print("inf")
else:
    print(ans)

Submission status: Wrong Answer

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

routes = list()
for i in range(M):
    routes.append(list(map(int,input().split())))

score = [0,0] + [1000000000] * (N-1)
negative = [False] * (N+1)

for i in range(N-1):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c

ans = -score[N]
            
for i in range(N):
    for a,b,c in routes:
        if(score[b] > score[a] - c):
            score[b] = score[a] - c
            negative[b] = True
        if(negative[a] == True):
            negative[b] = True

if(negative[N] == True):
    print("inf")
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
# Python program for Bellman-Ford's single source
# shortest path algorithm.

from collections import defaultdict

#Class to represent a graph
class Graph:

    def __init__(self,vertices):
        self.V= vertices #No. of vertices
        self.graph = [] # default dictionary to store graph

    # function to add an edge to graph
    def addEdge(self,u,v,w):
        self.graph.append([u, v, w])

    # utility function used to print the solution
    def printArr(self, dist):
        print -dist[-1]
        return

    # The main function that finds shortest distances from src to
    # all other vertices using Bellman-Ford algorithm.  The function
    # also detects negative weight cycle
    def BellmanFord(self, src):

        # Step 1: Initialize distances from src to all other vertices
        # as INFINITE
        dist = [float("Inf")] * self.V
        dist[src] = 0


        # Step 2: Relax all edges |V| - 1 times. A simple shortest
        # path from src to any other vertex can have at-most |V| - 1
        # edges
        for i in range(self.V - 1):
            # Update dist value and parent index of the adjacent vertices of
            # the picked vertex. Consider only those vertices which are still in
            # queue
            for u, v, w in self.graph:
                if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                        dist[v] = dist[u] + w

        # Step 3: check for negative-weight cycles.  The above step
        # guarantees shortest distances if graph doesn't contain
        # negative weight cycle.  If we get a shorter path, then there
        # is a cycle.

        for u, v, w in self.graph:
                if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                        print "inf"
                        return

        # print all distance
        self.printArr(dist)
v, x = map(int, raw_input().split())
g = Graph(v)
while x:
    x=x-1
    a, b, c = map(int, raw_input().split())
    g.addEdge(a-1, b-1, -c)

#Print the solution
g.BellmanFord(0)

Submission status: Wrong Answer

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

from scipy.sparse import lil_matrix
from scipy.sparse.csgraph import depth_first_order, bellman_ford, NegativeCycleError
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: Wrong Answer

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

for i in range(n):
    updated = False
    n_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 b == n:
                n_updated = True
    if not updated:
        print(dists[-1])
        break
else:
    print('inf' if n_updated else dists[-1])