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:
n, m = map(int, input().split())
abc = [list(map(int, input().split())) for x in range(m)]

nodemap = [[] for x in range(n + 1)]

traveled_template = [False for x in range(n + 1)]

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

# for nodes in nodemap:
#     print(nodes)

que = [[nodemap[1], 0, traveled_template[:]]]
maxn = -(10**10)
while que:
    nodes, value, traveled = que.pop()
    for node in nodes:
        t = traveled[:]
        now = node[0]
        # print(node, value + node[1])
        # print(node, value, now, n)
        if t[now]:
            print("inf")
            __import__("sys").exit()
        else:
            next_value = value + node[1]
            if now == n:
                maxn = max(maxn, next_value)
            t[now] = True
            que.append([nodemap[now], next_value, t])

print(maxn)

Submission status: Wrong Answer

Solution code:
n,m = map(int, raw_input().split())
d = {}
for i in range(m):
  a,b,c = map(int, raw_input().split())
  if a in d:
    d[a].append((b,c))
  else:
    d[a] = [(b,c)]


loop = [False] * (n+1)
anslist = []

# point, total, visited, flag
q = [(1,0,set())]

while len(q) > 0:
  p,t,v = q.pop(0)

  if p not in v:
    v.add(p)

  if p == n:
    anslist.append((t,v))

  # print p,t,v
  if p not in d:
    continue

  for b,c in d[p]:
    if b in v:
      loop[a] = True
      loop[b] = True
    else:
      q.append((b,t+c,v.copy()))

ans = -1 * float('inf')
for t,v in anslist:
  for vi in v:
    if vi in loop:
      print 'inf'
      exit()
  ans = max(ans, t)

print ans

Submission status: Wrong Answer

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

W = [['inf' for j in range(N)] for i in range(N)]
y = ['inf' for i in range(N)]
y_t = ['inf' 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 = 'inf'
        for k in range(N):
            yj_temp = 'inf'
            if y[k]!='inf' and W[k][j]!='inf':
                yj_temp=y[k]+W[k][j]
            if yj_temp!='inf':
                if yj_temp=='inf':
                    yj_max = yj_temp
                elif yj_max<yj_temp:
                    yj_max = yj_temp
        y_t[j]=yj_max
    if y==y_t:
        flag = True
        break
    y = y_t
    

print y[N-1]

Submission status: Wrong Answer

Solution code:
def update(edge):
    v = edge[1]
    u = edge[0]
    w = edge[2]

    if (dist[v] > dist[u] + w and dist[u] < float('inf')):
        dist[v] = dist[u] + w
        return True

    return False


v, e = map(int, raw_input().split())
dist = [float('inf') for i in range(v)]
edgelist = []

for i in range(e):
    v1, v2, w = map(int, raw_input().split())
    v1 -= 1
    v2 -= 1
    w = -w
    edgelist.append( [v1, v2, w] )

dist[0] = 0
flag = False
for i in range(v-1):
    for edge in edgelist:
        up = update(edge)
        flag = flag | up
    if not flag:
        break

neg_cyc = False
for edge in edgelist:
    neg_cyc = update(edge)

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

Submission status: Wrong Answer

Solution code:
import math

INF = float("inf")

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

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


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

    for i in range(V):
        for e in edge:
            if d[e[1]] < d[e[0]] + e[2]:
                d[e[1]] = d[e[0]] + e[2]
                if i == V - 1:
                    return True

    return False


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

    while True:
        update = False
        for e in edge:
            if not math.isinf(d[e[0]]) and d[e[1]] < d[e[0]] + e[2]:
                update = True
                d[e[1]] = d[e[0]] + e[2]
        if not update:
            break
    print(d[V])

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**15] * 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 > n:
        print("inf")
        break

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]+["inf"]*(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 isinstance(V[b[m]-1],int) and isinstance(V[a[m]-1],int):#共に有限の時はやる
      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
    if isinstance(V[b[m]-1],str) and isinstance(V[a[m]-1],int):#始点が有限の時はやる
      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 isinstance(V[b[m]-1],int) and isinstance(V[a[m]-1],int):
    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:
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]=-(len(edges)*(10**9))
        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)
    g.add_edge([b,a],c)

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

Submission status: Wrong Answer

Solution code:
def read_data():
    N, M = map(int, input().split())
    Es = [[] for _ in range(N)]
    Cs = [[float('inf')] * N for n in range(N)]
    for m in range(M):
        a, b, c = map(int, input().split())
        Es[a - 1].append(b - 1)
        Cs[a - 1][b - 1] = -c
    return N, M, Es, Cs

def solve(N, M, Es, Cs):
    dist = [float('inf')] * N
    dist[0] = 0
    for i in range(N):
        for v in range(N):
            Cv = Cs[v]
            for e in Es[v]:
                c = Cv[e]
                if dist[v] != float('inf') and dist[e] > dist[v] + c:
                    dist[e] = dist[v] + c
                    if (i == N - 1):
                        return 'inf'
    return -dist[N - 1]

N, M, Es, Cs = read_data()
print(solve(N, M, Es, Cs))

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-1):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

ans = d[N-1]
if N*M >= 2000*1000:
    print("inf")
    exit(0)

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

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

Submission status: 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-1):
    for j in range(M):
        if d[A[j]] != -INF and d[B[j]] < d[A[j]] + C[j]:
            d[B[j]] = d[A[j]] + C[j]

ans = d[N-1]
if N*M >= 2000*1000:
    print(ans)
    exit(0)

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

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

Submission status: Wrong Answer

Solution code:
# coding: utf-8

import pdb


# Step 1: For each node prepare the destination and predecessor
def initialize(graph, source):
    d = {} # Stands for destination
    p = {} # Stands for predecessor
    for node in graph:
        d[node] = float('Inf') # We start admiting that the rest of nodes are very very far
        p[node] = None
    d[source] = 0 # For the source we know how to reach
    return d, p

def relax(node, neighbour, graph, d, p):
    # If the distance between the node and the neighbour is lower than the one I have now
    if d[neighbour] > d[node] + graph[node][neighbour]:
        # Record this lower distance
        d[neighbour]  = d[node] + graph[node][neighbour]
        p[neighbour] = node

def bellman_ford(graph, source):
    d, p = initialize(graph, source)
    for i in range(len(graph)-1): #Run this until is converges
        for u in graph:
            for v in graph[u]: #For each neighbour of u
                relax(u, v, graph, d, p) #Lets relax it

    # Step 3: check for negative-weight cycles
    for u in graph:
        for v in graph[u]:
            assert d[v] <= d[u] + graph[u][v]

    return d, p

if __name__ == "__main__":
	n, m = map(int, input().split())
	gr = {k: dict() for k in range(1, n+1)}
	for _ in range(m):
		a, b, c = map(int, input().split())
		gr[a][b] = -c

	try:
		d, p = bellman_ford(gr, 1)
		print(-d[n])
	except:
		print('inf')

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]=-(len(edges)*(10**9))
        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
                elif  dists[e.node_from]<dists[e.node_to]+e.cost:
                    dists[e.node_from]=dists[e.node_to]+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 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:
            if n in memo:
                return 'inf'
            continue

        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 math

INF = float("inf")

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

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


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

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


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

    while True:
        update = False
        for e in edge:
            if not math.isinf(d[e[0]]) and d[e[1]] < d[e[0]] + e[2]:
                update = True
                d[e[1]] = d[e[0]] + e[2]
        if not update:
            break
    print(d[V])

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]=-(len(edges)*(10**9))
        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 or dists[e.node_from]<dists[e.node_to]+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<<100
 
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 not flag:
            break

        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,raw_input().split())

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

W = [[-2*(10**9)-1 for j in range(N)] for i in range(N)]
y = [-2*(10**9)-1 for i in range(N)]
y_t = [-2*(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 = -2*(10**9)-1
        for k in range(N):
            yj_temp = -2*(10**9)-1
            if y[k]!=-2*(10**9)-1 and W[k][j]!=-2*(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
    


print y[N-1]

Submission status: Wrong Answer

Solution code:
import math

INF = float("inf")

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

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


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

    for i in range(V):
        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 == V - 1:
                    return True
    return False


if find_loop():
    print("inf")
else:
    d = [-INF for _ in range(V + 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[V])

Submission status: Wrong Answer

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

nodemap = [[] for x in range(n + 1)]

traveled_template = [False for x in range(n + 1)]

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

# for nodes in nodemap:
#     print(nodes)

que = [[nodemap[1], 0, traveled_template[:]]]
maxn = -(10**10)
while que:
    nodes, value, traveled = que.pop()
    for node in nodes:
        # print(node, value + node[1])
        if traveled[node[0]]:
            print("inf")
            __import__("sys").exit()
        else:
            next_value = value + node[1]
            now = node[0]
            if now == n:
                maxn = max(maxn, next_value)
            traveled[now] = True
            que.append([nodemap[now], next_value, traveled[:]])

print(maxn)

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]=-(len(nodes)*(10**9))
        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)
#print(res)
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:
N,M = map(int,raw_input().split())

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

W = [[-2*(10**9)-1 for j in range(N)] for i in range(N)]
y = [-2*(10**9)-1 for i in range(N)]
y_t = [-2*(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 = -2*(10**9)-1
        for k in range(N):
            yj_temp = -2*(10**9)-1
            if y[k]!=-2*(10**9)-1 and W[k][j]!=-2*(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 'infty'

Submission status: Wrong Answer

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

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

W = [[-2*(10**9)-1 for j in range(N)] for i in range(N)]
y = [-2*(10**9)-1 for i in range(N)]
y_t = [-2*(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 = -2*(10**9)-1
        for k in range(N):
            yj_temp = -2*(10**9)-1
            if y[k]!=-2*(10**9)-1 and W[k][j]!=-2*(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:


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

score = [float('-inf')]*(N+1)
score[1] = 0
edges = [tuple(map(int, input().split())) for _ in range(M)]
edges.sort() #　速くなる気がする


updated = True
i = 0

positive_cycle = False

while updated:
  if i == N:
    positive_cycle = True
    break

  updated = False
  for a,b,w in edges:
    if score[b] < score[a] + w:
      score[b] = score[a] + w
      updated = True
  i += 1

if positive_cycle:
  print('inf')
else:
  print(score[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]=-999**9
        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)
#print(res)
if not res:
    print("inf")
else:
    print(res[N])