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 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

    cnt = 0
 
    for i in range(N):
        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 flag and i == N - 1:
            return None

    return dist[N - 1]
 
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1000000)
N,M = [int(x) for x in input().split()]
A=[]
B=[]
C=[]
for i in range(M):
    a,b,c = [int(x) for x in input().split()]
    A.append(a)
    B.append(b)
    C.append(c)

nodes= [0]*(N+1)

max_score=-10**15
max_score_node=0
def count(node,score,l):
    global max_score
    global max_score_node
    if node==N:
       if score > max_score:
           max_score = score
           max_score_node = l
    if nodes[node]==2:
        if score > 0:
            print("inf")
            sys.exit()
        else:
            print(max_score)
            sys.exit()
    nodes[node]=2
    for i in range(M):
        if A[i]==node:
            count(B[i],score+C[i],l+1)
    nodes[node]=1


count(1,0,0)

print(max_score)

Submission status: Wrong Answer

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]
if N*M >= 1900000:
    print("inf")
    exit(0)

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

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]
if N*M >= 1900000:
    print(ans)
    exit(0)

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

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

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

W = [[-10**9-1 for j in range(N)] for i in range(N)]
y = [-10**9-1 for i in range(N)]
y_t = [-10**9-1 for i in range(N)]
y[0] = 0
y_t[0] = 0

for i in range(N):
    W[i][i]=0

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

flag = False

for i in range(N):
    for j in range(N):
        yj_max = -10**9-1
        for k in range(N):
            yj_temp = -10**9-1
            if y[k]!=-10**9-1 and W[k][j]!=-10**9-1:
                yj_temp=y[k]+W[k][j]
            if yj_max<yj_temp:
                yj_max = yj_temp
        y_t[j]=yj_max
    if y==y_t:
        flag = True
        break
    y = y_t
    

if flag:
    print y[N-1]
else:
    print 'inf'

Submission status: Wrong Answer

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

    cnt = 0
 
    for i in range(N):
        for (u, v, c) in edges:
            flag = False

            if dist[u] != inf and dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True

        # print(dist)

        if flag and i == N - 1:
            return None

    return dist[N - 1]
 
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

    cnt = 0
 
    for i in range(N):
        for (u, v, c) in edges:
            flag = False

            if dist[u] != inf and dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True

        print(dist)

        if flag and i == N - 1:
            return None

    return dist[N - 1]
 
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys
N,M=map(int, input().split())
a=[]
b=[]
c=[]
for m in range (0,M):
  A,B,C=map(int, input().split() )
  a+=[A]
  b+=[B]
  c+=[C]
V=[0]+[-10**90]*(N-1)# iに到達するときの最大得点
R=[0]*N# iの直前にいる場所

for n in range(N-1):
  for m in range(M):
    u=a[m]
    v=b[m]
    if V[b[m]-1]<V[a[m]-1]+c[m]:
      V[b[m]-1]=V[a[m]-1]+c[m]
      R[b[m]-1]=a[m]-1

for m in range(M):
  u=a[m]
  v=b[m]
  if V[b[m]-1]<V[a[m]-1]+c[m]:
    print("inf")
    sys.exit()
print(V[N-1])

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1000000)
N,M = [int(x) for x in input().split()]
A=[]
B=[]
C=[]
for i in range(M):
    a,b,c = [int(x) for x in input().split()]
    A.append(a)
    B.append(b)
    C.append(c)

nodes= [0]*(N+1)

max_score=-10**15
max_score_node=0
def count(node,score,l):
    global max_score
    global max_score_node
    if node==N:
       if score > max_score:
           max_score = score
           max_score_node = l
    if nodes[node]==2:
        if score > 0:
            print("inf")
            sys.exit()
        return
    nodes[node]=2
    for i in range(M):
        if A[i]==node:
            count(B[i],score+C[i],l+1)
    nodes[node]=1


count(1,0,0)

print(max_score)

Submission status: Wrong Answer

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

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

W = [[-10**9-1 for j in range(N)] for i in range(N)]
y = [-10**9-1 for i in range(N)]
y_t = [-10**9-1 for i in range(N)]
y[0] = 0
y_t[0] = 0

for i in range(N):
    W[i][i]=0

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

flag1 = False
flag2 = False
for i in range(N):
    for j in range(N):
        yj_max = -10**9-1
        for k in range(N):
            yj_temp = -10**9-1
            if y[k]!=-10**9-1 and W[k][j]!=-10**9-1:
                yj_temp=y[k]+W[k][j]
            if yj_max<yj_temp:
                yj_max = yj_temp
        y_t[j]=yj_max
    if y==y_t:
        flag1 = True
        break
    if i==N-1:
        if not y[N-1]==y_t[N-1]:
            flag2 = True
    y = y_t
    

if flag2:
    print 'inf'
else:
    print y[N-1]

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import queue
import random
from heapq import heappush, heappop
sys.setrecursionlimit(10000)
mod = 10**9 + 7

n, m = map(int, input().split())
dist = [-10**18] * n
dist[0] = 0
edge = []
for i in range(m):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c))
cnt = 0
ans = 0
while True:
    update = False
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            update = True
    if update == False:
        print(dist[n - 1])
        break
    cnt += 1
    if cnt > 2 * n:
        print("inf")
        break

Submission status: Wrong Answer

Solution code:

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

class Bellman_Ford(object):
	"""
	ベルマンフォード法, O(EV)
	ステータス:distance(list),prev(list),length(int)
	edge=[i, j, cost] のリスト
	"""
	def __init__(self, edge, start, length):
		self.start=start
		self.length=length
		self.distance=[float("inf") for x in range(self.length)]
		self.distance[start]=0
		self.prev=[0 for x in range(self.length)]
		self.prev[start]=-1
		self.solvable=True
		def update():
			for i in edge:
				d=self.distance[i[0]]+i[2]
				if d<self.distance[i[1]]:
					self.distance[i[1]]=d 
					self.prev[i[1]]=i[0]
		for i in range(length):
			update()
		memo=[]
		for i in self.distance:
			memo.append(i)
		update()
		if memo!=self.distance:
			self.solvable=False

	def route(self,goal):
		route=[]
		while(True):
			route.append(self.prev[goal])
			goal=self.prev[goal]
			if goal==self.start:
				break
		route.reverse()
		return(route)

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

B = Bellman_Ford(edges,0,N)
if (not B.solvable):
	print("inf")
else:
	print(-B.distance[-1])

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(1000000)
N,M = [int(x) for x in input().split()]
A=[]
B=[]
C=[]
for i in range(M):
    a,b,c = [int(x) for x in input().split()]
    A.append(a)
    B.append(b)
    C.append(c+10**9+1)

nodes= [0]*(N+1)

max_score=0
max_score_node=0
def count(node,score,l):
    global max_score
    global max_score_node
    if node==N:
       if score > max_score:
           max_score = score
           max_score_node = l
    if nodes[node]==2:
        print("inf")
        sys.exit()
    nodes[node]=2
    for i in range(M):
        if A[i]==node:
            count(B[i],score+C[i],l+1)
    nodes[node]=1


count(1,0,0)

print(max_score-max_score_node*(10**9+1))

Submission status: Wrong Answer

Solution code:
import math

INF = float("inf")

N, M = map(int, input().split())
edge = []

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


def find_loop():
    d = [-INF for _ in range(N + 1)]
    d[1] = 0

    for i in range(N):
        for e in edge:
            if not math.isinf(d[e[0]]) and d[e[1]] < d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == N - 1:
                    return True
    return False


if find_loop():
    print("inf")
else:
    d = [-INF for _ in range(N + 1)]
    d[1] = 0

    while True:
        update = False
        for e in edge:
            if d[e[0]] != -INF and d[e[1]] < d[e[0]] + e[2]:
                update = True
                d[e[1]] = d[e[0]] + e[2]
        if not update:
            break
    print(d[N])

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self):
        pass

class Edge:

    def __init__(self,edge,cost=1):
        self.node_from=edge[0]
        self.node_to=edge[1]
        self.cost=cost

class myGraph:
    def __init__(self):
        self.nodes=[]
        self.edges=[]
        self.edges_cost=[]

    def add_edge(self,edge,cost=1):
        self.edges.append(Edge(edge,cost))
        for e in sorted(edge):
            if e not in self.nodes:
                self.nodes.append(e)


    def get_edges_fromx(self,x):

        #dd=self.node[self.node.index.map(lambda x:x.startswith('0'))]
        #dd=Gpd(dd)
        res=[]
        for e in self.edges:
            if x in (e.node_from,e.node_to):
                #res.append((e.node_to,e.node_from))
                res.append(e)

        return res

    def add_node(self,node):
        self.nodes.append(node)

    def show(self):

        import networkx as nx
        import matplotlib.pyplot as plt
        G=nx.Graph()

        for e in self.edges:

            G.add_edge(e.node_from,e.node_to,weight=e.cost)
            #print(e.node_from,e.node_to,e.cost)

        pos=nx.spring_layout(G)
        #nx.draw_networkx_edges(G,pos=pos,edgelist=G.edges())
        edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])

        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_weight)
        #nx.draw_networkx_labels(G, pos)
        nx.draw_networkx_nodes(G,pos)
        nx.draw_networkx_edges(G,pos)
        nx.draw_networkx_labels(G,pos)
        #plt.axis('off')
        #nx.draw(G,with_labels=True)
        plt.show()

    def bermn_ford(self,start):

        nodes=self.nodes
        edges=self.edges
        dists={}
        for n in nodes:
            dists[n]=False
        dists[start]=0


        for i in range(len(nodes)):
            update=False
            for k in range(len(edges)):
                e=edges[k]
                if not dists[e.node_to]:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True
                elif dists[e.node_to]<dists[e.node_from]+e.cost:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True


            if i==len(nodes)-1:
                return False

            if not update:
                break

        return dists


def linput():
    return list(map(int,input().split(" ")))

N,M=linput()
g=myGraph()
for i in range(M):
    a,b,c=linput()
    g.add_edge([a,b],c)

res=g.bermn_ford(1)
#print(res)
if not res:
    print("inf")
else:
    print(res[N])

Submission status: Wrong Answer

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

    cnt = 0
 
    for i in range(N):
        for (u, v, c) in edges:
            flag = False

            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True

            if flag and i == N - 1:
                return None

    return dist[N - 1]
 
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

class Bellman_Ford(object):
	"""
	ベルマンフォード法, O(EV)
	ステータス:distance(list),prev(list),length(int)
	edge=[i, j, cost] のリスト
	"""
	def __init__(self, edge, start, length):
		self.start=start
		self.length=length
		self.distance=[float("inf") for x in range(self.length)]
		self.distance[start]=0
		self.prev=[0 for x in range(self.length)]
		self.prev[start]=-1
		self.solvable=True
		def update():
			for i in edge:
				d=self.distance[i[0]]+i[2]
				if d<self.distance[i[1]]:
					self.distance[i[1]]=d 
					self.prev[i[1]]=i[0]
		for i in range(length-1):
			update()
		memo=[]
		for i in self.distance:
			memo.append(i)
		update()
		if memo!=self.distance:
			self.solvable=False

	def route(self,goal):
		route=[]
		while(True):
			route.append(self.prev[goal])
			goal=self.prev[goal]
			if goal==self.start:
				break
		route.reverse()
		return(route)

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

B = Bellman_Ford(edges,0,N)
if (not B.solvable) or B.distance[-1]==float("inf"):
	print("inf")
else:
	print(-B.distance[-1])

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
from heapq import heappush, heappop
import queue
import random
sys.setrecursionlimit(10000)

mod = 10**9 + 7

n, m = map(int, input().split())
dist = [-10**18] * n
dist[0] = 0
edge = []
for i in range(m):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c))
cnt = 0
while True:
    update = False
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            update = True
    if update == False:
        print(dist[n - 1])
        break
    cnt += 1
    if cnt > n:
        print("inf")
        break

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    n,m = LI()
    e = collections.defaultdict(list)
    for _ in range(m):
        a,b,c = LI_()
        e[a].append((b,c+1))

    t = [0] * n

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s, -1))
        v = {}
        while len(q):
            k, u, mu = heapq.heappop(q)
            if u in v and v[u][0] >= -k:
                continue
            if u in v and v[u][1] == mu:
                v[u][0] = inf
            else:
                v[u] = [-k, mu]

            for uv, ud in e[u]:
                vd = -k + ud
                if uv in v and v[uv][0] >= vd and v[uv][1] == u:
                    continue
                heapq.heappush(q, (-vd, uv, u))

        return v

    d = search(0)
    if d[n-1][0] == inf:
        return 'inf'
    return d[n-1][0]


print(main())

Submission status: Wrong Answer

Solution code:
INF = 10 ** 13

N, M = map(int, input().split())
edge = []

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


def find_loop():
    d = [-INF for _ in range(N + 1)]
    d[1] = 0

    for i in range(N):
        for e in edge:
            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:
                    return True
    return False


if find_loop():
    print("inf")
else:
    d = [-INF for _ in range(N + 1)]
    d[1] = 0

    while True:
        update = False
        for e in edge:
            if d[e[0]] != -INF and d[e[1]] < d[e[0]] + e[2]:
                update = True
                d[e[1]] = d[e[0]] + e[2]
        if not update:
            break
    print(d[N])

Submission status: Wrong Answer

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

class Bellman_Ford(object):
	"""
	ベルマンフォード法, O(EV)
	ステータス:distance(list),prev(list),length(int)
	edge=[i, j, cost] のリスト
	"""
	def __init__(self, edge, start, length):
		self.start=start
		self.length=length
		self.distance=[float("inf") for x in range(self.length)]
		self.distance[start]=0
		self.prev=[0 for x in range(self.length)]
		self.prev[start]=-1
		self.solvable=True
		def update():
			for i in edge:
				d=self.distance[i[0]]+i[2]
				if d<self.distance[i[1]]:
					self.distance[i[1]]=d 
					self.prev[i[1]]=i[0]
		for i in range(length):
			update()
		memo=[]
		for i in self.distance:
			memo.append(i)
		update()
		if memo!=self.distance:
			self.solvable=False

	def route(self,goal):
		route=[]
		while(True):
			route.append(self.prev[goal])
			goal=self.prev[goal]
			if goal==self.start:
				break
		route.reverse()
		return(route)

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

B = Bellman_Ford(edges,0,N)
if not B.solvable:
	print("inf")
else:
	print(B.distance[-1])

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    n,m = LI()
    e = collections.defaultdict(list)
    for _ in range(m):
        a,b,c = LI_()
        e[a].append((b,c+1))

    t = [0] * n

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s, -1))
        v = {}
        while len(q):
            k, u, mu = heapq.heappop(q)
            if u in v and v[u][0] >= -k:
                continue
            if u in v and v[u][1] == mu:
                v[u][0] = inf
            else:
                v[u] = [-k, mu]

            for uv, ud in e[u]:
                vd = -k + ud
                if uv in v and v[uv][0] >= vd:
                    continue
                heapq.heappush(q, (-vd, uv, u))

        return v

    d = search(0)
    if d[n-1][0] == inf:
        return 'inf'
    return d[n-1][0]


print(main())

Submission status: Wrong Answer

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

class Bellman_Ford(object):
	"""
	ベルマンフォード法, O(EV)
	ステータス:distance(list),prev(list),length(int)
	edge=[i, j, cost] のリスト
	"""
	def __init__(self, edge, start, length):
		self.start=start
		self.length=length
		self.distance=[float("inf") for x in range(self.length)]
		self.distance[start]=0
		self.prev=[0 for x in range(self.length)]
		self.prev[start]=-1
		self.solvable=True
		def update():
			for a,b,c in edge:
				d = self.distance[a]+c
				if d<self.distance[b]:
					self.distance[b] = d 
					self.prev[b] = a
		for i in range(length-1):
			update()
		memo=[]
		for i in self.distance:
			memo.append(i)
		update()
		if memo!=self.distance:
			self.solvable=False

	def route(self,goal):
		route=[]
		while(True):
			route.append(self.prev[goal])
			goal=self.prev[goal]
			if goal==self.start:
				break
		route.reverse()
		return(route)

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

B = Bellman_Ford(edges,0,N)
if not B.solvable or B.distance[-1]==float("-inf"):
	print("inf")
else:
	print(B.distance[-1])

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
from heapq import heappush, heappop
import queue
import random
sys.setrecursionlimit(10000)

mod = 10**9 + 7

n, m = map(int, input().split())
dist = [-10**18] * n
pq = queue.PriorityQueue()
edge = [[] for i in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    edge[a - 1].append((b - 1, c))
dist[0] = 0
used = [False] * n
pq.put((0, 0))
while not pq.empty():
    c, p = pq.get()
    if dist[p] != c:
        continue
    if used[p]:
        print("inf")
        exit(0)
    used[p] = True
    for i in edge[p]:
        to, sub = i
        nc = c + sub
        if dist[to] < nc:
            dist[to] = nc
            pq.put((nc, to))
print(dist[n - 1])

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


def main():
    n,m = LI()
    e = collections.defaultdict(list)
    for _ in range(m):
        a,b,c = LI_()
        e[a].append((b,c+1))

    t = [0] * n

    def search(s):
        d = collections.defaultdict(lambda: -inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s, -1))
        v = {}
        while len(q):
            k, u, mu = heapq.heappop(q)
            if u in v and v[u][0] >= -k:
                continue
            if u in v and v[u][1] == mu:
                v[u][0] = inf
            else:
                v[u] = [-k, mu]

            for uv, ud in e[u]:
                vd = -k + ud
                if uv in v and v[uv][0] >= vd:
                    continue
                if d[uv] < vd:
                    d[uv] = vd
                    heapq.heappush(q, (-vd, uv, u))

        return v

    d = search(0)
    if d[n-1][0] == inf:
        return 'inf'
    return d[n-1][0]


print(main())

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self):
        pass

class Edge:

    def __init__(self,edge,cost=1):
        self.node_from=edge[0]
        self.node_to=edge[1]
        self.cost=cost

class myGraph:
    def __init__(self):
        self.nodes=[]
        self.edges=[]
        self.edges_cost=[]

    def add_edge(self,edge,cost=1):
        self.edges.append(Edge(edge,cost))
        for e in sorted(edge):
            if e not in self.nodes:
                self.nodes.append(e)


    def get_edges_fromx(self,x):

        #dd=self.node[self.node.index.map(lambda x:x.startswith('0'))]
        #dd=Gpd(dd)
        res=[]
        for e in self.edges:
            if x in (e.node_from,e.node_to):
                #res.append((e.node_to,e.node_from))
                res.append(e)

        return res

    def add_node(self,node):
        self.nodes.append(node)

    def show(self):

        import networkx as nx
        import matplotlib.pyplot as plt
        G=nx.Graph()

        for e in self.edges:

            G.add_edge(e.node_from,e.node_to,weight=e.cost)
            #print(e.node_from,e.node_to,e.cost)

        pos=nx.spring_layout(G)
        #nx.draw_networkx_edges(G,pos=pos,edgelist=G.edges())
        edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])

        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_weight)
        #nx.draw_networkx_labels(G, pos)
        nx.draw_networkx_nodes(G,pos)
        nx.draw_networkx_edges(G,pos)
        nx.draw_networkx_labels(G,pos)
        #plt.axis('off')
        #nx.draw(G,with_labels=True)
        plt.show()

    def bermn_ford(self,start):

        nodes=self.nodes
        edges=self.edges
        Z=10**4
        dists={}
        for n in nodes:
            dists[n]=Z
        dists[start]=0


        for i in range(len(nodes)):
            update=False
            for k in range(len(edges)):
                e=edges[k]
                if dists[e.node_to]>dists[e.node_from]+e.cost:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True


            if i==len(nodes)-1:
                return False

            if not update:
                break

        return dists


def linput():
    return list(map(int,input().split(" ")))

N,M=linput()
g=myGraph()
for i in range(M):
    a,b,c=linput()
    g.add_edge([a,b],c)

res=g.bermn_ford(1)
if not res:
    print("inf")
else:
    print(res[N])

Submission status: Wrong Answer

Solution code:
import collections

def solve():
    n, m = map(int, input().split())

    cost = collections.defaultdict(dict)
    for _ in range(m):
        a, b, c = map(int, input().split())
        cost[a][b] = c

    ans = -float('inf')
    stack = [(1, 0, set())]
    while stack:
        x, cnt, memo = stack.pop()
        if x in memo: return 'inf'
        if x == n: ans = max(ans, cnt)
        for y in cost[x]:
            temp = set(memo)
            temp.add(x)
            stack.append((y, cnt + cost[x][y], temp))
    return ans

if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)

def dfs(now,cost):
    visited[now]=True
    dist[now]=max(dist[now],cost)
    for nx,c in g[now]:
        if nx==n-1:
            for i in xrange(n):
                if visited[i]:
                    canv[i]=True
            dist[nx]=max(dist[nx],cost+c)
        if not visited[nx]:
            dfs(nx,cost+c)
    visited[now]=False
    return

def dfs2(now):
    for nx,c in g[now]:
        if canv[nx] and dist[n-1]-dist[nx]>0:
            print "inf"
            exit()

n,m=map(int,raw_input().split())
g=[[] for _ in xrange(n)]
for i in xrange(m):
    a,b,c=map(int,raw_input().split())
    a-=1;b-=1
    g[a].append((b,c))
dist=[-float("inf")]*n
dist[0]=0
visited=[False]*n
canv=[False]*n
canv[0]=True
dfs(0,0)
dfs2(n-1)
#print dist
print dist[n-1]

Submission status: Wrong Answer

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

    for i in range(N - 1):
        for (u, v, c) in edges:
            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True

    for (u, v, c) in edges:
        if dist[u] + c < dist[v]:
            return None

    return dist[N - 1]

if __name__ == '__main__':
    solve()