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

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

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

costs = [None for x in range(n + 1)]
costs[1] = 0
flg = True
for i in range(n):
    for a, b, c in abc:
        if costs[a] == None:
            continue
        if costs[b] == None or costs[b] < costs[a] + c:
            flg = False
            costs[b] = costs[a] + c
    # for node in nodes[1:]:
    #     for a, b, c in node:
    #         if costs[a] == None:
    #             continue
    #         if costs[b] == None or costs[b] > costs[a] + c:
    #             flg = False
    #             costs[b] = costs[a] + c
#     if flg:
#         print(costs[n])
#         break
#     flg = True
# else:
#     print("inf")

ans = costs[n]
negative = [False for x in range(n + 1)]
for i in range(n - 1):
    for a, b, c in abc:
        if costs[a] == None:
            continue
        if costs[b] == None or costs[b] < costs[a] + c:
            costs[b] = costs[a] + c
            negative[b] = True

        if negative[a] == True:
            negative[b] = True

print(negative[n] and "inf" or ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)

inf = 1<<60

def solve():
    N, M = map(int, sys.stdin.readline().split())
    edges = [None] * M
    Adj = [[] for i in range(N)]

    for i in range(M):
        ai, bi, ci = map(int, sys.stdin.readline().split())
        edges[i] = (ai - 1, bi - 1, -ci)
        Adj[bi - 1].append(ai - 1)

    reachable = [False] * N
    reachable[N - 1] = True
    dfs(N, Adj, reachable, N - 1)

    edges = [(ai, bi, ci) for (ai, bi, ci) in edges if reachable[ai] and reachable[bi]]

    ans = BellmanFord(N, M, edges)

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

    pass

def dfs(N, Adj, visited, u):
    for v in Adj[u]:
        if not visited[v]:
            visited[v] = True
            dfs(N, Adj, visited, v)

def BellmanFord(N, M, edges):
    d = [inf] * N
    d[0] = 0

    for i in range(N - 1):
        for (ai, bi, ci) in edges:
            if d[ai] != inf and d[ai] + ci < d[bi]:
                d[bi] = d[ai] + ci

    for (ai, bi, ci) in edges:
        if d[ai] != inf and d[ai] + ci < d[bi]:
            return None

    return d[N - 1]

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
n, m = map(int, raw_input().split())
graph = {}
visited = {}
# 0: not visited, 1: visited
scores = {}
for i in range(n):
    if i == 0:
        scores[i+1] = 0
    else:
        scores[i+1] = float("inf")
    graph[i+1] = {}

for i in range(m):
    a, b, c = map(int, raw_input().split())
    graph[a][b] = -c
    # {1: {2: 4, 3: 5}, 2: {3: 4}}

for i in range(n):
    for v in graph.keys():
        for e in graph[v].keys():
            if scores[e] > scores[v] + graph[v][e]:
                scores[e] = scores[v] + graph[v][e]

ans = -scores[n]
negative = {}
for i in range(n):
    negative[i+1] = False

for i in range(n+1):
    if negative[n]:
        break
    for v in graph.keys():
        for e in graph[v].keys():
            if scores[v] + graph[v][e] < scores[e]:
                scores[e] = scores[v] + graph[v][e]
                negative[e] = True
                if negative[v]:
                    negative[e] = True

if negative[n]:
    print 'inf'
else:
    print ans

Submission status: Accepted

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**12]*(N-1)# 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]
 
moji2=[0]*N
for n in range(N):
  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]
      moji2[b[m]-1]=1
      if moji2[N-1]:
        print("inf")
        sys.exit()
print(V[N-1])

Submission status: Accepted

Solution code:
# Bellman-Ford
n, m = map(int, raw_input().split())
a, b, c = [], [], []
for i in xrange(m):
    at, bt, ct = map(int, raw_input().split())
    a.append(at - 1)
    b.append(bt - 1)
    c.append(ct)
# step1 : initialize
point = [-1e9 * m - 1] * n
point[0] = 0
# step2 : relaxation
for i in xrange(n+1):
    for j in xrange(m):
        if point[b[j]] < point[a[j]] + c[j]:
            point[b[j]] = point[a[j]] + c[j]
# step3 : check
looped = [False] * n
for i in xrange(n):
    for j in xrange(m):
        if point[b[j]] < point[a[j]] + c[j]:
            looped[b[j]] = True
        if looped[a[j]] == True:
            looped[b[j]] = True
if looped[n-1]:
    print("inf")
else:
    print(point[n-1])

Submission status: Accepted

Solution code:
import math

INF = float("inf")

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

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

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

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

print(-d[V-1] if cnt[V-1] < V else "inf")

Submission status: Accepted

Solution code:

MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = 10 ** 13

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = [-INF for x in range(MAX_N)]
    update_cnt = [0 for x in range(MAX_N)]
    result = -INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]
        if (visited[pos] > cost):
            continue
        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]

            if (cost + nxt_cost > visited[nxt] and update_cnt[nxt] < MAX_M):
                visited[nxt] = cost + nxt_cost
                update_cnt[nxt] += 1
                que.append([nxt, nxt_cost + cost])

    if (update_cnt[N - 1] >= MAX_N):
        return (0, False)
    return (visited[N - 1], True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = [[] for x in range(MAX_N)]
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        print ('inf')
    else:
        print (res)

Submission status: Accepted

Solution code:
INF = 10**15
N, M = map(int, raw_input().split())
G = [map(int, raw_input().split()) for _ in range(M)]

def run():
    cost = [-INF for i in range(N+1)]
    cost[1] = 0
    for _ in range(N+1):
        for a, b, c in G:
            if cost[a] == INF:
                continue
            if cost[a] + c > cost[b]:
                cost[b] = cost[a] + c
    looped = [False for i in range(N+1)]
    for _ in range(N+1):
        for a, b, c in G:
            if cost[a] == INF:
                continue
            if cost[a] + c > cost[b]:
                looped[b] = True
            if looped[a]:
                looped[b] = True
    return "inf" if looped[N] else cost[N]
print run()

Submission status: Accepted

Solution code:
N, M = list(map(int, input().split()))
a = []
b = []
c = []

for o in range(M):
    a_i, b_i, c_i = list(map(int, input().split()))
    a.append(a_i)
    b.append(b_i)
    c.append(c_i)


cost = [-float('inf') for i in range(N + 1)]
cost[1] = 0
flag = True

for _ in range(N - 1):
    for k in range(M):
        cost[b[k]] = max(cost[b[k]], cost[a[k]] + c[k])

cost_n = cost[N]

def check():
    for l in range(M):
        cost[b[l]] = max(cost[b[l]], cost[a[l]] + c[l])
    if cost[N] > cost_n:
        return 'inf'
    return cost[N]


print(check())

Submission status: Accepted

Solution code:
#coding=UTF-8

#ゴールに関係無い袋小路で永パされると、探索が収束しない
#かつ答えがinfでないということで 修正

#表にあるかを尋ねるのが重いので
#データ構造を変えて回避する
mozir=input()
hyo=mozir.split(' ')

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

#idx番目の都市に繋っている道とコストのタプルを持つリスト
tuuro=[]
# [] はコピーがしんどいものだったりするので
# 参照でごまかしたりしてくる
# なので1個づつ書いている
for idx in range(0,N,1):
    tuuro.append([])


A=[]
B=[]

for idx in range(0,M,1):
    mozir=input()
    hyo=mozir.split(' ')
    tuuro[int(hyo[0])-1].append((int(hyo[1])-1,int(hyo[2])))

#print(tuuro)
#普通の経路探索のようなことをする
#永パ
tmp_score=[None]*N #マイナス点のときもある
tmp_score[0]=0
tansaku=[0]
loopconut=0
while len(tansaku) > 0:
    loopconut=loopconut+1
    next_tansaku=[]
    for mono in tansaku:
        for deru in tuuro[mono]:
            kouho_ten=tmp_score[mono]+deru[1]
            if tmp_score[deru[0]] == None or kouho_ten > tmp_score[deru[0]]:
                tmp_score[deru[0]]=kouho_ten
                next_tansaku.append(deru[0])

    tansaku=list(set(next_tansaku))
    if loopconut==N-1:
        tmp_ans=tmp_score[N-1] #cannot be None
    elif loopconut==2*N-1:
        #period must be eqal or less than N
        if tmp_score[N-1] > tmp_ans:
            print('inf')
            break
        else:
            #関係の無い無限ループ
            print(tmp_score[N-1])
            break
else:
    print(tmp_score[N-1])

Submission status: Accepted

Solution code:
import sys
from math import sqrt

inf = 1<<60

def solve():
    N, M = map(int, sys.stdin.readline().split())

    edges = [None] * M
    # Adj = [[] for i in range(N)]
    Adjr = [[] for i in range(N)]

    for i in range(M):
        ai, bi, ci = map(int, sys.stdin.readline().split())
        edges[i] = (ai - 1, bi - 1, -ci)
        # Adj[ai - 1].append(bi - 1)
        Adjr[bi - 1].append(ai - 1)

    reachable = [False] * N
    dfs(N, M, Adjr, reachable, N - 1)

    edges = [(u, v, c) for (u, v, c) in edges if reachable[u] and reachable[v]]

    ans = BellmanFord(N, M, edges)

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

def dfs(N, M, Adj, visited, u):
    visited[u] = True

    for v in Adj[u]:
        if not visited[v]:
            dfs(N, M, Adj, visited, v)

def BellmanFord(N, M, edges):
    d = [inf] * N
    d[0] = 0

    for i in range(N):
        flag = False

        for (u, v, c) in edges:
            if d[u] != inf and d[u] + c < d[v]:
                d[v] = d[u] + c
                flag = True

        if not flag:
            break

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

    return d[N - 1]

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
from math import sqrt

inf = 1<<60

def solve():
    N, M = map(int, sys.stdin.readline().split())

    edges = [None] * M
    Adj = [[] for i in range(N)]
    Adjr = [[] for i in range(N)]

    for i in range(M):
        ai, bi, ci = map(int, sys.stdin.readline().split())
        edges[i] = (ai - 1, bi - 1, -ci)
        Adj[ai - 1].append(bi - 1)
        Adjr[bi - 1].append(ai - 1)

    visitable = [False] * N
    dfs(N, M, Adj, visitable, 0)

    reachable = [False] * N
    dfs(N, M, Adjr, reachable, N - 1)

    valid = [visitable[i] and reachable[i] for i in range(N)]

    edges = [(u, v, c) for (u, v, c) in edges if valid[u] and valid[v]]

    ans = BellmanFord(N, M, edges, valid)

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

def dfs(N, M, Adj, visited, u):
    visited[u] = True

    for v in Adj[u]:
        if not visited[v]:
            dfs(N, M, Adj, visited, v)

def BellmanFord(N, M, edges, valid):
    d = [inf] * N
    d[0] = 0

    for i in range(N):
        flag = False

        for (u, v, c) in edges:
            if d[u] != inf and d[u] + c < d[v]:
                d[v] = d[u] + c
                flag = True

        if not flag:
            break

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

    return d[N - 1]

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000)

def set_enable_goal(cur_node, back_paths, enable_goal):
    if cur_node in back_paths:
        for next_node in back_paths[cur_node]:
            if enable_goal[next_node - 1] == 0:
                enable_goal[next_node - 1] = 1
                set_enable_goal(next_node, back_paths, enable_goal)


N, M = map(int, input().split())
MIN = float('-inf')
INF_LIMIT = -MIN

back_paths = {}
all_paths = {}
for i in range(M):
    a, b, c = map(int, input().split())
    if a in all_paths:
        all_paths[a].append((b, c))
    else:
        all_paths[a] = [(b, c)]

    if b in back_paths:
        back_paths[b].append(a)
    else:
        back_paths[b] = [a]


# path cut
enable_goal= [0 for i in range(N)]
enable_goal[N - 1] = 1
set_enable_goal(N, back_paths, enable_goal)

scores = [MIN for i in range(N)]
scores[0] = 0

is_inf = False
for n in range(N):
    for a in all_paths.keys():
        if not enable_goal[a - 1]:
            continue
        for b, c in all_paths[a]:
            if not enable_goal[b - 1]:
                continue
            scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)

# loop check
if not is_inf:
    prev_score = scores[N - 1]
    for a in all_paths.keys():
        if not enable_goal[a - 1]:
            continue
        for b, c in all_paths[a]:
            if not enable_goal[b - 1]:
                continue
            scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)
    if prev_score != scores[N - 1]:
        is_inf = True


if is_inf:
    print('inf')
else:
    print(scores[N - 1])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000)

def set_enable_goal(cur_node, back_paths, enable_goal):
    if cur_node in back_paths:
        for next_node in back_paths[cur_node]:
            if enable_goal[next_node - 1] == 0:
                enable_goal[next_node - 1] = 1
                set_enable_goal(next_node, back_paths, enable_goal)


N, M = map(int, input().split())
MIN = float('-inf')
INF_LIMIT = -MIN

back_paths = {}
all_paths = {}
for i in range(M):
    a, b, c = map(int, input().split())
    if a in all_paths:
        all_paths[a].append((b, c))
    else:
        all_paths[a] = [(b, c)]

    if b in back_paths:
        back_paths[b].append(a)
    else:
        back_paths[b] = [a]


# path cut
enable_goal= [0 for i in range(N)]
enable_goal[N - 1] = 1
set_enable_goal(N, back_paths, enable_goal)

for a, paths in all_paths.items():
    if not enable_goal[a - 1]:
        all_paths[a] = []
    else:
        valid_paths = []
        for b, c in paths:
            if enable_goal[b - 1]:
                valid_paths.append((b, c))
        all_paths[a] = valid_paths


scores = [MIN for i in range(N)]
scores[0] = 0

is_inf = False
for n in range(N):
    for a in all_paths.keys():
        for b, c in all_paths[a]:
            scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)

# loop check
if not is_inf:
    prev_score = scores[N - 1]
    for a in all_paths.keys():
        for b, c in all_paths[a]:
            scores[b - 1] = max(scores[b - 1], scores[a - 1] + c)
    if prev_score != scores[N - 1]:
        is_inf = True


if is_inf:
    print('inf')
else:
    print(scores[N - 1])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
import numpy as np
N, M = map(int, raw_input().split())
R = [map(int, raw_input().split()) for i in xrange(M)] 

score = [None for _ in xrange(N+1)]
score[1] = 0
for _ in xrange(N):
    for  a, b, c in R:
        if score[a] != None:
          score[b] = max(score[b], score[a] + c) 
v1 = score[-1]

for _ in xrange(N):
    for  a, b, c in R:
          if score[a] != None:
            score[b] = max(score[b], score[a] + c)
v2 = score[-1]

if v1 != v2:
    print "inf"
else:
    print v2

Submission status: Accepted

Solution code:
import sys

inf = 1<<60

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

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

    ans = BellmanFord(N, M, edges)

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

def BellmanFord(N, M, edges):
    d = [inf] * N
    d[0] = 0

    for i in range(N - 1):
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                d[v] = d[u] + c

    for i in range(N):
        for (u, v, c) in edges:
            if d[u] + c < d[v]:
                if v == N - 1:
                    return None

                d[v] = d[u] + c

    return d[N - 1]

if __name__ == '__main__':
    solve()

Submission status: Accepted

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

from collections import defaultdict
E = []

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

def reachable_vertices(neighbor, s):
  V = set()
  V.add(s)
  stack=[s]
  while stack:
    v = stack.pop()
    for u in neighbor[v]:
      if u not in V:
        V.add(u)
        stack.append(u)
  return V

def neighbor_dict(E):
  neighbor = defaultdict(list)
  for a,b,c in E:
    neighbor[a].append(b)
  return neighbor

def rev_neighbor_dict(E):
  neighbor = defaultdict(list)
  for a,b,c in E:
    neighbor[b].append(a)
  return neighbor

def degenerate_graph(V, E):
  d = {v:i for i,v in enumerate(sorted(V))}
  return len(V), [(d[a],d[b],c) for a,b,c in E if a in V and b in V]

# only vertices that are reachable from 1 or N
N,E = degenerate_graph(reachable_vertices(neighbor_dict(E), 0), E)
N,E = degenerate_graph(reachable_vertices(rev_neighbor_dict(E), N-1), E)
score = [float('-inf')]*N
score[0] = 0


i = 0
updated=True
while updated:
  if i == N:
    print('inf')
    break

  updated = False
  for a,b,w in E:
    if score[b] < score[a] + w:
      score[b] = score[a] + w
      updated = True
  i += 1
else:
  print(score[N-1])

Submission status: Accepted

Solution code:
#coding:utf-8

import sys
from collections import defaultdict

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

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

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


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

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

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

    is_inf = False
    if is_cycle:
        route_node = N
        while route_node != 1:
            route_node = pre[route_node]
            if route_node in cycle_node:
                is_inf = True
                break


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

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
dist = [-10**18] * n
edge = []
for i in range(m):
    a, b, c = map(int, input().split())
    edge.append((a - 1, b - 1, c))
dist[0] = 0
for i in range(n):
    for i in edge:
        a, b, c = i
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            updated = True
ans = dist[n - 1]
for i in range(n):
    for i in edge:
        a, b, c = i
        if dist[a] + c > dist[b]:
            dist[b] = dist[a] + c
            updated = True
if ans == dist[n - 1]:
    print(dist[n - 1])
else:
    print("inf")

Submission status: Accepted

Solution code:
import math 
from collections import defaultdict as dd
def main():
    N, M = map(int, input().split())

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

    dp = [-float('inf')]*N
    dp[0] = 0
    updated = set([0])
    for count in range(1, 2*N+1):  # N
        preupdated = list(updated)
        updated = set([])
        for a in preupdated:
            for b,c in MAP[a]:
                if max(dp[b], dp[b]) < dp[a] + c:
                    updated.add(b)
                    dp[b] = dp[a] + c
        if count == N-1:
            tmp = dp[N-1]

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


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

Submission status: Accepted

Solution code:
N, M = map(int, raw_input().split())
D = [map(int, raw_input().split()) for _ in range(M)]
 
score = [None for _ in range(N+1)]
score[1] = 0
 
for _ in range(N):
    for a, b, c in D:
        if score[a] != None:
            score[b] = max(score[b], score[a] + c)
v1 = score[-1]
for _ in range(N):
    for a, b, c in D:
        if score[a] != None:
            score[b] = max(score[b], score[a] + c)
v2 = score[-1]
 
if v1 != v2:
    print "inf"
else:
    print v2

Submission status: Accepted

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

from collections import defaultdict
neighbor = defaultdict(list)
rev_neighbor = defaultdict(list)
E = []

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

def reachable_vertices(neighbor, s):
  V = set()
  V.add(s)
  stack=[s]
  while stack:
    v = stack.pop()
    for u in neighbor[v]:
      if u not in V:
        V.add(u)
        stack.append(u)
  return V

# only vertices that are reachable from 1 or N
V = reachable_vertices(neighbor, 0) & reachable_vertices(rev_neighbor, N-1)

E = [(a,b,c) for a,b,c in E if a in V or b in V]
score = defaultdict(lambda: float('-inf'))
score[0] = 0


i = 0
updated=True
while updated:
  if i == len(V):
    print('inf')
    break

  updated = False
  for a,b,w in E:
    if score[b] < score[a] + w:
      score[b] = score[a] + w
      updated = True
  i += 1
else:
  print(score[N-1])

Submission status: Accepted

Solution code:


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

from collections import defaultdict
neighbor = defaultdict(list)
Rneighbor = defaultdict(list)
edges = []
for i in range(M):
  a,b,c = map(int, input().split())
  a,b = a-1, b-1
  edges += [(a,b,c)]
  neighbor[a].append(b)
  Rneighbor[b].append(a)

# only vertices that are reachable from 1 or N
v1 = set()
v1.add(0)
stack = [0]
while stack:
  v = stack.pop()
  for u in neighbor[v]:
    if u not in v1:
      v1.add(u)
      stack.append(u)

vn = set()
vn.add(N-1)
stack = [N-1]
while stack:
  v = stack.pop()
  for u in Rneighbor[v]:
    if u not in vn:
      vn.add(u)
      stack.append(u)

V = v1 & vn

edges = [(a,b,c) for a,b,c in edges if a in V and b in V]
score = [float('-inf')]*N
score[0] = 0

updated = True
i = 0

positive_cycle = False

while updated:
  if i == len(V):
    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-1])

Submission status: Accepted

Solution code:
import sys
from collections import Counter

sys.setrecursionlimit(10**7)
 
inf = 1<<100
 
def solve():
    N, M = map(int, input().split())
    edges = [None]*M
    Adj = [[] for i in range(N)]
 
    for i in range(M):
        ui, vi, ci = map(int, sys.stdin.readline().split())
        ui, vi = ui - 1, vi - 1
        edges[i] = (ui, vi, -ci)
        Adj[ui].append(vi)

    visitable = [False]*N

    dfs(N, M, Adj, visitable, 0)

    reachable = [False]*N
    reachable[0] = True
    reachable[N - 1] = True

    for u in range(1, N - 1):
        visited = [False]*N

        dfs(N, M, Adj, visited, u)

        if visited[N - 1]:
            reachable[u] = True
 
    ans = Bellmanford(N, M, edges, visitable, reachable)
 
    if ans is not None:
        print(-ans)
    else:
        print('inf')

def dfs(N, M, Adj, visitable, u):
    visitable[u] = True

    for v in Adj[u]:
        if not visitable[v]:
            dfs(N, M, Adj, visitable, v)

def Bellmanford(N, M, edges, visitable, reachable):
    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

                if visitable[v] and reachable[v]:
                    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: Accepted

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 + 1):
        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):
                        d = dist[N - 1]
                    if (i == N):
                        if d != dist[N - 1]:
                            return 'inf'
    return -dist[N - 1]

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

Submission status: Accepted

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=self.distance[-1]
		for i in range(length-1):
			update()
		if memo!=self.distance[-1]:
			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: Accepted

Solution code:
n,m = map(int, input().split())
g = [[] for i in range(n)]
for i in range(m):
    a,b,c = map(int, input().split())
    a -= 1
    b -= 1
    g[a].append((b, -c))

# Bellman Ford
dist = [float('inf') for i in range(n)]
dist[0] = 0
prev = [-1 for i in range(n)]
negative_cycle = False
for k in range(n*2):
    for i in range(n):
        for dst, cst in g[i]:
            src = i
            if dist[dst] > dist[src] + cst:
                dist[dst] = dist[src] + cst
                prev[dst] = src
                if k >= n-1 and dst == n-1:
                    dist[dst] = -float('inf')
                    negative_cycle = True

if negative_cycle:
    print('inf')
else:
    print(-dist[n-1])

Submission status: Accepted

Solution code:
import sys
import random

def rd():
        return sys.stdin.readline().rstrip()

def rdi():
        return [ long(x) for x in rd().split() ]

INF = 1000000000 * 2000 + 1

N, M = rdi()
a = []
b = []
c = []
for i in range(M):
        ai, bi, ci = rdi()
        a.append(ai)
        b.append(bi)
        c.append(ci)

t = {}
for i in range(N):
        t[i+1] = []
for i in range(M):
        ai = a[i]
        bi = b[i]
        ci = c[i]
        t[ai].append( (bi, ci) )


w = { 1: (0, []) }
q = [ 1 ]
while q:
        ai = q.pop()
        s = w[ai][0]
        p = w[ai][1]
        for bi, ci in t[ai]:
                if s == INF:
                        s2 = INF
                else:
                        s2 = s + ci
                if bi not in w:
                        w[bi] = (s2, p+[bi])
                        q.append(bi)
                else:
                        if s2 > w[bi][0]:
                                if bi in p:
                                        s2 = INF
                                w[bi] = (s2, p+[bi])
                                q.append(bi)

sn = w[N][0]
if sn == INF:
        print "inf"
else:
        print sn

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin


def na(): return map(int, stdin.readline().split())


def ns(): return stdin.readline().strip()

def bf(es, n, start, ved):
    I = 999999999999999999
    d = [I] * n
    d[start] = 0

    for i in range(n-1):
        updated = False
        for e in es:
            if not ved[e[0]]: continue
            if not ved[e[1]]: continue
            if d[e[0]] + e[2] < d[e[1]]:
                d[e[1]] = d[e[0]] + e[2]
                updated = True
        if not updated: break
    for e in es:
        if not ved[e[0]]: continue
        if not ved[e[1]]: continue
        if d[e[0]] + e[2] < d[e[1]]:
            return None
    return d

def go(start, g, ind):
    n = len(g)
    ved = [False] * n
    q = [start]
    j = 0
    ved[start] = True
    while(j < len(q)):
        cur = q[j]
        for e in g[cur]:
            if not ved[e[ind]]:
                ved[e[ind]] = True
                q.append(e[ind])
        j += 1
    return ved

n,m = na()
es = []

for i in range(m):
    a,b,c = na()
    es.append([a-1,b-1,-c])

g = [[] for _ in range(n)]
for e in es:
    g[e[0]].append(e)

ig = [[] for _ in range(n)]
for e in es:
    ig[e[1]].append(e)


ved = go(0, g, 1)
ived = go(n-1, ig, 0)

for i in range(n):
    ved[i] &= ived[i]

res = bf(es, n, 0, ved)
if res:
    print(-res[n-1])
else:
    print("inf")