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:
import collections
class BellmanFord():
    def __init__(self, N):
        self.N = N
        self.edges = collections.defaultdict(list)

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges[u].append([v, d])
            self.edges[v].append([u, d])
        else:
            self.edges[u].append([v, d])


    def BellmanFord_search(self, s):
        """
        :param s: 始点
        :return: d[i] 始点sから各点iまでの最短経路
        """
        d = [float('inf') for i in range(self.N)]
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def BellmanFord_negative_search(self, start):
        # true, dist なら負の経路を含む
        d = collections.defaultdict(lambda: float('inf'))
        d[start] = 0
        counter = 0
        while True:
            update = False
            for n in range(N):
                for edge in self.edges[n]:
                    to, cost = edge
                    if d[n] != float('inf') and d[to] > d[n] + cost:
                        d[to] = d[n] + cost
                        update = True
                        counter += 1
            if not update:
                break
            if counter >= self.N ** 2:
                return True, d

        return False, d


N, M = map(int, input().split())
graph = BellmanFord(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, -c, directed=True)

hasNegativeCycle, d = graph.BellmanFord_negative_search(0)
if hasNegativeCycle:
    print('inf')
else:
    print(-1 * d[N-1])

Submission status: Wrong Answer

Solution code:
N,M = [int(s) for s in input().split()]
dist = [-10**10]*N
E = []
flag = 0
change = 0
N_flag = 0
for i in range(M):
    a,b,c = [int(s) for s in input().split()]
    E.append((a,b,c))
dist[0] = 0
for i in range(N):
    for (a,b,c) in E:
        if a == N or b == N:
            N_flag = 1
        newLen = dist[a-1] + c
        if newLen > dist[b-1]:
            change = 1
            dist[b-1] = newLen
            if i == N-1 and change == 1 and N_flag == 1:
                flag = 1
        change = 0
        N_flag = 0
if flag == 1:
    print('inf')
else:
    print(dist[N-1])

Submission status: Wrong Answer

Solution code:
N,M = [int(s) for s in input().split()]
dist = [-10**10]*N
E = []
flag = 0
change = 0
N_flag = 0
for i in range(M):
    a,b,c = [int(s) for s in input().split()]
    E.append((a,b,c))
dist[0] = 0
for i in range(N+1):
    for (a,b,c) in E:
        if a == N or b ==  N:
            N_flag = 1
        newLen = dist[a-1] + c
        if newLen > dist[b-1]:
            change = 1
            dist[b-1] = newLen
            if i == N and change == 1 and N_flag == 1:
                flag = 1
        change = 0
        N_flag = 0
if flag == 1:
    print('inf')
else:
    print(dist[N-1])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = []
for _ in range(M):
    a,b,c = map(int, input().split())
    E.append((a,b,c))
dist = [-N*10**9]*(N+1)
dist[1] = 0
flag = False
for i in range(N):
    for (a,b,c) in E:
        newlen = dist[a] + c
        if newlen > dist[b]:
            if i == N-1:
                flag = True
            dist[b] = newlen
            predist = dist[N]
if flag:
    dist2 = dist.copy()
    for i in range(N):
        for (a,b,c) in E:
            newlen = dist2[a] + c
            if newlen > dist2[b]:
                dist2[b] = newlen
    if dist2[N] > dist[N]:
        print("inf")
else:
    print(dist[N])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = []
for _ in range(M):
    a,b,c = map(int, input().split())
    E.append((a,b,c))
dist = [-N*10**9]*(N+1)
dist[1] = 0
flag = False
for i in range(N):
    for (a,b,c) in E:
        newlen = dist[a] + c
        if newlen > dist[b]:
            dist[b] = newlen
            predist = dist[N]
        if i == N-1 and dist[N] > predist:
            flag = True
if flag:
    print("inf")
else:
    print(dist[N])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = []
for _ in range(M):
    a,b,c = map(int, input().split())
    E.append((a,b,c))
dist = [-N*10**9]*(N+1)
dist[1] = 0
flag = False
for i in range(N+1):
    for (a,b,c) in E:
        newlen = dist[a] + c
        if newlen > dist[b]:
            if i == N:
                flag = True
            dist[b] = newlen
if flag:
    print("inf")
else:
    print(dist[N])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = []
for _ in range(M):
    a,b,c = map(int, input().split())
    E.append((a,b,c))
dist = [-N*10**9]*(N+1)
dist[1] = 0
flag = False
for i in range(N):
    for (a,b,c) in E:
        newlen = dist[a] + c
        if newlen > dist[b]:
            dist[b] = newlen
if flag:
    print("inf")
else:
    print(dist[N])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
E = []
for _ in range(M):
    a,b,c = map(int, input().split())
    E.append((a,b,c))
dist = [-N*10**9]*(N+1)
dist[1] = 0
flag = False
for i in range(N):
    for (a,b,c) in E:
        newlen = dist[a] + c
        if newlen > dist[b]:
            if i == N-1:
                flag = True
            dist[b] = newlen
if flag:
    print("inf")
else:
    print(dist[N])

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

def Bellman_Ford(g,start):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    a0 = float("inf")
    
    for i in [0]*(2*n):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if dist[to] <= dist[v] + cost: continue
                dist[to] = dist[v] + cost
                updated = True
        if not updated: break
        if i <= n: a0 = dist[-1]
    if a0 != dist[-1]: return None, False
    return dist, True


import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
for i in range(m):
    a,b,c = [int(i) for i in readline().split()]
    g[a-1].append((b-1,-c))
#    g[b-1].append((a-1,c))

dist, TF = Bellman_Ford(g, 0)

if TF: print(-dist[-1])
else: print("inf")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
import string
import sys
from itertools import chain, dropwhile, takewhile


def read(
    *shape, f=int, it=chain.from_iterable(sys.stdin), whitespaces=set(string.whitespace)
):
    def read_word():
        w = lambda c: c in whitespaces
        nw = lambda c: c not in whitespaces
        return f("".join(takewhile(nw, dropwhile(w, it))))

    if not shape:
        return read_word()
    elif len(shape) == 1:
        return [read_word() for _ in range(shape[0])]
    elif len(shape) == 2:
        return [[read_word() for _ in range(shape[1])] for _ in range(shape[0])]


def readi(*shape):
    return read(*shape)


def readi1(*shape):
    return [i - 1 for i in readi(*shape)]


def readf(*shape):
    return read(*shape, f=float)


def reads(*shape):
    return read(*shape, f=str)


def arr(*shape, fill_value=0):
    if len(shape) == 1:
        return [fill_value] * shape[0]
    elif len(shape) == 2:
        return [[fill_value] * shape[1] for _ in range(shape[0])]


def dbg(**kwargs):
    print(
        ", ".join("{} = {}".format(k, repr(v)) for k, v in kwargs.items()),
        file=sys.stderr,
    )


def main():
    N, M = readi(2)
    edges = readi(M, 3)
    dist = arr(N + 1, fill_value=float("-inf"))
    dist[1] = 0
    for i in range(N):
        for a, b, c in edges:
            new_d = dist[a] + c
            if new_d > dist[b]:
                if i == N - 1:
                    print("inf")
                    return
                dist[b] = new_d
    print(dist[N])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

def Bellman_Ford(g,start):
    n = len(g)    
    dist = [float("inf")]*n
    dist[start] = 0
    
    for i in [0]*(n):
        updated = False
        for v in range(n):
            for to, cost in g[v]:
                if dist[to] <= dist[v] + cost: continue
                dist[to] = dist[v] + cost
                updated = True
        if not updated: break
    else: return None, False #n周更新された場合
    return dist, True        


import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
for i in range(m):
    a,b,c = [int(i) for i in readline().split()]
    g[a-1].append((b-1,-c))
#    g[b-1].append((a-1,c))

dist, TF = Bellman_Ford(g, 0)

if TF: print(-dist[-1])
else: print("inf")

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

def SPFA(g, start):#g: グラフ, start: 始点
    from collections import deque
    n = len(g)
    relax_max = [n]*n #緩和回数
    is_inQ = [False]*n #キューに入っているか
    dist = [float("inf")]*n
    dist[start] = 0
    
    q = deque([start])
    while q:
        v = q.popleft()
        is_inQ[v] = False
        for to,cost in g[v]:
            if dist[to] <= dist[v] + cost: continue
            dist[to] = dist[v] + cost 
            if is_inQ[to]: continue
            q.append(to)
            is_inQ[to] = True
            relax_max[v] -= 1
            if relax_max[v] < 0: return None, False #負回路
 
    return dist, True

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n,m = [int(i) for i in readline().split()]
g = [[] for _ in range(n)]
for i in range(m):
    a,b,c = [int(i) for i in readline().split()]
    g[a-1].append((b-1,-c))
#    g[b-1].append((a-1,c))

dist, TF = SPFA(g, 0)

if TF: print(-dist[-1])
else: print("inf")

Submission status: Wrong Answer

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

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

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

	def NegativeCycle(self):
		for x in range(self.size):
			for y, w in self.adj[x]:
				if self.dist[y] > self.dist[x] + w:
					return True
		return False

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

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

bf = BellmanFord(adj, 0)
bf.solve()
if bf.NegativeCycle():
	print("inf")
else:
	print(-bf.GetDistance(n-1))

Submission status: Wrong Answer

Solution code:
N, M = list(map(int, input().split()))
abc = [list(map(int, input().split())) for _ in range(M)]

INF = - 10 ** 20
d = [INF for _ in range(N)]
d[0] = 0

for i in range(2 * N):
  f = True
  for j in range(M):
    a, b, c = abc[j]
    a -= 1
    b -= 1
    if d[b] < d[a] + c:
      d[b] = d[a] + c
      f = False
  if f:
    break
else:
  print("inf")
  exit()

print(d[-1])

Submission status: Wrong Answer

Solution code:
class BellmanFord():
    def __init__(self, N):
        self.N = N
        self.edges = []

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges.append([u, v, d])
            self.edges.append([v, u, d])
        else:
            self.edges.append([u, v, d])

    def BellmanFord_search(self, s):
        """
        :param s: 始点
        :return: d[i] 始点sから各点iまでの最短経路
        """
        d = [float('inf') for i in range(self.N)]
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def BellmanFord_negative_bool(self, start, numNodes):
        # 負の閉路の検出, Trueなら負の閉路が存在する
        d = [float('inf') for i in range(self.N)]
        d[start] = 0
        numEdges = len(self.edges)
        for i in range(numNodes):
            for j in range(numEdges):
                e = self.edges[j]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    if i == numNodes-1:
                        return True, d
        return False, d


N, M = map(int, input().split())
graph = BellmanFord(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, -c, directed=True)

hasNegativeCycle, d = graph.BellmanFord_negative_bool(0, N)
if hasNegativeCycle:
    print('inf')
else:
    print(-1 * d[N-1])

Submission status: Wrong Answer

Solution code:
class BellmanFord():
    def __init__(self, N):
        self.N = N
        self.edges = []

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges.append([u, v, d])
            self.edges.append([v, u, d])
        else:
            self.edges.append([u, v, d])

    def BellmanFord_search(self, s):
        """
        :param s: 始点
        :return: d[i] 始点sから各点iまでの最短経路
        """
        d = [float('inf') for i in range(self.N)]
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def BellmanFord_negative_bool(self, start, numNodes):
        # 負の閉路の検出, Trueなら負の閉路が存在する
        d = [float('inf') for i in range(self.N)]
        d[start] = 0
        numEdges = len(self.edges)
        for i in range(numNodes):
            for j in range(numEdges):
                e = self.edges[j]
                if d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    if i == numNodes-1:
                        return True, d
        return False, d


N, M = map(int, input().split())
graph = BellmanFord(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, -c, directed=True)

hasNegativeCycle, d = graph.BellmanFord_negative_bool(0, N)
if hasNegativeCycle:
    print('inf')
else:
    print(-1 * d[N-1])

Submission status: Wrong Answer

Solution code:
class BellmanFord():
    def __init__(self, N):
        self.N = N
        self.edges = []

    def add(self, u, v, d, directed=False):
        """
        u = from, v = to, d = cost
        directed = Trueのとき、有向グラフである。
        """
        if directed is False:
            self.edges.append([u, v, d])
            self.edges.append([v, u, d])
        else:
            self.edges.append([u, v, d])

    def BellmanFord_search(self, s):
        """
        :param s: 始点
        :return: d[i] 始点sから各点iまでの最短経路
        """
        d = [float('inf') for i in range(self.N)]
        d[s] = 0
        numEdges = len(self.edges)
        while True:
            update = False
            for i in range(numEdges):
                e = self.edges[i]
                # e: 辺iについて [from,to,cost]
                if d[e[0]] != float("inf") and d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    update = True
            if not update:
                break
        return d

    def BellmanFord_negative_bool(self, numNodes):
        # 負の閉路の検出, Trueなら負の閉路が存在する
        d = [float('inf') for i in range(self.N)]
        d[0] = 0
        numEdges = len(self.edges)
        for i in range(numNodes):
            for j in range(numEdges):
                e = self.edges[j]
                if d[e[1]] > d[e[0]] + e[2]:
                    d[e[1]] = d[e[0]] + e[2]
                    if i == numNodes-1:
                        return True, d
        return False, d


N, M = map(int, input().split())
graph = BellmanFord(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, -c, directed=True)

hasNegativeCycle, d = graph.BellmanFord_negative_bool(N)
if hasNegativeCycle:
    print('inf')
else:
    print(-1 * graph.BellmanFord_search(0)[N-1])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
egdes = [list(map(int, input().split())) for _ in range(M)]

INF = 10 ** 13

G = [[-INF] * (N + 1) for _ in range(N + 1)]
for a, b, c in egdes:
    G[a][b] = c
dp = [[-INF] * (N + 10) for _ in range(N + 10)]
dp[1][1] = 0
for i in range(1, N + 1):
    for j in range(1, i):
        for k in range(1, N + 1):
            dp[j][i] = max(dp[j][i], dp[j][k] + G[k][i])

for a, b, c in egdes:
    if a > b:
        if dp[b][a] + c > 0:
            print('inf')
            exit()
print(dp[1][N])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
egdes = [list(map(int, input().split())) for _ in range(M)]

INF = 10 ** 13

G = [[-INF] * (N + 1) for _ in range(N + 1)]
for a, b, c in egdes:
    G[a][b] = c
dp = [-INF] * (N + 10)
dp[1] = 0
for i in range(1, N + 1):
    for j in range(1, i):
        dp[i] = max(dp[i], dp[j] + G[j][i])

for a, b, c in egdes:
    if a > b:
        if dp[a] - dp[b] + c > 0:
            print('inf')
            exit()
print(dp[N])

Submission status: Wrong Answer

Solution code:
def BellmanFord(edges,num_v,source):
  dist=[float("inf") for i in range(num_v)]
  dist[source]=0
  
  for i in range(num_v):
    for edge in edges:
      if edge[0] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1: return -1
  
  return dist

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

d  = BellmanFord(edges,N,0)
if d==-1:
    print("inf")
    exit()

print(-d[N-1])

Submission status: Wrong Answer

Solution code:
print("inf")

Submission status: Wrong Answer

Solution code:
def BellmanFord(edges,num_v,source):
  dist=[float("inf") for i in range(num_v)]
  dist[source]=0

  for i in range(num_v):
    for edge in edges:
      if edge[0] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1: return -1

  return dist

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

d  = BellmanFord(edges,N,0)
if d==-1:
    print("inf")
    exit()

ans = 10**20
for i in range(N):
    if d[i] == float("inf"):
        print("inf")
        exit()

print(-d[N-1])

Submission status: Wrong Answer

Solution code:
def BellmanFord(edges,num_v,source):
  dist=[float("inf") for i in range(num_v)]
  dist[source]=0

  for i in range(num_v):
    for edge in edges:
      if edge[0] != float("inf") and dist[edge[1]] > dist[edge[0]] + edge[2]:
        dist[edge[1]] = dist[edge[0]] + edge[2]
        if i==num_v-1: return -1

  return dist

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

d  = BellmanFord(edges,N,0)
if d==-1:
    print("INF")
    exit()

ans = 10**20
for i in range(N):
    if d[i] == float("inf"):
        print("INF")
        exit()

print(-d[N-1])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(M)]

def bellman_ford():
    INF = 10 ** 20
    d = [INF] * (N + 1)
    d[1] = 0
    updated = True
    cnt = 0
    
    while updated and (cnt < N):
        updated = False
        cnt += 1
        for u, v, c in edges:
            if (d[u] != INF) and (d[v] > d[u] - c):
                d[v] = d[u] - c
                updated = v != N
                
    return d, cnt

d, cnt = bellman_ford()
print(-d[-1] if cnt < N else 'inf')

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(M)]

def bellman_ford():
    INF = 10 ** 20
    d = [INF] * (N + 1)
    d[1] = 0
    updated = True
    cnt = 0
    
    while updated and (cnt < N):
        updated = False
        cnt += 1
        for u, v, c in edges:
            if (d[u] != INF) and (d[v] > d[u] - c):
                d[v] = d[u] - c
                updated = True
                
    return d, cnt

d, cnt = bellman_ford()
print(-d[-1] if cnt < N else 'inf')

Submission status: Wrong Answer

Solution code:
n, m = map(int, raw_input().split())
import sys
edges = []
dist = [sys.maxint]*(n+1)
dist[1] = 0
dist
for _ in range(m):
    a, b, c = map(int, raw_input().split())
    edges.append((a, b, -c))

for i in range(n-1):
    for a, b, c in edges:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c
for i in range(n):
    for a, b, c in edges:
        if b == n and dist[a] + c < dist[b]:
            print "inf"
            exit()
print -dist[n]

Submission status: Wrong Answer

Solution code:
n, m = map(int, raw_input().split())
import sys
edges = []
dist = [sys.maxint]*(n+1)
dist[1] = 0
dist
for _ in range(m):
    a, b, c = map(int, raw_input().split())
    edges.append((a, b, -c))

for i in range(n-1):
    for a, b, c in edges:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c

for a, b, c in edges:
    if b == n and dist[a] + c < dist[b]:
        print "inf"
        exit()
print -dist[n]

Submission status: Wrong Answer

Solution code:
n, m = map(int, raw_input().split())
import sys
edges = []
dist = [sys.maxint]*(n+1)
dist[1] = 0
dist
for _ in range(m):
    a, b, c = map(int, raw_input().split())
    edges.append((a, b, -c))

for i in range(n-1):
    for a, b, c in edges:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c

for a, b, c in edges:
    if dist[a] + c < dist[b]:
        print "inf"
        exit()
print -dist[n]

Submission status: Wrong Answer

Solution code:
n, m = map(int, raw_input().split())
import sys
edges = []
dist = [sys.maxint]*(n+1)
dist[1] = 0
dist
for _ in range(m):
    a, b, c = map(int, raw_input().split())
    edges.append((a, b, -c))

for i in range(n):
    for a, b, c in edges:
        if dist[b] > dist[a] + c:
            dist[b] = dist[a] + c

for a, b, c in edges:
    if dist[a] + c < dist[b]:
        print "inf"
        exit()
print -dist[n]

Submission status: Wrong Answer

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

inf = float('inf')

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

loop = False
for j in range(E):
    From,To,cost = edge[j]
    if d[From] != inf and d[To]>d[From]+cost and To==V-1:
        loop = True

if loop:
    print('inf')
else:
    print(-d[V-1])

Submission status: Wrong Answer

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

inf = float('inf')

d = [inf]*V
d[0] = 0
for i in range(V):
    update = False
    for j in range(E):
        From,To,cost = edge[j]
        if d[From] != inf and d[To]>d[From]+cost:
            d[To]=d[From]+cost
            update = True
    if not update:
        break

loop = False
for j in range(E):
    From,To,cost = edge[j]
    if d[From] != inf and d[To]>d[From]+cost:
        loop = True

if loop:
    print('inf')
else:
    print(-d[V-1])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)


def solve(N: int, M: int, a: "List[int]", b: "List[int]", c: "List[int]"):
    def detect_loop(idx, conn, visited):
        visited[idx] = True
        for nex in conn[idx]:
            if visited[nex[0]]:
                return True
            if detect_loop(nex[0], conn, visited):
                return True
        visited[idx] = False
        return False

    def dfs(idx, conn, dis):
        for nex in conn[idx]:
            dis[nex[0]] = max(dis[nex[0]], dis[idx] + nex[1])
            dis = dfs(nex[0], conn, dis)
        return dis

    conn = [[] for _ in range(N + 1)]
    for i in range(M):
        conn[a[i]].append([b[i], c[i]])

    visited = [False] * (N + 1)
    if detect_loop(1, conn, visited):
        print('inf')
        return

    dis = [- float('inf')] * (N + 1)
    dis[1] = 0
    dis = dfs(1, conn, dis)
    #print(dis)
    print(dis[N])
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    a = [int()] * (M)  # type: "List[int]" 
    b = [int()] * (M)  # type: "List[int]" 
    c = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        a[i] = int(next(tokens))
        b[i] = int(next(tokens))
        c[i] = int(next(tokens))
    solve(N, M, a, b, c)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import bellman_ford

n,m=map(int,input().split())
g=[[float('inf')]*(n+1) for _ in range(n+1)]
for _ in range(m):
  a,b,c=map(int,input().split())
  g[a][b]=-c
try:
  score=int(bellman_ford(g)[1][n])
except:
  print('inf')
else:
  print(-score)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def bellman_ford(V, E, s):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
        s (in V) : start vertex
    Output:
        dist: the list of the minimum cost from s to arbitrary vertex v in the given graph
    '''
    INF = float('inf')
    N = len(V)
    dist = [INF]*N
    prev = [-1]*N
    dist[s] = 0
    for n_iterations in range(N):
        updated = False
        for v in V:
            d = dist[v]
            if d != INF:
                for u, c in E[v].items():
                    temp = d + c
                    if dist[u] > temp:
                        updated = True
                        dist[u] = temp
                        prev[u] = v
        if not updated: # the minimum costs are already stored in dist
            break
    else: # the above loop is not broken if and only if there exists a negative cycle
        return None
    return dist

N, M = map(int, input().split())
E = {i: defaultdict(int) for i in range(N)}
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1][b-1] = -c
V = list(range(N))
dist = bellman_ford(V, E, 0)
if dist is None:
    print('inf')
else:
    print(-dist[N-1])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

def bellman_ford(V, E, s):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
        s (in V) : start vertex
    Output:
        dist: the list of the minimum cost from s to arbitrary vertex v in the given graph
    '''
    INF = float('inf')
    N = len(V)
    dist = [INF]*N
    prev = [-1]*N
    dist[s] = 0
    for n_iterations in range(N):
        updated = False
        for v in V:
            d = dist[v]
            for u, c in E[v].items():
                temp = d + c
                if dist[u] != INF and dist[u] > temp:
                    updated = True
                    dist[u] = temp
                    prev[u] = v
        if not updated: # the minimum costs are already stored in dist
            break
    else: # the above loop is not broken if and only if there exists a negative cycle
        return None
    return dist

N, M = map(int, input().split())
E = {i: defaultdict(int) for i in range(N)}
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1][b-1] = -c
V = list(range(N))
dist = bellman_ford(V, E, 0)
if dist is None:
    print('inf')
else:
    print(-dist[N-1])