Problem:


Score : 400 points

Problem Statement

There are N people standing on the x-axis.
Let the coordinate of Person i be x_i.
For every i, x_i is an integer between 0 and 10^9 (inclusive).
It is possible that more than one person is standing at the same coordinate.

You will given M pieces of information regarding the positions of these people.
The i-th piece of information has the form (L_i, R_i, D_i).
This means that Person R_i is to the right of Person L_i by D_i units of distance, that is, x_{R_i} - x_{L_i} = D_i holds.

It turns out that some of these M pieces of information may be incorrect.
Determine if there exists a set of values (x_1, x_2, ..., x_N) that is consistent with the given pieces of information.

Constraints

1 \leq N \leq 100 000

0 \leq M \leq 200 000

1 \leq L_i, R_i \leq N (1 \leq i \leq M)

0 \leq D_i \leq 10 000 (1 \leq i \leq M)

L_i \neq R_i (1 \leq i \leq M)

If i \neq j, then (L_i, R_i) \neq (L_j, R_j) and (L_i, R_i) \neq (R_j, L_j).

D_i are integers.

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1 D_1
L_2 R_2 D_2
:
L_M R_M D_M

Output

If there exists a set of values (x_1, x_2, ..., x_N) that is consistent with all given pieces of information, print Yes; if it does not exist, print No.

Sample Input 1

3 3
1 2 1
2 3 1
1 3 2

Sample Output 1

Yes

Some possible sets of values (x_1, x_2, x_3) are (0, 1, 2) and (101, 102, 103).

Sample Input 2

3 3
1 2 1
2 3 1
1 3 5

Sample Output 2

No

If the first two pieces of information are correct, x_3 - x_1 = 2 holds, which is contradictory to the last piece of information.

Sample Input 3

4 3
2 1 1
2 3 5
3 4 2

Sample Output 3

Yes

Sample Input 4

10 3
8 7 100
7 9 100
9 8 100

Sample Output 4

No

Sample Input 5

100 0

Sample Output 5

Yes



Sample input:
3 3
1 2 1
2 3 1
1 3 2


Sample output:
Yes

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
N, M = map(int,input().split())
p = {}
link = set()
q = {}

for u in range(1,N+1):
  q[u] = deque()

for j in range(M):
  L,R,D = map(int,input().split())
  link.add((L,R,D))
  q[L].append((R,D))
  q[R].append((L,-D))
  
def depthfirstsearch(start):
  while q[start]:
    target,d = q[start].pop()
    if target not in p:
      p[target] = p[start] + d
      depthfirstsearch(target)

for s in range(1,N+1):
  if s not in p:
    p[s] = 0
    depthfirstsearch(s)

yes = True
for L,R,D in link:
  if p[R] != p[L] + D:
    print("No")
    yes = False
if yes:
  print("Yes")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
N, M = map(int,input().split())
p = {}
link = set()
q = {}

for u in range(1,N+1):
  q[u] = deque()

for j in range(M):
  L,R,D = map(int,input().split())
  link.add((L,R,D))
  q[L].append((R,D))
  q[R].append((L,-D))
  
def depthfirstsearch(start):
  while q[start]:
    target,d = q[start].pop()
    if target not in p:
      p[target] = p[start] + d
      depthfirstsearch(target)

for start in range(1,N+1):
  if start not in p:
    p[start] = 0
    depthfirstsearch(start)

for L,R,D in link:
  if p[R] != p[L] + D:
    print("No")
    yes = False
if yes:
  print("Yes")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
N, M = map(int,input().split())
p = {}
link = set()
q = {}

for u in range(1,N+1):
  q[u] = deque()

for j in range(M):
  L,R,D = map(int,input().split())
  link.add((L,R,D))
  #link.add((R,L,-D))
  q[L].append((R,D))
  q[R].append((L,-D))
  
def depthfirstsearch(start):
  while q[start]:
    target,d = q[start].pop()
    if target not in p:
      p[target] = p[start] + d
      depthfirstsearch(target)



for start in range(1,N+1):
  if start not in p:
    p[start] = 0
    depthfirstsearch(start)

#for u in range(1,N+1):
  #print("position of " + str(u) + " = " + str(p[u]))

for L,R,D in link:
  if p[R] != p[L] + D:
    #print((L,R))
    #print((p[L],D,p[R]))
    print("No")
    exit()

print("Yes")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
visited = set()
d = {}
arrow = {}
nodes = deque()

raw = input().split()
N = int(raw[0])
M = int(raw[1])

for i in range(1,N+1):
  arrow[i] = deque()
  d[i] = 0
  nodes.append(i)

for i in range(M):
  raw = list(map(int,input().split()))
  L = raw[0]
  R = raw[1]
  D = raw[2]
  arrow[L].append((R,D))
  arrow[R].append((L,-D))

def dfsl(v):
  #矛盾が見つかればFalseを返す
  visited.add(v)
  while arrow[v]:
    w,cost = arrow[v].pop()
    
    if w not in visited:
      d[w] = d[v] + cost
      return dfsl(w)
    else:
      if d[w] != d[v] + cost:
        return False
  return True

ans = True
while nodes:
  u = nodes.pop()
  if u not in visited:
    d[u] = 0
    ans = dfsl(u)
    if not ans:
      break

for v in range(1,N+1):
  while arrow[v] and not ans:
    w,c = arrow[v].pop()
    if d[w] != d[v] + c:
      ans = False
      break
  

if ans:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
visited = set()
d = {}
arrow = {}
nodes = deque()

raw = input().split()
N = int(raw[0])
M = int(raw[1])

for i in range(1,N+1):
  arrow[i] = deque()
  d[i] = 0
  nodes.append(i)

for i in range(M):
  raw = list(map(int,input().split()))
  L = raw[0]
  R = raw[1]
  D = raw[2]
  arrow[L].append((R,D))
  arrow[R].append((L,-D))

def dfsl(v):
  #矛盾が見つかればFalseを返す
  visited.add(v)
  while arrow[v]:
    w,cost = arrow[v].pop()
    
    if w not in visited:
      d[w] = d[v] + cost
      return dfsl(w)
    else:
      if d[w] != d[v] + cost:
        return False
  return True

ans = True
while nodes:
  u = nodes.pop()
  if u not in visited:
    d[u] = 0
    ans = dfsl(u)
    if not ans:
      break

if ans:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
visited = set()
d = {}
arrow = {}
raw = input().split()
N = int(raw[0])
M = int(raw[1])

for i in range(1,N+1):
  arrow[i] = deque()
  d[i] = 0

for i in range(M):
  raw = list(map(int,input().split()))
  L = raw[0]
  R = raw[1]
  D = raw[2]
  arrow[L].append((R,D))
  arrow[R].append((L,-D))

def dfsl(v):
  #矛盾が見つかればFalseを返す
  visited.add(v)
  while arrow[v]:
    w,cost = arrow[v].pop()
    
    if w not in visited:
      d[w] = d[v] + cost
      #print("not visited")
      #print([d[v],d[w],cost])
      return dfsl(w)
    else:
      if d[w] != d[v] + cost:
        #print("visited")
        #print([d[v],d[w],cost])
        return False
  return True

ans = True
for u in range(1,N+1):
  if u not in visited:
    d[u] = 0
    ans = dfsl(u)
    if not ans:
      break
  

if ans:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
# coding: UTF-8
from collections import deque
visited = set()
d = {}
arrow = {}
raw = input().split()
N = int(raw[0])
M = int(raw[1])

for i in range(1,N+1):
  arrow[i] = deque()
  d[i] = None

for i in range(M):
  raw = list(map(int,input().split()))
  L = raw[0]
  R = raw[1]
  D = raw[2]
  arrow[L].append((R,D))
  arrow[R].append((L,-D))

def dfsl(v):
  #矛盾が見つかればFalseを返す
  visited.add(v)
  while arrow[v]:
    w,cost = arrow[v].pop()
    
    if w not in visited:
      d[w] = d[v] + cost
      #print("not visited")
      #print([d[v],d[w],cost])
      return dfsl(w)
    else:
      if d[w] != d[v] + cost:
        #print("visited")
        #print([d[v],d[w],cost])
        return False
  return True

ans = True
for u in range(1,N+1):
  if u not in visited:
    d[u] = 0
    ans = dfsl(u)
    if not ans:
      break
    else:
      continue

if ans:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
import sys                                                    
l1 = list(map(int, input().split()))                          
N = l1[0]                                                     
M = l1[1]                                                     
                                                              
                                                              
per_dis = [ [] for n in range(N+1)]                           
people = [None] * (N+1)                                       
                                                              
for n in range(M):                                            
    x = list(map(int, input().split()))                       
    per_dis[x[0]].append((x[1], x[2]))                        
    per_dis[x[1]].append((x[0], -x[2]))                       
                                                              
if M != 0:                                                    
    visited = []                                              
    unvisited = [(x[0], 0)]                                   
    people[x[0]] = 0                                          
    while unvisited:                                          
        now = unvisited[0]                                    
        unvisited = unvisited[1:]                             
        for next in per_dis[now[0]]:                          
            if next[0] not in visited:                        
                people[next[0]] =  now[1] + next[1]           
                unvisited.append((next[0], now[1] + next[1])) 
                visited.append(now[0])                        
                                                              
for i, x in enumerate(per_dis):                               
    if x != None:                                             
        for y in x:                                           
            if y[1] < 0:                                      
                if people[y[0]] - people[i] != y[1]:          
                    print("No")                               
                    sys.exit()                                
            else:                                             
                if people[i] - people[y[0]] != -y[1]:         
                    print("No")                               
                    sys.exit()                                
                                                              
                                                              
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np

N, M = tuple(map(int, input().split()))
Ls = np.zeros((M,), dtype=int)
Rs = np.zeros((M,), dtype=int)
Ds = np.zeros((M,), dtype=int)

for i in range(M):
    Ls[i], Rs[i], Ds[i] = tuple(map(int, input().split()))

# debug 1 exit()

Ls = Ls - 1
Rs = Rs - 1

adjacency_list = []
for i in range(N):
    adjacency_list.append([])

for i in range(M):
    adjacency_list[Ls[i]].append((Rs[i], Ds[i]))
    adjacency_list[Rs[i]].append((Ls[i], -Ds[i]))

# print(adjacency_list)

# BFSする
visited = np.zeros(N, dtype=bool)
weights = np.zeros(N, dtype=int)

# debug 2 exit()

def DFS(node_index):
    global visited
    global adjacency_list
    global to_be_visited
    global weights
    try:
        candidate = adjacency_list[node_index]
    except:
        pass
        # debug 4 exit()
    for _i, weight in candidate:
        if visited[_i]:
            # print("{}: already visited".format(_i))
            pass
        if not visited[_i]:
            # print("{} found; add to stack".format(_i))
            visited[_i] = True
            weights[_i] = weights[node_index] + weight
            to_be_visited.append(_i)
    if len(to_be_visited) != 0:
        try:
            next_node = to_be_visited.pop()
        except:
            exit()
        DFS(next_node)
    else:
        return 0

pointer = 0
while pointer < N:
    while pointer < N:
        if not visited[pointer]:
            # print("initialized with {}".format(pointer))
            break
        else:
            # print("{} th node already visited".format(pointer))
            pointer += 1
    if not pointer < N:
        break
    to_be_visited = [pointer]
    DFS(pointer)
    pointer += 1

# debug 3 exit()

# print(weights)

for i in range(M):
    # print("given weights: {}, estimated weights: {}".format(Ds[i],weights[Rs[i]]-weights[Ls[i]]))
    if weights[Rs[i]] - weights[Ls[i]] == Ds[i]:
        # print("passed {} th condition".format(i))
        pass
    else:
        # print("failed {} th condition".format(i))
        print("No")
        exit()
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np

N, M = tuple(map(int, input().split()))
Ls = np.zeros((M,), dtype=int)
Rs = np.zeros((M,), dtype=int)
Ds = np.zeros((M,), dtype=int)

for i in range(M):
    Ls[i], Rs[i], Ds[i] = tuple(map(int, input().split()))

# debug 1 exit()

Ls = Ls - 1
Rs = Rs - 1

adjacency_list = []
for i in range(N):
    adjacency_list.append([])

for i in range(M):
    adjacency_list[Ls[i]].append((Rs[i], Ds[i]))
    adjacency_list[Rs[i]].append((Ls[i], -Ds[i]))

# print(adjacency_list)

# BFSする
visited = np.zeros(N, dtype=bool)
weights = np.zeros(N, dtype=int)

# debug 2 exit()

def DFS(node_index):
    global visited
    global adjacency_list
    global to_be_visited
    global weights
    try:
        candidate = adjacency_list[node_index]
    except:
        exit()
    for _i, weight in candidate:
        if visited[_i]:
            # print("{}: already visited".format(_i))
            pass
        if not visited[_i]:
            # print("{} found; add to stack".format(_i))
            visited[_i] = True
            weights[_i] = weights[node_index] + weight
            to_be_visited.append(_i)
    if len(to_be_visited) != 0:
        next_node = to_be_visited.pop()
        DFS(next_node)
    else:
        return 0

pointer = 0
while pointer < N:
    while pointer < N:
        if not visited[pointer]:
            # print("initialized with {}".format(pointer))
            break
        else:
            # print("{} th node already visited".format(pointer))
            pointer += 1
    if not pointer < N:
        break
    to_be_visited = [pointer]
    DFS(pointer)
    pointer += 1

# debug 3 exit()

# print(weights)

for i in range(M):
    # print("given weights: {}, estimated weights: {}".format(Ds[i],weights[Rs[i]]-weights[Ls[i]]))
    if weights[Rs[i]] - weights[Ls[i]] == Ds[i]:
        # print("passed {} th condition".format(i))
        pass
    else:
        # print("failed {} th condition".format(i))
        print("No")
        exit()
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np

N, M = tuple(map(int, input().split()))
Ls = np.zeros((M,), dtype=int)
Rs = np.zeros((M,), dtype=int)
Ds = np.zeros((M,), dtype=int)

for i in range(M):
    Ls[i], Rs[i], Ds[i] = tuple(map(int, input().split()))

# debug 1 exit()

Ls = Ls - 1
Rs = Rs - 1

adjacency_list = []
for i in range(N):
    adjacency_list.append([])

for i in range(M):
    adjacency_list[Ls[i]].append((Rs[i], Ds[i]))
    adjacency_list[Rs[i]].append((Ls[i], -Ds[i]))

# print(adjacency_list)

# BFSする
visited = np.zeros(N, dtype=bool)
weights = np.zeros(N, dtype=int)

# debug 2 exit()

def DFS(node_index):
    global visited
    global adjacency_list
    global to_be_visited
    global weights
    candidate = adjacency_list[node_index]
    for _i, weight in candidate:
        if visited[_i]:
            # print("{}: already visited".format(_i))
            pass
        if not visited[_i]:
            # print("{} found; add to stack".format(_i))
            visited[_i] = True
            weights[_i] = weights[node_index] + weight
            to_be_visited.append(_i)
    if len(to_be_visited) != 0:
        next_node = to_be_visited.pop()
        DFS(next_node)
    else:
        return 0

pointer = 0
while pointer < N:
    while pointer < N:
        if not visited[pointer]:
            # print("initialized with {}".format(pointer))
            break
        else:
            # print("{} th node already visited".format(pointer))
            pointer += 1
    if not pointer < N:
        break
    to_be_visited = [pointer]
    DFS(pointer)
    pointer += 1

exit()

# print(weights)

for i in range(M):
    # print("given weights: {}, estimated weights: {}".format(Ds[i],weights[Rs[i]]-weights[Ls[i]]))
    if weights[Rs[i]] - weights[Ls[i]] == Ds[i]:
        # print("passed {} th condition".format(i))
        pass
    else:
        # print("failed {} th condition".format(i))
        print("No")
        exit()
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np

N, M = tuple(map(int, input().split()))
Ls = np.zeros((M,), dtype=int)
Rs = np.zeros((M,), dtype=int)
Ds = np.zeros((M,), dtype=int)

for i in range(M):
    Ls[i], Rs[i], Ds[i] = tuple(map(int, input().split()))

Ls = Ls - 1
Rs = Rs - 1

adjacency_list = []
for i in range(N):
    adjacency_list.append([])

for i in range(M):
    adjacency_list[Ls[i]].append((Rs[i], Ds[i]))
    adjacency_list[Rs[i]].append((Ls[i], -Ds[i]))

# print(adjacency_list)

# BFSする
visited = np.zeros(N, dtype=bool)
weights = np.zeros(N, dtype=int)


def DFS(node_index):
    global visited
    global adjacency_list
    global to_be_visited
    global weights
    candidate = adjacency_list[node_index]
    for _i, weight in candidate:
        if visited[_i]:
            # print("{}: already visited".format(_i))
            pass
        if not visited[_i]:
            # print("{} found; add to stack".format(_i))
            visited[_i] = True
            weights[_i] = weights[node_index] + weight
            to_be_visited.append(_i)
    if len(to_be_visited) != 0:
        next_node = to_be_visited.pop()
        DFS(next_node)
    else:
        return 0

pointer = 0
while pointer < N:
    while pointer < N:
        if not visited[pointer]:
            # print("initialized with {}".format(pointer))
            break
        else:
            # print("{} th node already visited".format(pointer))
            pointer += 1
    if not pointer < N:
        break
    to_be_visited = [pointer]
    DFS(pointer)
    pointer += 1

# print(weights)

for i in range(M):
    # print("given weights: {}, estimated weights: {}".format(Ds[i],weights[Rs[i]]-weights[Ls[i]]))
    if weights[Rs[i]] - weights[Ls[i]] == Ds[i]:
        # print("passed {} th condition".format(i))
        pass
    else:
        # print("failed {} th condition".format(i))
        print("No")
        exit()
print("Yes")

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

import sys

def reachable(td, origL, l, r, d):
    if not(l in td):
        return (False, d)
    vd = td[l]

    if origL in vd:
        return (False, d)

    if r in vd:
        return (True, d + vd[r])

    for er, ed in vd.iteritems():
        rb, rd = reachable(td, origL, er, r, d + ed)
        if rb:
            return (True, rd)
        
    return (False, d)

n, m = [int(i) for i in raw_input().split()]
tl = list()
for i in range(m):
    l = [int(i) for i in raw_input().split()]
    tl.append(l)
# print n, m
# print tl

consistent = 'Yes'
td = dict()
for t in tl:
    l, r, d = t
    
    found, fd = reachable(td, r, r, l, 0)
    if found:
        consistent = 'No'
        break
    
    found, fd = reachable(td, l, l, r, 0)
    if found:
        if fd != d:
            consistent = 'No'
            break
        else:
            td[l][r] = d
    else:
        if not (l in td):
            td[l] = dict()
        td[l][r] = d

sys.stdout.write('%s\n' % consistent)
sys.stdout.flush()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

import sys

def reachable(td, origL, l, r, d):
    if not(l in td):
        return (False, d)
    vl = td[l]
    for v in vl:
        vr, vd = v
        
        if vr == origL:
            return (False, d)
        
        if vr == r:
            return (True, d + vd)
        
        rb, rd = reachable(td, origL, vr, r, d + vd)
        if rb:
            return (rb, rd)
        
    return (False, d)

n, m = [int(i) for i in raw_input().split()]
tl = list()
for i in range(m):
    l = [int(i) for i in raw_input().split()]
    tl.append(l)
# print n, m
# print tl

consistent = 'Yes'
td = {}
for t in tl:
    l, r, d = t
    
    found, fd = reachable(td, r, r, l, 0)
    if found:
        consistent = 'No'
        break
    
    found, fd = reachable(td, l, l, r, 0)
    if found:
        if fd != d:
            consistent = 'No'
            break
        else:
            v = (r, d)
            td[l].add(v)
    else:
        if not (l in td):
            td[l] = set()
        v = (r, d)
        td[l].add(v)

sys.stdout.write('%s\n' % consistent)
sys.stdout.flush()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

import sys

def reachable(td, l, r, d):
    if not(l in td):
        return (False, d)
    vl = td[l]
    for v in vl:
        vr, vd = v
        if vr == r:
            return (True, d + vd)
        rb, rd = reachable(td, vr, r, d + vd)
        if rb:
            return (rb, rd)
    return (False, d)

n, m = [int(i) for i in raw_input().split()]
tl = list()
for i in range(m):
    l = [int(i) for i in raw_input().split()]
    tl.append(l)
# print n, m
# print tl

consistent = 'Yes'
td = {}
for t in tl:
    l, r, d = t
    
    found, fd = reachable(td, r, l, 0)
    if found:
        consistent = 'No'
        break
    
    found, fd = reachable(td, l, r, 0)
    if found:
        if fd != d:
            consistent = 'No'
            break
        else:
            v = (r, d)
            td[l].add(v)
    else:
        if not (l in td):
            td[l] = set()
        v = (r, d)
        td[l].add(v)

sys.stdout.write('%s\n' % consistent)
sys.stdout.flush()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
g = defaultdict(list)

n, m = map(int, input().split())
if m==0:
    print('Yes')
    exit()
for i in range(m):
    l, r, d = map(int, input().split())
    g[l].append((r, d))
    g[r].append((l, -1*d))
    
visited = {}
vv = {k:None for k in g.keys()}
def dfs(v, w=0):
    visited[v] = True
    vv[v] = w
    for c,d in g[v]:
        if not visited.get(c, False):
            dfs(c, w+d)

f = list(g.keys())[0]
while True:
    dfs(f)
    not_visited = list(set(g.keys()) - set(visited.keys()))
    if not_visited == []: break
    else: f = not_visited[0]

for k in g.keys():
    v = vv[k]
    for c,w in g[k]:
        if not v + w == vv[c]:
            print('No')
            exit()

print('Yes')

Submission status: Runtime Error

Solution code:
def DFS(i, pos, connected, distances):
  if pos[i] == None:
    pos[i] = 0
  size = len(connected[i])
  for j in range(size):
    if pos[connected[i][j]] == None:
      pos[connected[i][j]] = pos[i] + distances[i][j]
      if DFS(connected[i][j], pos, connected, distances) == False:
        return False
    elif pos[connected[i][j]] != pos[i] + distances[i][j]:
      return False
  return True

N, M = map(int, input().split())
pos = [None for i in range(N + 1)]
connected = [[] for i in range(N + 1)]
distances = [[] for i in range(N + 1)]
for i in range(M):
  l, r, d = map(int, input().split())
  connected[l].append(r)
  distances[l].append(d)
  connected[r].append(l)
  distances[r].append(-d)
judge = True
for i in range(1, N + 1):
  if pos[i] == None:
    judge = DFS(i, pos, connected, distances)
    if judge == False:
      break
if judge:
  print('Yes')
else:
  print('No')

Submission status: Runtime Error

Solution code:
import numpy as np

N,M = map(int,input().split(" "))
if M<1:
    print("Yes")
else:
    info = [list(map(int, input().split(" "))) for i in range(M)]

    A = np.zeros((M, N))
    Ab = np.zeros((M, N+1))
    for i in range(M):
        A[i][info[i][1]-1] = 1
        A[i][info[i][0]-1] = -1
        Ab[i][info[i][1]-1] = 1
        Ab[i][info[i][0]-1] = -1
        Ab[i][-1] = info[i][2]

    rankA = np.linalg.matrix_rank(A)
    rankAb = np.linalg.matrix_rank(Ab)

    if rankA == rankAb :
        print("Yes")
    else:
        print("No")

Submission status: Runtime Error

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

INF = 10000000000000
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = INF
    
def DFS(vertice):
  judge = True
  connected_num = len(vertice.connected)
  for i in range(connected_num):
    con = vertice.connected[i]
    if con.pos == INF:
      con.pos = vertice.pos + vertice.edge[i]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[i]:
      judge = False
    if judge == False:
      break
  return judge
 
N, M = map(int, input().split())
L, R, D = ([None for i in range(M)] for j in range(3))
vertices = [Vertice(i) for i in range(N)]
for i in range(M):
  L[i], R[i], D[i] = map(int, input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == INF:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
INF = 10000000000000
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = INF
    
def DFS(vertice):
  judge = True
  connected_num = len(vertice.connected)
  for i in range(connected_num):
    con = vertice.connected[i]
    if con.pos == INF:
      con.pos = vertice.pos + vertice.edge[i]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[i]:
      judge = False
    if judge == False:
      break
  return judge
 
N, M = map(int, input().split())
L, R, D = ([None for i in range(M)] for j in range(3))
vertices = [Vertice(i) for i in range(N)]
for i in range(M):
  L[i], R[i], D[i] = map(int, input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == INF:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
INF = 10000000000000
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = INF
    
def DFS(vertice):
  judge = True
  connected_num = len(vertice.connected)
  for i in range(connected_num):
    con = vertice.connected[i]
    if con.pos == INF:
      con.pos = vertice.pos + vertice.edge[i]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[i]:
      judge = False
    if judge == False:
      break
  return judge
 
N, M = map(int, input().split())
vertices = [Vertice(i) for i in range(N)]
L, R, D = ([None for i in range(M)] for j in range(3))
for i in range(M):
  L[i], R[i], D[i] = map(int, input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == INF:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
INF = 10000000000000
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = INF
    
def DFS(vertice):
  judge = True
  for con in vertice.connected:
    index = vertice.connected.index(con)
    if con.pos == INF:
      con.pos = vertice.pos + vertice.edge[index]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[index]:
      judge = False
    if judge == False:
      break
  return judge
 
N, M = map(int, input().split())
vertices = [Vertice(i) for i in range(N)]
L, R, D = ([None for i in range(M)] for j in range(3))
for i in range(M):
  L[i], R[i], D[i] = map(int, input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == INF:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
INF = 10000000000000
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = INF
    
def DFS(vertice):
  judge = True
  for con in vertice.connected:
    index = vertice.connected.index(con)
    if con.pos == INF:
      con.pos = vertice.pos + vertice.edge[index]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[index]:
      judge = False
    if judge == False:
      break
  return judge

N, M = (int(_) for _ in input().split())
vertices = [Vertice(i) for i in range(N)]
L, R, D = ([None for i in range(M)] for j in range(3))
for i in range(M):
  L[i], R[i], D[i] = (int(_) for _ in input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == INF:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")

Submission status: Runtime Error

Solution code:
import math
class Vertice:
  def __init__(self, num):
    self.num = num
    self.connected = []
    self.edge = []
    self.pos = math.inf
    
def DFS(vertice):
  judge = True
  for con in vertice.connected:
    index = vertice.connected.index(con)
    if con.pos == math.inf:
      con.pos = vertice.pos + vertice.edge[index]
      judge = DFS(con)
    elif con.pos != vertice.pos + vertice.edge[index]:
      judge = False
    if judge == False:
      break
  return judge

N, M = (int(_) for _ in input().split())
vertices = [Vertice(i) for i in range(N)]
L, R, D = ([None for i in range(M)] for j in range(3))
for i in range(M):
  L[i], R[i], D[i] = (int(_) for _ in input().split())
for i in range(M):
  if not vertices[R[i] - 1] in vertices[L[i] - 1].connected:
    vertices[L[i] - 1].connected.append(vertices[R[i] - 1])
    vertices[R[i] - 1].connected.append(vertices[L[i] - 1])
    vertices[L[i] - 1].edge.append(D[i])
    vertices[R[i] - 1].edge.append(-D[i])
judge = True
for i in range(N):
  if vertices[i].pos == math.inf:
    vertices[i].pos = 0
    judge = DFS(vertices[i])
    if judge == False:
      break
if judge:
  print("Yes")
else:
  print("No")