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:
def bellman_ford(s,k):
    d = [float('inf')]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    for i in range(n):
        update = False # 更新が行われたか
        for x, y, z in g:
            if d[y] > d[x] + z:
                d[y] = d[x] + z
                update = True
        if not update:
            break
        # 負閉路が存在
        if i == n - 1:
            return "inf"
    return (-1)*d[k]

n, m = [int(x) for x in input().split()] # n:頂点数, w:辺の数
g = []
for _ in range(m):
    x, y, z = map(int,input().split()) # 始点,終点,コスト
    g.append([x-1, y-1, -z])
print(bellman_ford(0,n-1))

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
el = []
for i in range(m):
  a, b, c = map(int, input().split())
  a -= 1
  b -= 1
  el.append([a, b, c])
s = [-(10**15)] * n
s[0] = 0

for i in range(n):
  for j in range(m):
    e = el[j]
    if s[e[1]] < (s[e[0]] + e[2]):
      s[e[1]] = s[e[0]] + e[2]
      if i == n-1:
        # 閉路あり
        print('inf')
        exit(0)
print(s[n-1])

Submission status: Wrong Answer

Solution code:
#michatta ...
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import johnson
import scipy
def main():
    N, M = map(int, input().split())
    p = []
    q = []
    w = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        p.append(a-1)
        q.append(b-1)
        w.append(-c)
    csr = csr_matrix((w, (p, q)), shape=(N, N))
    try:
        t = johnson(csr, indices=0)
    except scipy.sparse.csgraph._shortest_path.NegativeCycleError:
        print('inf')
        return
    print(-int(t[-1]))
main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def main():
    N, M = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        G[a - 1].append((b - 1, c))
    INF = 10 ** 40
    S = [-INF] * N
    S[0] = 0

    def helper(n, s, hist):
        for g, gc in G[n]:
            if S[g] > s + gc or S[g] >= INF:
                continue
            S[g] = s + gc
            if g in hist:
                S[g] = INF
            hist[g] = hist.get(g, 0) + 1
            helper(g, S[g], hist)
            hist[g] -= 1
            if hist[g] == 0:
                del hist[g]
    helper(0, 0, {0: 1})
    s = S[-1]
    return s if s < INF else 'inf'

print(main())

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def main():
    N, M = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        G[a - 1].append((b - 1, c))
    INF = 10 ** 40
    S = [-INF] * N
    S[0] = 0

    def helper(n, s, hist):
        for g, gc in G[n]:
            if S[g] > s + gc or S[g] >= INF:
                continue
            S[g] = s + gc
            if g in hist:
                S[g] = INF
            hist.add(g)
            helper(g, S[g], hist)
            if g in hist:
                hist.remove(g)
    helper(0, 0, set([0]))
    s = S[-1]
    return s if s < INF else 'inf'

print(main())

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def main():
    N, M = map(int, input().split())
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        G[a - 1].append((b - 1, c))
    INF = 10 ** 40
    S = [-INF] * N
    S[0] = 0

    cur = set([0])
    def helper(n, s, hist):
        for g, gc in G[n]:
            if S[g] > s + gc or S[g] >= INF:
                continue
            S[g] = s + gc
            if g in hist:
                S[g] = INF
            hist.add(g)
            helper(g, S[g], hist)
            if g in hist:
                hist.remove(g)
    helper(0, 0, set())
    s = S[-1]
    return s if s < INF else 'inf'

print(main())

Submission status: Wrong Answer

Solution code:
def solve(V,E,r,edges):
    cost=[-float('inf')]*V
    cost[r]=0
    for _ in range(V-1):
        for edge in edges:
            s=edge[0]
            t=edge[1]
            d=edge[2]
            if cost[t]<cost[s]+d:
                cost[t]=cost[s]+d
    for edge in edges:
        s=edge[0]
        t=edge[1]
        d=edge[2]
        if cost[t]<cost[s]+d:
            return []
    return cost
            



V,E=map(int,input().split())
edges=[]
for _ in range(E):
    s,t,d=map(int,input().split())
    s-=1
    t-=1
    edges.append(tuple((s,t,d)))
ans=solve(V,E,0,edges)
if len(ans)==0:
    print("inf")
else:
    print(ans[V-1])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
ABC = [list(map(int, input().split())) for _ in range(m)]
dist = [-float("inf")]*(n+1)
dist[1] = 0
for i in range(n):
  for a, b, c in ABC:
    if dist[b] < dist[a]+c:
      if i == n-1:
        print("inf")
        exit()
      dist[b] = dist[a]+c
ans = dist[n]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
ABC = [list(map(int, input().split())) for _ in range(m)]
dist = [-float("inf")]*(n+1)
dist[1] = 0
for i in range(n):
  for a, b, c in ABC:
    if dist[a] != -float("inf") and dist[b] < dist[a]+c:
      if i == n-1:
        print("inf")
        exit()
      dist[b] = dist[a]+c
ans = dist[n]
print(ans)

Submission status: Wrong Answer

Solution code:
def bellman_ford(N, S, path):
    d = [float('inf')]*N # 各頂点への最小コスト
    d[S] = 0 # 自身への距離は0
    for i in range(N):
        update = False # 更新が行われたか
        for x, y, z in path:
            if d[y-1] > d[x-1] + z:
                d[y-1] = d[x-1] + z
                update = True
        if not update:
            break
        # 負閉路が存在
        if i == N - 1:
            return -123
    return d

N, M = map(int, input().split())
path = [0]*M
for i in range(M):
    a, b, c = map(int, input().split())
    path[i] = [a, b, -1*c]
A = bellman_ford(N, 0, path)
print("inf")

Submission status: Wrong Answer

Solution code:
def bellman_ford(N, S, path):
    d = [float('inf')]*N # 各頂点への最小コスト
    d[S] = 0 # 自身への距離は0
    for i in range(N):
        update = False # 更新が行われたか
        for x, y, z in path:
            if d[y-1] > d[x-1] + z:
                d[y-1] = d[x-1] + z
                update = True
        if not update:
            break
        # 負閉路が存在
        if i == N - 1:
            return -123
    return d

N, M = map(int, input().split())
path = [0]*M
for i in range(M):
    a, b, c = map(int, input().split())
    path[i] = [a, b, -1*c]
A = bellman_ford(N, 0, path)
if A == -123:
    print("inf")
else:
    print(-1*A[N-1])

Submission status: Wrong Answer

Solution code:
def bellman_ford(N, S, path):
    d = [float('inf')]*N # 各頂点への最小コスト
    d[S] = 0 # 自身への距離は0
    for i in range(N):
        update = False # 更新が行われたか
        for x, y, z in path:
            if d[y-1] > d[x-1] + z:
                d[y-1] = d[x-1] + z
                update = True
        if not update:
            break
        # 負閉路が存在
        if i == N - 1:
            return -1
    return d

N, M = map(int, input().split())
path = [0]*M
for i in range(M):
    a, b, c = map(int, input().split())
    path[i] = [a, b, -1*c]
A = bellman_ford(N, 0, path)
if A == -1:
    print("inf")
else:
    print(-1*A[N-1])

Submission status: Wrong Answer

Solution code:
def bellman_ford(N, S, path):
    d = [float('inf')]*N # 各頂点への最小コスト
    d[S] = 0 # 自身への距離は0
    for i in range(N):
        update = False # 更新が行われたか
        for x, y, z in path:
            if d[y-1] > d[x-1] + z:
                d[y-1] = d[x-1] + z
                update = True
        if not update:
            break
        # 負閉路が存在
        if i == N - 1:
            return -1
    return d

N, M = map(int, input().split())
path = [0]*M
for i in range(M):
    a, b, c = map(int, input().split())
    path[i] = [a, b, -1*c]
A = bellman_ford(N, 0, path)
if A == -1:
    print(-1)
else:
    print(-1*A[N-1])

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
path = [[-1*float("inf")]*N for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    path[a-1][b-1] = c
for k in range(N):
    for i in range(N):
        for j in range(N):
            path[i][j] = max(path[i][j], path[i][k]+path[k][j])
flag = 0
for i in range(N):
    if path[i][i] != -1*float("inf") and path[0][i] != -1*float("inf") and path[i][N-1] != -1*float("inf") :
        ans = "inf"
    else:
        ans = path[0][N-1]
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline


N, M = map(int, input().split())
starts = []
ends = []
costs = []
for _ in range(M):
    a, b, c = map(int, input().split())
    starts.append(a-1)
    ends.append(b-1)
    costs.append(-c)

graph = csr_matrix((costs, (starts, ends)), shape = (N, N))
try:
    ans = bellman_ford(graph, directed = True, indices = [0])[0][N-1]
    ans = int(round(-ans))
except NegativeCycleError:
    ans = "inf"

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline


N, M = map(int, input().split())
starts = []
ends = []
costs = []
for _ in range(M):
    a, b, c = map(int, input().split())
    starts.append(a-1)
    ends.append(b-1)
    costs.append(-c)

graph = csr_matrix((costs, (starts, ends)), shape = (N, N))
try:
    ans = bellman_ford(graph, directed = True, indices = [0])[0][N-1]
    ans = int(round(-ans))
except NegativeCycleError:
    ans = "inf"
    
if ans == float("inf"):
    raise ValueError

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import bellman_ford
from scipy.sparse.csgraph._shortest_path import NegativeCycleError

input = sys.stdin.buffer.readline


N, M = map(int, input().split())
starts = []
ends = []
costs = []
for _ in range(M):
    a, b, c = map(int, input().split())
    starts.append(a-1)
    ends.append(b-1)
    if c != 0:
        costs.append(-c)
    else:
        costs.append(sys.float_info.epsilon)

graph = csr_matrix((costs, (starts, ends)), shape = (N, N))
try:
    ans = bellman_ford(graph, directed = True, indices = [0])[0][N-1]
    ans = int(round(-ans))
except NegativeCycleError:
    ans = "inf"

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from scipy.sparse.csgraph import johnson
from scipy.sparse import csr_matrix, csgraph
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    N, M = map(int, readline().split())
    A = []
    B = []
    W = []
    for _ in range(M):
        a, b, w = map(int, readline().split())
        A.append(a-1)
        B.append(b-1)
        W.append(-w)

    try:
        path = johnson(csr_matrix((W,(A,B)),shape=(N,N)),indices=0)
        print(int(-path[N-1]))
    except csgraph._shortest_path.NegativeCycleError:
        print('inf')

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    root = []
    for _ in range(M):
        a,b,c = LI()
        root.append((a-1,b-1,c))
    node = [-INF]* N

    node[0] = 0
    up = False
    for _ in range(N):
        up = False
        for a,b,c in root:
            if node[a] + c > node[b]:
                node[b] = node[a] + c
                up = True
    if up:
        print('inf')
    else:
        print(node[N-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    root = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        root[a-1].append((b-1,c))
    node = [[-INF,0] for _ in range(N)]

    node[0][0] = 0
    node[0][1] = 1
    q = collections.deque()
    q.append((0,0,1))
    while q:
        u,d,b = q.popleft()
        if d < node[u][0]: continue
        for v,c in root[u]:
            r = (1<<v)
            if node[v][0] < d + c:
                if b & r:
                    print('inf')
                    return
                node[v][0] = d + c
                node[v][1] = b|r
                q.append((v,d+c,b|r))
    print(node[-1][0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    root = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        root[a-1].append((b-1,c))
    node = [[-INF,0] for _ in range(N)]

    node[0][0] = 0
    node[0][1] = 1
    q = collections.deque()
    q.append((0,0,1))
    while q:
        u,d,b = q.popleft()
        for v,c in root[u]:
            r = (1<<v)
            if node[v][0] < d + c:
                if b&r:
                    print('inf')
                    return
                node[v][0] = d + c
                node[v][1] = b|r
                q.append((v,d+c,b|r))
    print(node[-1][0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    root = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        root[a-1].append((b-1,c))
    node = [[-INF,0] for _ in range(N)]

    node[0][0] = 0
    q = collections.deque()
    q.append((0,0,1))
    while q:
        u,d,b = q.popleft()
        for v,c in root[u]:
            r = (1<<v)
            if b & r and node[v][0] < d + c:
                print('inf')
                return
            if node[v][0] < d + c:
                node[v][0] = d + c
                node[v][1] = b|r
                q.append((v,d+c,node[v][1]))
    print(node[-1][0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**18
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    root = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        root[a-1].append((b-1,c))
    node = [[-INF,0] for _ in range(N)]

    node[0][0] = 0
    q = collections.deque()
    q.append((0,0,1))
    while q:
        u,d,b = q.popleft()
        for v,c in root[u]:
            r = (1<<v)
            if b & r and node[v][0] < d + c:
                print('inf')
                return
            if node[v][0] < d + c:
                node[v][0] = d + c
                node[v][1] |= b|r
                q.append((v,d+c,node[v][1]))
    print(node[-1][0])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

cost = [-float('inf')]*N
cost[0] = 0

for i in range(2):
    for a,b,c in reversed(abc):
        a,b = a-1,b-1
        cost[b] = max(cost[b], cost[a] + c)
                
    if i == 0:
        ans = cost[N-1]
    else:
        Max = cost[N-1]


if ans != Max:
    print('inf')
else:
    print(ans)

Submission status: Wrong Answer

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

cost = [-float('inf')]*N
cost[0] = 0

for i in range(2):
    update = False
    for a,b,c in abc:
        a,b = a-1,b-1
        if cost[a] != -(10**10)*N:
            if cost[b] < cost[a] + c:
                cost[b] = cost[a] + c
                update = True
    if i == 0:
        Max = cost[N-1]
    elif i < N-1:
        Max = max(Max,cost[N-1])


if update == True and Max < cost[N-1]:
    print('inf')
else:
    print(Max)

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    edge_list.append( ( a_i - 1, b_i - 1, - c_i ) )

INF = 10 ** 15
cost = [ INF ] * n
cost[ 0 ] = 0

NegativeLoopExist = False
for i in range( n ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ a ] != INF and cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n - 1:
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( - cost[ n - 1 ] )

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    edge_list.append( ( a_i - 1, b_i - 1, - c_i ) )

INF = 10 ** 13
cost = [ INF ] * n
cost[ 0 ] = 0

NegativeLoopExist = False
for i in range( n ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ a ] != INF and cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n - 1:
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( - cost[ n - 1 ] )

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    edge_list.append( ( a_i - 1, b_i - 1, - c_i ) )

INF = 10 ** 10
cost = [ INF ] * n
cost[ 0 ] = 0

NegativeLoopExist = False
for i in range( n ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ a ] != INF and cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n - 1 and b == n - 1 :
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( - cost[ n - 1 ] )

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    edge_list.append( ( a_i - 1, b_i - 1, - c_i ) )

INF = 10 ** 10
cost = [ INF ] * n
cost[ 0 ] = 0

NegativeLoopExist = False
for i in range( n + 1 ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ a ] != INF and cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n - 1:
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( - cost[ n - 1 ] )

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    edge_list.append( ( a_i - 1, b_i - 1, - c_i ) )

INF = 10 ** 10
cost = [ INF ] * n
cost[ 0 ] = 0

NegativeLoopExist = False
for i in range( n + 1 ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ a ] != INF and cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n:
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( - cost[ n - 1 ] )

Submission status: Wrong Answer

Solution code:
n, m = map( int, input().split() )
adj_list = [ [] for _ in range( n ) ]
edge_list = []
for _ in range( m ):
    a_i, b_i, c_i = map( int, input().split() )
    adj_list[ a_i - 1 ].append( ( c_i, b_i - 1 ) )
    edge_list.append( ( a_i - 1, b_i - 1, -c_i ) )

INF = 10 ** 10
VISITED = 1
NOT_VISITED = 0
cost = [ INF ] * n
cost[ 0 ] = 0
visit = [ NOT_VISITED ] * n
visit[ 0 ] = VISITED

queue = [ ( cost[0], 0 ) ]

NegativeLoopExist = False
for i in range( n + 1 ):
    for j in range( m ):
        a, b, c = edge_list[ j ]
        if cost[ b ] > cost[ a ] + c:
            cost[ b ] = cost[ a ] + c
            if i == n:
                NegativeLoopExist = True

if NegativeLoopExist:
    print( "inf" )
else:
    print( -cost[n-1] )

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import johnson, NegativeCycleError
from scipy.sparse import csr_matrix

N, M = map(int, input().split())
row = [0] * M
col = [0] * M
dist = [0] * M
for i in range(M):
    a, b, c = map(int, input().split())
    row[i], col[i], dist[i] = a-1, b-1, -c

try:
    ans = johnson(csr_matrix((dist, (row, col)), shape=[N, N]), directed=True, indices=0)[-1]
    print(-int(ans))
except NegativeCycleError:
    print('inf')

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
NMAX = 1000; MMAX = 2000

INF = 10**10

edge = []
for _ in range(m):
    a, b, c = map(int, input().split())
    # 最短距離の問題に変える
    a -= 1; b -= 1; c = -c
    edge.append([a, b, c])

# Bellman-Ford O(NM)
dist = [INF for _ in range(NMAX)] # 頂点1からの最短距離を格納する配列
dist[0] = 0
for loop in range(n):
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] == INF:
            continue
        dist[b] = min(dist[b], dist[a]+c)

ans = dist[n-1]

# 負の閉路検出 O(NM)
## すでにBellman-Fordを実施しているので、distには頂点1から各頂点vまでの最短距離が格納されているはず
## もしまだ更新されるようなら、負の閉路(問題に合わせると正の閉路)が存在していることになる
negative = [False for _ in range(NMAX)] # 頂点iが負の閉路に含まれる場合はTrue
for loop in range(n):
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] == INF:
            continue
        if dist[b] > dist[a]+c:
            dist[b] = dist[a]+c
            negative[b] = True
        if negative[a]:
            negative[b] = True

if negative[n-1]:
    print("inf")
else:
    print(-ans)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
NMAX = 1000; MMAX = 2000

INF = 10**10

edge = []
for _ in range(m):
    a, b, c = map(int, input().split())
    # 最短距離の問題に変える
    a -= 1; b -= 1; c = -c
    edge.append([a, b, c])

# Bellman-Ford O(NM)
dist = [INF for _ in range(NMAX)] # 頂点1からの最短距離を格納する配列
dist[0] = 0
for loop in range(n-1):
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] == INF:
            continue
        dist[b] = min(dist[b], dist[a]+c)

ans = dist[n-1]

# 負の閉路検出 O(NM)
## すでにBellman-Fordを実施しているので、distには頂点1から各頂点vまでの最短距離が格納されているはず
## もしまだ更新されるようなら、負の閉路(問題に合わせると正の閉路)が存在していることになる
negative = [False for _ in range(NMAX)] # 頂点iが負の閉路に含まれる場合はTrue
for loop in range(n):
    for i in range(m):
        a, b, c = edge[i]
        if dist[a] == INF:
            continue
        if dist[b] > dist[a]+c:
            dist[b] = dist[a]+c
            negative[b] = True
        if negative[a]:
            negative[b] = True

if negative[n-1]:
    print("inf")
else:
    print(-ans)

Submission status: Wrong Answer

Solution code:
N,M = map(int, input().split())
edges = []
for _ in range(M):
  u,v,c = map(int, input().split())
  edges.append((-c,u-1,v-1))

INF = float('inf')
dist = [INF] * N
dist[0] = 0
for _ in range(N-1):
  for c,u,v in edges:
    if dist[v] > c+dist[u]:
      dist[v] = c+dist[u]

cycle = False
for c,u,v in edges:
  if dist[v] > c+dist[u]:
    cycle = True
    break

if cycle:
  print('inf')
else:
  print(-dist[N-1])

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
N,M = map(int,input().split())
start = []
goal = []
data1 = []
data2 = []
for _ in range(M):
    a,b,c = map(int,input().split())
    start.append(a)
    goal.append(b)
    data1.append(c)
    data2.append(-c)
csr1 = csr_matrix((data1,(start,goal)),shape=(N+1,N+1))
csr2 = csr_matrix((data2,(start,goal)),shape=(N+1,N+1))
try:
    p = shortest_path(csr1)
    q = shortest_path(csr2)
    if np.min(p)<np.min(q):
        print(int(np.min(p)))
    else:
        print(-int(np.min(q)))
except:
    print("inf")

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
N,M = map(int,input().split())
start = []
goal = []
data1 = []
data2 = []
for _ in range(M):
    a,b,c = map(int,input().split())
    start.append(a)
    goal.append(b)
    data1.append(c)
    data2.append(-c)
csr1 = csr_matrix((data1,(start,goal)),shape=(N+1,N+1))
csr2 = csr_matrix((data2,(start,goal)),shape=(N+1,N+1))
try:
    p = shortest_path(csr1)
    q = shortest_path(csr2)
    print(-min(int(np.min(p)),int(np.min(q))))
except:
    print("inf")

Submission status: Wrong Answer

Solution code:
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
N,M = map(int,input().split())
start = []
goal = []
data = []
for _ in range(M):
    a,b,c = map(int,input().split())
    start.append(a)
    goal.append(b)
    if c>0:
        data.append(-c)
    else:
        data.append(c)
csr = csr_matrix((data,(start,goal)),shape=(N+1,N+1))
try:
    p = shortest_path(csr)
    mini = int(np.min(p))
    if mini<0:
      print(mini)
    else:
      print(mini)
except:
    print("inf")

Submission status: Wrong Answer

Solution code:
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")
MOD = 1000000007


def bellman_ford(edges, num_v, sv):
    #グラフの初期化
    dist = [INF] * num_v
    dist[sv]=0
    
    #辺の緩和
    for i in range(num_v):
        for edge in edges:
            s, t, d = edge[0], edge[1], edge[2]
            if dist[s] != INF and dist[t] > dist[s] + d:
                dist[t] = dist[s] + d
                if i == num_v - 1:
                    return -1       # 負の閉路が存在する
    
    return dist


def main():
    N, M = map(int, input().split())

    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1; b -= 1; c *= -1
        edges.append([a, b, c])
    
    dist = bellman_ford(edges, N, 0)
    print("inf")
    # if dist == -1:
    #     print("inf")
    # else:
    #     print(-dist[N-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")
MOD = 1000000007


def bellman_ford(edges, num_v, sv):
    #グラフの初期化
    dist = [INF] * num_v
    dist[sv]=0
    
    #辺の緩和
    for i in range(num_v):
        for edge in edges:
            s, t, d = edge[0], edge[1], edge[2]
            if dist[s] != INF and dist[t] > dist[s] + d:
                dist[t] = dist[s] + d
                if i == num_v - 1:
                    return -1       # 負の閉路が存在する
    
    return dist


def main():
    N, M = map(int, input().split())

    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1; b -= 1; c *= -1
        edges.append([a, b, c])
    
    dist = bellman_ford(edges, N, 0)
    if dist == -1:
        print("inf")
    else:
        print(-dist[N-1])


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")
MOD = 1000000007


def bellman_ford(edges, num_v, sv):
    #グラフの初期化
    dist = [INF for i in range(num_v)]
    dist[sv]=0
    
    #辺の緩和
    for i in range(num_v):
        for edge in edges:
            s, t, d = edge[0], edge[1], edge[2]
            if dist[s] != INF and dist[t] > dist[s] + d:
                dist[t] = dist[s] + d
                if i == num_v - 1:
                    return -1       # 負の閉路が存在する
    
    return dist


def main():
    N, M = map(int, input().split())

    edges = []
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1; b -= 1; c *= -1
        edges.append([a, b, c])
    
    dist = bellman_ford(edges, N, 0)
    if dist == -1:
        print("inf")
    else:
        print(dist[N-1] * (-1))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def BellmanFord():
    def BF(s, n, edge, inf=float("inf")):
        d = [inf for i in range(n)]
        d[s] = 0
        for i in range(n):
            for before, after, dist in edge:
                if before != inf:
                    d[after] = min(d[after], d[before] + dist)
            if i == n - 1:
                t = d[:]
            elif i == n:
                for i, j in enumerate(d):
                    if j != t[i]:
                        d[i] = -inf
        return list(map(lambda x: -x, d))
    n, m = map(int, input().split())
    inf = 10 ** 20
    edge = [list(map(int, input().split())) for i in range(m)]
    edge = [[x - 1, y - 1, -z] for x, y, z in edge]
    l = BF(0, n, edge)
    print(l[-1] if l[-1] < inf else "inf")
BellmanFord()