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

Solution (Python):
n, m = list(map(int, input().split()))
par = list(range(n+1))
dis = [0] * (n+1)

def root(x):
  if x == par[x]:
    return x
  r = root(par[x])
  dis[x] += dis[par[x]]
  par[x] = r
  return r

def cost(x):
  
  if x == par[x]:
    return 0
  return dis[x] + cost(par[x])

for _ in range(m):
  l, r, d = list(map(int, input().split()))
  
  
  
  
  
  rootl = root(l)
  rootr = root(r)
  if rootl != rootr:
    if r != rootr:
      
      dis[rootl] = d - cost(l)
    else:
      
      dis[rootl] = d - (dis[l] - dis[r])
    
    par[rootl] = r
  else:
    if d != cost(l) - cost(r):
      print("No")
      exit()

  """
  ちょっとなにがダメなのかわかんないので確かめる
  if rootl != rootr:
    
    if r == rootr:
      dis[rootl] = d - cost(l)
    else:
      dis[rootl] = d - (dis[l] - dis[r]) 
    par[rootl] = r
  else:
    
    if d == cost(l) - cost(r):
      continue
    else:
      print("No")
      exit()
  """
print("Yes")

Solution (Python):
n, m = list(map(int, input().split()))
par = list(range(n+1))
dis = [0] * (n+1)

def root(x):
  if x == par[x]:
    return x
  r = root(par[x])
  dis[x] += dis[par[x]]
  par[x] = r
  return r

def cost(x):
  
  if x == par[x]:
    return 0
  return dis[x] + cost(par[x])


def unite(x, y, w):
  rootx = root(x)
  rooty = root(y)
  if rootx != rooty:
    if y != rooty:
      
      dis[rootx] = w - cost(x)
    else:
      
      dis[rootx] = w - (dis[x] - dis[y])
    
    par[rootx] = y
  else:
    if w != cost(x) - cost(y):
      print("No")
      exit()


for _ in range(m):
  l, r, d = list(map(int, input().split()))
  
  
  
  rootl, rootr = root(l), root(r)
  
  a = unite(l, r, d)
  if a is not None:
    if a == False:
      flag = False

  """
  ちょっとなにがダメなのかわかんないので確かめる
  if rootl != rootr:
    
    if r == rootr:
      dis[rootl] = d - cost(l)
    else:
      dis[rootl] = d - (dis[l] - dis[r]) 
    par[rootl] = r
  else:
    
    if d == cost(l) - cost(r):
      continue
    else:
      print("No")
      exit()
  """
print("Yes")

Solution (Python):
import sys
sys.setrecursionlimit(10**7)

n, m = list(map(int, input().split()))
par = list(range(n+1))
dist = [0 for _ in range(n+1)]

def root(x):
  if x == par[x]:
    return x
  r = root(par[x])
  dist[x] += dist[par[x]]
  par[x] = r
  return r

def direct_cost(x):
  if x == par[x]:
    return 0
  return dist[x] + direct_cost(par[x])

def diff(x, y):
  return direct_cost(x) - direct_cost(y)

def unite(x, y, w):
  rootx = root(x)
  rooty = root(y)
  if rootx != rooty:
    if y != rooty:
      
      dist[rootx] = w - direct_cost(x)
    else:
      
      dist[rootx] = w - (dist[x] - dist[y])
    
    par[rootx] = y
  else:
    return w == diff(x, y)

flag = True
for _ in range(m):
  l, r, d = list(map(int, input().split()))
  
  a = unite(l, r, d)
  if a is not None:
    if a == False:
      flag = False
  """
  rootx, rooty = root(l), root(r)
  if rootx != rooty:
    if r != rooty:
      
      dist[rootx] = d - direct_cost(l)
    else:
      
      dist[rootx] = d - (dist[l] - dist[r])
    par[rootx] = l
  else:
    if d != diff(l, r):
      flag = False
  """
"""
[print("[{}]{}".format(idx, v), end=" ") for idx, v in enumerate(par)]
print()
[print("[{}]{}".format(idx, v), end=" ") for idx, v in enumerate(dist)]
print()
"""

print("Yes" if flag else "No")

Solution (Python):


def main():
    na = list(map(int, input().split()))
    N = na[0]
    M = na[1]
    lrd_list = []
    for i in range(M):
        na = list(map(int, input().split()))
        lrd_list.append((na[0], na[1], na[2]))

    l_list = [None for i in range(N+1)]
    r_list = [None for i in range(N+1)]
    for lrd in lrd_list:
        l = lrd[0]
        r = lrd[1]
        if l_list[l] is None:
            l_list[l] = [lrd]
        else:
            l_list[l].append(lrd)
        if r_list[r] is None:
            r_list[r] = [lrd]
        else:
            r_list[r].append(lrd)

    positions = [None for i in range(N+1)]
    consistent = True
    i = 1
    while consistent and i <= N:
        s = []
        p = 0
        positions[i] = p
        s.append(i)
        while consistent and 0 < len(s):
            j = s.pop()
            p = positions[j]
            if not l_list[j] is None:
                for lrd in l_list[j]:
                    l, r, d = lrd
                    if positions[r] is None:
                        positions[r] = p + d
                        s.append(r)
                    elif positions[r] != p + d:
                        consistent = False
                        break
                if not consistent:
                    break
            if not r_list[j] is None:
                for lrd in r_list[j]:
                    l, r, d = lrd
                    if positions[l] is None:
                        positions[l] = p - d
                        s.append(l)
                    elif positions[l] != p - d:
                        consistent = False
                        break
        while consistent and i <= N and (not positions[i] is None):
            i += 1


    print('Yes' if consistent else 'No')


if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10**7)

class WeightedUnionFindTree:
  def __init__(self, n):
    self.par = list(range(n))
    self.rank = [0 for _ in range(n)]
    self.weight = [0 for _ in range(n)]
   
  def root(self, t):
    if t == self.par[t]:
      return t
    
    r = self.root(self.par[t])
    self.weight[t] += self.weight[self.par[t]]
    self.par[t] = r
    return r
   
  def rec_weight(self, t):
    if t == self.par[t]:
      return 0
    return self.weight[t] + self.rec_weight(self.par[t])
   
  def same(self, x, y):
    return self.root(x) == self.root(y)
     
  def unite(self, x, y, w):
    rootx = self.root(x)
    rooty = self.root(y)
    if rootx != rooty:
      if y != rooty:
        
        self.weight[rootx] = w - self.rec_weight(x)
      else:
        
        self.weight[rootx] = w - (self.weight[x] - self.weight[y])
      
      self.par[rootx] = y
    else:
      return w == self.diff(x, y)
 
  def diff(self, x, y):
    return self.rec_weight(x) - self.rec_weight(y)

n, m = list(map(int, input().split()))
par = list(range(n+1))
dist = [0 for _ in range(n+1)]


wuft = WeightedUnionFindTree(n+1)
flag = True
for _ in range(m):
  l, r, d = list(map(int, input().split()))
  
  a = wuft.unite(l, r, d)
  if a is not None:
    if a == False:
      flag = False
"""
[print("[{}]{}".format(idx, v), end=" ") for idx, v in enumerate(wuft.par)]
print()
[print("[{}]{}".format(idx, v), end=" ") for idx, v in enumerate(wuft.weight)]
print()
"""

print("Yes" if flag else "No")

Solution (Python):
def dfs(graph, start, visited):
    if visited[start] != -99999:
        return True

    stack = [start]
    visited[start] = 0
    while stack:
        label = stack.pop()
        for nextnode, distance in graph[label]:
            if visited[nextnode] == -99999:
                stack.append(nextnode)
                visited[nextnode] = visited[label] + distance
            elif visited[nextnode] != visited[label] + distance:
                return False
    return True


N, M = (int(i) for i in input().split())

graph = [[] for i in range(N + 1)]

for i in range(M):
    L, R, D = (int(i) for i in input().split())
    graph[L].append((R, D))
    graph[R].append((L, -1 * D))

visited = [-99999 for i in range(N + 1)]

flag = True
for i in range(1, N + 1):
    ans = dfs(graph, i, visited)
    if not ans:
        flag = False
        break

if flag:
    print('Yes')
else:
    print('No')

Solution (Python):
def dfs(graph, start, visited):
    if visited[start] != -99999:
        return True

    stack = [start]
    visited[start] = 0
    while stack:
        label = stack.pop()
        for nextnode, distance in graph[label]:
            if visited[nextnode] == -99999:
                stack.append(nextnode)
                visited[nextnode] = visited[label] + distance
            elif visited[nextnode] != visited[label] + distance:
                return False
    return True


N, M = (int(i) for i in input().split())

graph = [[] for i in range(N + 1)]

for i in range(M):
    L, R, D = (int(i) for i in input().split())
    graph[L].append((R, D))
    graph[R].append((L, -1 * D))

visited = [-99999 for i in range(N + 1)]

flag = True
for i in range(1, N + 1):
    ans = dfs(graph, i, visited)
    if not ans:
        flag = False
        break

if flag:
    print('Yes')
else:
    print('No')

Solution (Python):


"""
参考：https://www.hamayanhamayan.com/entry/2018/01/28/231916
・深さ優先
・幅優先とほとんど一緒だけど練習用にこっちも書いた。
"""

import sys


sys.setrecursionlimit(10 ** 9)

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

l_edges = [[] for i in range(N)]
r_edges = [[] for i in range(N)]
for i in range(M):
    l, r, d = map(int, input().split())
    l_edges[l-1].append((r-1, d))
    r_edges[r-1].append((l-1, d))


visited = [0] * N

def dfs(cur):
    visited[cur] = 1
    
    for r, d in l_edges[cur]:
        
        if visited[r]:
            if pos[r] - pos[cur] != d:
                print('No')
                exit()
        
        else:
            visited[r] = 1
            pos[r] = pos[cur] + d
            
            dfs(r)
    
    for l, d in r_edges[cur]:
        if visited[l]:
            if pos[cur] - pos[l] != d:
                print('No')
                exit()
        else:
            visited[l] = 1
            pos[l] = pos[cur] - d
            dfs(l)

for i in range(N):
    
    if not visited[i]:
        
        pos = {i: 0}
        dfs(i)
        pos = {}

print('Yes')

Solution (Python):


"""
参考：https://www.hamayanhamayan.com/entry/2018/01/28/231916
・幅優先
・辺の情報の持たせ方を工夫して、辺のループを余計に回さないようにする。
"""

from collections import deque

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

l_edges = [[] for i in range(N)]
r_edges = [[] for i in range(N)]
for i in range(M):
    l, r, d = map(int, input().split())
    l_edges[l-1].append((r-1, d))
    r_edges[r-1].append((l-1, d))


visited = [0] * N

def bfs(start):
    
    pos = {start: 0}
    que = deque()
    que.append(start)
    visited[start] = 1
    while len(que) != 0:
        cur = que.popleft()
        
        for r, d in l_edges[cur]:
            
            if visited[r]:
                if pos[r] - pos[cur] != d:
                    print('No')
                    exit()
            
            else:
                visited[r] = 1
                pos[r] = pos[cur] + d
                
                que.append(r)
        
        for l, d in r_edges[cur]:
            if visited[l]:
                if pos[cur] - pos[l] != d:
                    print('No')
                    exit()
            else:
                visited[l] = 1
                pos[l] = pos[cur] - d
                que.append(l)

for i in range(N):
    
    if not visited[i]:
        bfs(i)

print('Yes')

Solution (Python):


"""
参考：http://hamko.hatenadiary.jp/entry/2018/01/30/210057
　　　http://at274.hatenablog.com/entry/2018/02/03/140504
・重み付きUnion-Find木
"""

import sys
def input(): return sys.stdin.readline().strip()

class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        
        self.weight = [0] * (n+1)

    
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = - w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

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

wuf = WeightedUnionFind(N)
for i in range(M):
    x, y, w = map(int, input().split())
    
    if wuf.same(x, y):
        
        if wuf.diff(x, y) != w:
            print('No')
            exit()
    wuf.union(x, y, w)

print('Yes')

Solution (Python):


"""
参考：http://hamko.hatenadiary.jp/entry/2018/01/30/210057
　　　http://at274.hatenablog.com/entry/2018/02/03/140504
・重み付きUnion-Find木
"""

class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        
        self.weight = [0] * (n+1)

    
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = - w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

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

wuf = WeightedUnionFind(N)
for i in range(M):
    x, y, w = map(int, input().split())
    
    if wuf.same(x, y):
        
        if wuf.diff(x, y) != w:
            print('No')
            exit()
    wuf.union(x, y, w)

print('Yes')

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


class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n)]
        self.rank = [0] * n
        
        self.weight = [0] * n

    
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    
    def weighting(self, x):
        self.find(x)
        return self.weight[x]

    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]


wuf = WeightedUnionFind(N)
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    if wuf.same(l, r):
        if d != wuf.diff(l, r):
            print('No')
            break
    else:
        wuf.union(l, r, d)
else:
    print('Yes')

Solution (Python):
class WeightedUnionFind:
    def __init__(self, n):
        self.parent = [i for i in range(n + 1)]
        self.rank = [0 for _ in range(n + 1)]
        self.weight = [0 for _ in range(n + 1)]

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            y = self.find(self.parent[x])
            self.weight[x] += self.weight[self.parent[x]]
            self.parent[x] = y
            return y

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            if w != self.diff(x, y):
                print("No")
                exit()

        if self.rank[rx] < self.rank[ry]:
            self.parent[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        else:
            self.parent[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def diff(self, x, y):
        return self.weight[x] - self.weight[y]


N, M = map(int, input().split())
w_union_find = WeightedUnionFind(N)
for i in range(M):
    l, r, d = map(int, input().split())
    w_union_find.union(l, r, d)
print("Yes")

Solution (Python):
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)
        
        self.weight = [0] * (n + 1)

    
    def find(self, x):  
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            
            self.par[x] = y
            return y  

    
    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if rx == ry:
            if self.diff(x, y) != w:
                print("No")
                exit()
        
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w + self.weight[x] - self.weight[y]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]


import sys
sys.setrecursionlimit(10**8)
N, M = map(int, input().split())
lrd = []
for i in range(M):
    l, r, d = map(int, input().split())
    lrd.append([l, r, d])
w_union_find = WeightedUnionFind(N)
for i in range(M):
    l, r, d = lrd[i]
    w_union_find.union(l, r, d)
print("Yes")

Solution (Python):
import sys
sys.setrecursionlimit(1000000)

def DFS(start):
    global graph
    global zahyou

    start_num=zahyou[start]

    for w,d in graph[start]:
        if(zahyou[w]==None):
            zahyou[w]=start_num + d
            if( not DFS(w)):
                return False
        else:
            if(start_num + d != zahyou[w]):
                return False

    return True



n,m=map(int,input().split())
graph=[[] for _ in range(n)]

zahyou=[None]*n
for i in range(m):
    l,r,d=map(int,input().split())
    graph[l-1].append((r-1,d))
    graph[r-1].append((l-1,-1*d))

flag=True
for i in range(n):
    if(zahyou[i]==None):
        zahyou[i]=0
        flag&=DFS(i)
        if( not flag):
            break

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

Solution (Python):

from pprint import pprint
import random
from collections import deque, defaultdict
N, M = map(int, input().split())

if M == 0:
    print("Yes")
    exit()

LRD = [list(map(int, input().split())) for _ in range(M)]






graph = defaultdict(lambda: defaultdict(int))


visited = defaultdict()

for L,R,D in LRD:
    graph[L][R] = D
    graph[R][L] = -D
    visited[L] = None
    visited[R] = None




def xfs(v):
    que = deque()
    que.append((v,0))
    while len(que) > 0:
        i,cnt = que.pop()  
        visited[i] = cnt
        
        for n,val in graph[i].items():
            if visited[n] == None:
                
                que.append((n, cnt+val))
            else:
                
                
                if cnt + val != visited[n]:
                    return False

    return True


que2 = deque()
L, _, _ = LRD[0]
que2.append(L)
while len(que2) > 0:
    L = que2.pop()
    
    if xfs(L):
        for k,v in [(k,v) for k,v in visited.items() if v==None]:
            
            que2.append(k)
            break
    else:
        
        
        print("No")
        exit()


print("Yes")

Solution (Python):
class WeightsUnionfind:
  def __init__(self,n):
    self.Tree=[i for i in range(n)]
    self.dWeights=[0]*n
    self.rank=[0]*n
    self.wrong=0

  def find(self,x):
    if x==self.Tree[x]:
      return x
    else:
      root=self.find(self.Tree[x])
      self.dWeights[x]=self.weigh(x)
      self.Tree[x]=root
      return root
  
  def weigh(self,x):
    if x==self.Tree[x]:
      return 0
    else:
      w=self.weigh(self.Tree[x])+self.dWeights[x]
      return w

  def unite(self,x,y,w):
    s1=self.find(x)
    s2=self.find(y)
    if s1==s2:
      if self.weigh(y)-self.weigh(x)!=w:
        self.wrong=1
    else:
      if self.rank[s1]>self.rank[s2]:
        self.Tree[s2]=s1
        self.dWeights[s2]=self.weigh(x)-self.weigh(y)+w
      elif self.rank[s1]<self.rank[s2]:
        self.Tree[s1]=s2
        self.dWeights[s1]=self.weigh(y)-self.weigh(x)-w
      else:
        self.Tree[s2]=s1
        self.rank[s1]+=1
        self.dWeights[s2]=self.weigh(x)-self.weigh(y)+w
          
N,M=map(int,input().split())
wuf=WeightsUnionfind(N)
F=0
for m in range(M):
  l,r,d=map(int,input().split())
  wuf.unite(l-1,r-1,d)
if wuf.wrong==1:
  print("No")
else:
  print("Yes")

Solution (Python):
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)
        
        self.weight = [0] * (n + 1)

    
    def find(self, x):  
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            
            self.par[x] = y
            return y  

    
    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if rx == ry:
            if self.diff(x, y) != w:
                print("No")
                exit()
        
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w + self.weight[x] - self.weight[y]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

    def show(self):
        for i in range(1, n + 1):
            print("node:{} par:{} w:{}".format(i, union.par[i], union.weight[i]))


n, m = [int(i) for i in input().split()]
l = [0 for i in range(m)]
r = [0 for i in range(m)]
d = [0 for i in range(m)]

union = WeightedUnionFind(n)
for i in range(m):
    l[i], r[i], d[i] = [int(i) for i in input().split()]
    union.union(l[i], r[i], d[i])
print("Yes")

Solution (Python):
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)
        
        self.weight = [0] * (n + 1)

    
    def find(self, x):  
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            
            self.par[x] = y
            return y  

    
    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if rx == ry:
            if self.diff(x, y) != w:
                print("No")
                exit()
        
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

    def show(self):
        for i in range(1, n + 1):
            print("node:{} par:{} w:{}".format(i, union.par[i], union.weight[i]))


n, m = [int(i) for i in input().split()]
l = [0 for i in range(m)]
r = [0 for i in range(m)]
d = [0 for i in range(m)]

union = WeightedUnionFind(n)
for i in range(m):
    l[i], r[i], d[i] = [int(i) for i in input().split()]
    union.union(l[i], r[i], d[i])
print("Yes")

Solution (Python):
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)
        
        self.weight = [0] * (n + 1)

    
    def find(self, x):  
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            
            self.weight[x] += self.weight[self.par[x]]
            
            self.par[x] = y
            return y 

    
    
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        
        if rx == ry:
            if self.diff(x, y) != w:
                print("No")
                exit()
        
        
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    
    def same(self, x, y):
        return self.find(x) == self.find(y)

    
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]


n, m = [int(i) for i in input().split()]
l = [0 for i in range(m)]
r = [0 for i in range(m)]
d = [0 for i in range(m)]

union = WeightedUnionFind(n)
for i in range(m):
    l[i], r[i], d[i] = [int(i) for i in input().split()]
    union.union(l[i], r[i], d[i])
print("Yes")

Solution (Python):
import sys
sys.setrecursionlimit(1000000)

def DFS(start):
    global graph
    global zahyou

    start_num=zahyou[start]

    for w,d in graph[start]:
        if(zahyou[w]==None):
            zahyou[w]=start_num + d
            if( not DFS(w)):
                return False
        else:
            if(start_num + d != zahyou[w]):
                return False
    
    return True
            


n,m=map(int,input().split())
graph=[[] for _ in range(n)]

zahyou=[None]*n
for i in range(m):
    l,r,d=map(int,input().split())
    graph[l-1].append((r-1,d))
    graph[r-1].append((l-1,-1*d))

flag=True
for i in range(n):
    if(zahyou[i]==None):
        zahyou[i]=0
        flag&=DFS(i)
        if( not flag):
            break

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

Solution (Python):
from collections import defaultdict
N, M = map( int, input().split())
E = [ [] for _ in range(N)]
V = [ 0 for _ in range(N)]
for i in range(M):
    L, R, D = map( int, input().split())
    E[L-1].append((R-1,D))
    V[R-1] += 1
dist = [-1]*N
for i in range(N):
    if V[i]:
        continue
    S = [i]
    dist[i] = 0
    while S:
        v = S.pop()
        for u, d in E[v]:
            if dist[u] == -1:
                dist[u] = dist[v] + d
                S.append(u)
ans = "Yes"
for v in range(N):
    for u, d in E[v]:
        if dist[v] + d != dist[u]:
            ans = "No"
            break
    if ans == "No":
        break
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    global X, G
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        else:
            if X[w] != X[u] + d:
                return False

    return True


flag = True
for i in range(N):
    if X[i] is None:
        X[i] = 0
        flag &= dfs(i)

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

Solution (Python):
import sys
sys.setrecursionlimit(200002)
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    global X, G
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        else:
            if X[w] != X[u] + d:
                return False

    return True


flag = True
for i in range(N):
    if X[i] is None:
        X[i] = 0
        flag &= dfs(i)

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

Solution (Python):
N,M = map(int,input().split())
src = [tuple(map(int,input().split())) for i in range(M)]

class WeightedUnionFind:
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self.rank = [0] * N
        self.count = 0
        self.weight = [0] * N
    def root(self,a):
        if self.parent[a] == a:
            return a
        else:
            pa = self.root(self.parent[a])
            self.weight[a] += self.weight[self.parent[a]]
            self.parent[a] = pa
            return pa
    def is_same(self,a,b):
        return self.root(a) == self.root(b)
    def unite(self,a,b,w):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb: return
        if self.rank[ra] < self.rank[rb]:
            self.parent[ra] = rb
            self.weight[ra] = w - self.weight[a] + self.weight[b]
        else:
            self.parent[rb] = ra
            self.weight[rb] = -w - self.weight[b] + self.weight[a]
            if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1
        self.count += 1
    def diff(self,a,b):
        return self.weight[a] - self.weight[b]

wuf = WeightedUnionFind(N)
for l,r,d in src:
    l,r = l-1, r-1
    if wuf.is_same(l,r):
        if d != wuf.diff(l,r):
            print('No')
            exit()
    else:
        wuf.unite(l,r,d)
print('Yes')