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: Runtime Error

Solution code:
import collections
import heapq
import math

# python 3 only!!!
import collections
import math


class Graph:
    def __init__(self):
        self.vertices = set()
        self.successors = collections.defaultdict(list)
        self.weights = {}

    def add_vertex(self, label):
        self.vertices.add(label)

    def add_edge(self, begin, end, weight):
        self.successors[begin].append(end)
        self.weights[(begin, end)] = weight


def dijkstra(graph, start):
    queue = []
    closed = set()
    dist = dict.fromkeys(graph.vertices, -math.inf)
    prev = dict.fromkeys(graph.vertices, None)

    heapq.heappush(queue, (0, start))
    dist[start] = 0

    while len(queue) != 0:
        _, v = heapq.heappop(queue)
        closed.add(v)

        for u in graph.successors[v]:
            cost = dist[v] + graph.weights[(v, u)]
            if u not in closed and u not in [_[1] for _ in queue]:
                prev[u] = v
                dist[u] = cost
                heapq.heappush(queue, (cost, u))
            elif u in [_[1] for _ in queue]:
                if cost > dist[u]:
                    prev[u] = v
                    dist[u] = cost

    return dist, prev


def cyclic(graph):
    """Return True if the directed graph has a cycle.
    The graph must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph)]
    while stack:
        for v in stack[-1]:
            if v in path_set:
                return True
            elif v not in visited:
                visited.add(v)
                path.append(v)
                path_set.add(v)
                stack.append(iter(graph.get(v, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False


def main():
    g = Graph()

    n, m = map(int, input().split())

    for i in range(m):
        a, b, c = map(int, input().split())
        g.add_vertex(a)
        g.add_vertex(b)
        g.add_edge(a, b, c)

    if cyclic(g.successors):
        print('inf')
        exit(0)

    # print(dijkstra(g, 1)[0])

    print(dijkstra(g, 1)[0][n])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import defaultdict
sys.setrecursionlimit(100000)

def has_loop_f(now, path_dic, weight_dic, visited_path):
    next_cand = path_dic[now]

    if len(next_cand) == 0:
        return (False, ([], 0))

    # sys.stderr.write(str(next_cand))
    # sys.stderr.write("\n")
    for next_v in next_cand:
        if next_v in visited_path:
            weight = 0
            start_v = next_v
            now_v = next_v
            loop_path = [now_v]
            for v in visited_path[::-1]:
                weight += weight_dic[(now_v, v)]
                loop_path.append(v)
                if v == start_v:
                    break
                else:
                    now_v = v
            return (True, (loop_path[::-1], weight))
        else:
            next_visited_path = visited_path + [next_v]
            # sys.stderr.write(str((next_v, next_visited_path)))
            # sys.stderr.write("\n")
            b, tpl = has_loop_f(next_v, path_dic, weight_dic, next_visited_path)
            if b == True and tpl[1] > 0:
                return (b, tpl)
            else:
                continue

    return (False, ([], 0))

def calc_max_weight(end, rev_path_dic, weight_dic):
    if end == 1:
        return 0
    else:
        return max([calc_max_weight(prev, rev_path_dic, weight_dic) + weight_dic[(prev, end)] for prev in rev_path_dic[end]])

def main():
    line = sys.stdin.readline()
    lst = line.split()
    n = int(lst[0])
    m = int(lst[1])

    weight_dic = {}
    path_dic = defaultdict(list)
    rev_path_dic = defaultdict(list)
    for line in sys.stdin:
        lst = line.split()
        a = int(lst[0])
        b = int(lst[1])
        c = int(lst[2])
        path_dic[a].append(b)
        rev_path_dic[b].append(a)
        weight_dic[(a,b)] = c

    #まずは回路を検出
    # sys.stderr.write(str((1, [1])))
    # sys.stderr.write("\n")
    b, (loop_path, loop_weight) = has_loop_f(1, path_dic, weight_dic, [1])
    if b == True and loop_weight > 0:
        print("inf")
        return 0

    ans = calc_max_weight(n, rev_path_dic, weight_dic)
    print("%d" % ans)
    return 0

if __name__ == '__main__':
    sys.exit(main())

Submission status: Runtime Error

Solution code:
import math

def int_input():
    line = input()
    return [int(x) for x in line.split()]

n, m = int_input()
graph = {}

for i in range(n):
    graph[i+1] = {}

for i in range(m):
    a, b, c = int_input()
    graph[a][b] = c

max_score = 0
def walk(graph, current, stack, acc_score, has_loop):
    has_loop = False
    for dest, _ in graph[current].items():
        if dest in stack:
            has_loop = True

    if current == n:
        if has_loop:
            return math.inf
        return acc_score

    if not graph[current]:
        return 0

    stack_next = stack.copy()
    stack_next[current] = True

    graph_next = graph.copy()
    del graph_next[current]

    scores = []
    for dest, score in graph[current].items():
        if dest not in stack:
            scores.append(walk(graph_next, dest, stack_next, acc_score+score, has_loop))

    return max(scores)

print(walk(graph, 1, {}, 0, False))

Submission status: Runtime Error

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_max=='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
    
if flag:
    print y[N-1]
else:
    print 'inf'

Submission status: Runtime Error

Solution code:
def dstar(use, i):
    connect = ver[i]
    use.append(i)
    for k in range(n):
        if connect[k] != 0.5:
            if k in use:
                if weigth[i] + k > 0:
                    if k == n-1:
                        print('inf')
                        exit()
                    else:
                        weigth[k] = 10**17
                        return
                else:
                    return
            if weigth[k] < weigth[i] + connect[k]:
                weigth[k] = weigth[i] + connect[k]
            dstar(use[:], k)


n, m = [int(x) for x in input().split(' ')]
ver = [[0.5 for x in range(n)] for y in range(n)]
for i in range(m):
    a, b, c = [int(x) for x in input().split(' ')]
    ver[a-1][b-1] = c
weigth = [0] + [-10**12 for x in range(n-1)]
dstar([], 0)
if weigth[n-1] > 10**13:
    print('inf')
else:
    print(weigth[n-1])

Submission status: Runtime Error

Solution code:
import collections
import heapq
import math


class WeightedDigraph:
    def __init__(self):
        self.vertices = set()
        self.successors = collections.defaultdict(list)
        self.weights = {}

    def add_vertex(self, label):
        self.vertices.add(label)

    def add_edge(self, begin, end, weight):
        self.successors[begin].append(end)
        self.weights[(begin, end)] = weight


def dijkstra(graph, start):
    queue = []
    closed = set()
    dist = dict.fromkeys(graph.vertices, math.inf)
    prev = dict.fromkeys(graph.vertices, None)

    heapq.heappush(queue, (0, start))
    dist[start] = 0

    while len(queue) != 0:
        _, v = heapq.heappop(queue)
        closed.add(v)

        for u in graph.successors[v]:
            cost = dist[v] + graph.weights[(v, u)]
            if u not in closed and u not in [_[1] for _ in queue]:
                prev[u] = v
                dist[u] = cost
                heapq.heappush(queue, (cost, u))
            elif u in [_[1] for _ in queue]:
                if cost > dist[u]:
                    prev[u] = v
                    dist[u] = cost

    return dist, prev


def shortest_path(graph, begin, end):
    _, prev = dijkstra(graph, begin)

    path = []
    vertex = end

    while vertex is not None:
        path.append(vertex)
        vertex = prev[vertex]

    return list(reversed(path))


def cyclic(graph):
    """Return True if the directed graph has a cycle.
    The graph must be represented as a dictionary mapping vertices to
    iterables of neighbouring vertices. For example:

    >>> cyclic({1: (2,), 2: (3,), 3: (1,)})
    True
    >>> cyclic({1: (2,), 2: (3,), 3: (4,)})
    False

    """
    visited = set()
    path = [object()]
    path_set = set(path)
    stack = [iter(graph)]
    while stack:
        for v in stack[-1]:
            if v in path_set:
                return True
            elif v not in visited:
                visited.add(v)
                path.append(v)
                path_set.add(v)
                stack.append(iter(graph.get(v, ())))
                break
        else:
            path_set.remove(path.pop())
            stack.pop()
    return False


def main():
    g = WeightedDigraph()

    n, m = map(int, input().split())

    for i in range(m):
        a, b, c = map(int, input().split())
        g.add_vertex(a)
        g.add_vertex(b)
        g.add_edge(a, b, c)

    if cyclic(g.successors):
        print('inf')
        exit(0)

    print(dijkstra(g, 1)[0][n])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Submission status: Runtime Error

Solution code:
n, m = map(int, input().split())
l = [[0, 0, 0]]

for i in range(m):
    a, b, c = map(int, input().split())
    l.append([a, b, c])

edge = [- (10 ** 15)] * (n + 1)
ans = - (10 ** 15)

edge[1] = 0


def func(now):
    if now == n:
        return edge[n]

    f_l = filter(lambda x: x[0] == now, l)
    for j in f_l:
        to = j[1]
        edge[to] = max(edge[now] + j[2], edge[to])
        func(to)

func(1)
print(edge[n])

Submission status: Runtime Error

Solution code:
read = lambda: map(int, input().split())
n, m = read()
g = [list() for i in range(n + 2)]
for i in range(m):
    a, b, c = read()
    g[b].append((a, c))
g[1].append((0, 0))
g[n + 1].append((n, 0))
top = []
def dfs(v):
    if was[v]: return
    was[v] = 1
    for u, w in g[v]: dfs(u)
    top.append(v)
was = [0] * (n + 2)
for i in range(n + 2):
    dfs(i)
inf = 10 ** 100
dp = [-inf] * (n + 2)
dp[0] = 0
for v in top:
    for u, w in g[v]:
        if dp[u] == -inf:
            print('inf')
            exit()
        dp[v] = max(dp[v], dp[u] + w)
print(dp[n + 1])

Submission status: Runtime Error

Solution code:

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: Runtime Error

Solution code:
# coding: utf-8
n,m=map(int,input().split())
data=[]
dic={}
muki={}
kaburi=[]
kita={}
for i in range(1,n+1):
    dic[i]=0
    muki[i]=[(-1,0)]
    kita[i]=0
for i in range(m):
    a,b,c=map(int,input().split())
    if (b,a) not in kaburi:
        kaburi.append((a,b))
    else:
        print('inf')
        exit()
    if muki[a][0]!=(-1,0):
        muki[a].append((b,c))
    else:
        muki[a]=[(b,c)]
def check(moto):
    for p in muki[moto]:
        if kita[p[0]]==0 or dic[p[0]]<dic[moto]+p[1]:
            dic[p[0]]=dic[moto]+p[1]
            kita[p[0]]+=1
        if p[0]!=n:
            check(p[0])
            

check(1)
print(dic[n])

Submission status: Runtime Error

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
 
    while True:
        flag = False
 
        for (u, v, c) in edges:
            if d[u] != inf and dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                flag = True
 
        # print(dist)
 
        if not flag or dist[0] < 0:
            break
 
    if dist[0] >= 0:
        return dist[N - 1]
    else:
        return None
 
if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
import collections
import heapq
import math


class WeightedDigraph:
    def __init__(self):
        self.vertices = set()
        self.successors = collections.defaultdict(list)
        self.weights = {}

    def add_vertex(self, label):
        self.vertices.add(label)

    def add_edge(self, begin, end, weight):
        self.successors[begin].append(end)
        self.weights[(begin, end)] = weight


def dijkstra(graph, start):
    queue = []
    closed = set()
    dist = dict.fromkeys(graph.vertices, math.inf)
    prev = dict.fromkeys(graph.vertices, None)

    heapq.heappush(queue, (0, start))
    dist[start] = 0

    while len(queue) != 0:
        _, v = heapq.heappop(queue)
        closed.add(v)

        for u in graph.successors[v]:
            cost = dist[v] + graph.weights[(v, u)]
            if u not in closed and u not in [_[1] for _ in queue]:
                prev[u] = v
                dist[u] = cost
                heapq.heappush(queue, (cost, u))
            elif u in [_[1] for _ in queue]:
                if cost > dist[u]:
                    prev[u] = v
                    dist[u] = cost

    return dist, prev


def shortest_path(graph, begin, end):
    _, prev = dijkstra(graph, begin)

    path = []
    vertex = end

    while vertex is not None:
        path.append(vertex)
        vertex = prev[vertex]

    return list(reversed(path))


def main():
    g = WeightedDigraph()

    n, m = map(int, input().split())

    for i in range(m):
        a, b, c = map(int, input().split())
        g.add_vertex(a)
        g.add_vertex(b)
        g.add_edge(a, b, c)
        if a in g.successors[b] and b in g.successors[a]:
            print('inf')
            exit(0)

    print(dijkstra(g, 1)[0][n])


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n, m = map(int, raw_input().split())
g = [[] for i in xrange(n)]
for i in xrange(m):
    a, b, c = map(int, raw_input().split())
    g[a-1].append((b-1, c))
dist = [-10**18]*n

used = [0]*n
valid = [0]*n
memo = [None]*n
def dfs(v):
    res = 0
    if memo[v] is not None:
        return memo[v]
    for t, c in g[v]:
        if not used[t]:
            if t == n-1:
                res = 1
            used[t] = 1
            res |= dfs(t)
            used[t] = 0
    valid[v] |= res
    memo[v] = valid[v]
    return res
valid[0] = valid[n-1] = 1
used[0] = 1
dfs(0)

dist[0] = 0
for t in xrange(2*n):
    update = 0
    for v in xrange(n):
        for t, c in g[v]:
            if valid[t] and dist[v] + c > dist[t]:
                dist[t] = dist[v] + c
                update = 1
if update == 1:
    print "inf"
else:
    print dist[n-1]

Submission status: Runtime Error

Solution code:
n, m = map(int, raw_input().split())
g = [[] for i in xrange(n)]
for i in xrange(m):
    a, b, c = map(int, raw_input().split())
    g[a-1].append((b-1, c))
dist = [-10**18]*n

used = [0]*n
valid = [0]*n
def dfs(v):
    res = 0
    for t, c in g[v]:
        if not used[t]:
            if t == n-1:
                res = 1
            used[t] = 1
            res |= dfs(t)
            used[t] = 0
    valid[v] |= res
    return res
valid[0] = valid[n-1] = 1
used[0] = 1
dfs(0)

dist[0] = 0
for t in xrange(2*n):
    update = 0
    for v in xrange(n):
        for t, c in g[v]:
            if valid[t] and dist[v] + c > dist[t]:
                dist[t] = dist[v] + c
                update = 1
if update == 1:
    print "inf"
else:
    print dist[n-1]