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 = map(int, input().split())
G = [[] for _ in range(n)]
indeg = [0] * n

for _ in range(m):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    G[l].append((r, d))
    G[r].append((l, -d))

from collections import deque
ng = False
visited = [0] * n
visited_cost = [0] * n

for start in range(n):
    if visited[start]:
        continue
    visited[start] = 1
    st = deque([[start, 0]])
    while st:
        i, cost = st.pop()
        for ni, nd in G[i]:
            if visited[ni] == 0:
                visited[ni] = 1
                visited_cost[ni] = cost + nd
                st.append([ni, cost + nd])
            else:
                
                if visited_cost[ni] != cost + nd:
                    
                    ng = True
                    break
        if ng:
            break
    if ng:
        break
print('No' if ng else 'Yes')

Solution (Python):
from collections import deque
N,M=map(int, input().split())
A=[[]for _ in range(N)]
V=[False]*N
X=[0]*N
x=0
for i in range(M):
  L,R,D=map(int, input().split())
  A[L-1].append((R-1,D))
  A[R-1].append((L-1,-D))
  
for i in range(N):
  if V[i]==False:
    stack=deque([(i,x)])
    V[i]=True
    while stack:
      now,dx=stack.popleft()
      for new,di in A[now]:
        if V[new]:
          if X[new]!=dx+di:
            print('No')
            exit()
        else:
          X[new]=dx+di
          V[new]=True
          stack.append((new,dx+di))

if max(X)-min(X)>10**9:
  print('No')
else:
  print('Yes')

Solution (Python):
from collections import deque

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

G = [[] for _ in range(N)]
for i in range(M):
  L, R, D = map(int, input().split())
  G[L-1].append((R-1, D))
  G[R-1].append((L-1, -D))
  
visited = [False] * N
xs = [0] * N
xs[0] = 0
x = 0
for i in range(N):
  if visited[i]:
    continue
  stack = deque([(i, x)])
  visited[i] = True
  while stack:
    now, xi = stack.popleft()
    for nx, di in G[now]:
      if visited[nx]:
        if xs[nx] != xi + di:
          print('No')
          exit()
      else:
        xs[nx] = xi + di
        visited[nx] = True
        stack.append((nx, xi+di))
        
if max(xs)-min(xs) > 1000000000:
  print('No')
else:
  print('Yes')

Solution (Python):

class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            px = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = px
            return px

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w
        return

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

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

    def size(self, x):
        return -self.parents[self.find(x)]

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


n, m = map(int, input().split())
UF = WeightedUnionFind(n + 1)

for i in range(m):
    l, r, d = map(int, input().split())
    if UF.same(l, r):
        if d != abs(UF.diff(l, r)):
            exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")

Solution (Python):

class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            px = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = px
            return px

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w
        return

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

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

    def size(self, x):
        return -self.parents[self.find(x)]

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


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

for i in range(m):
    l, r, d = map(int, input().split())
    l -= 1;r -= 1
    if UF.same(l, r):
        if d != abs(UF.diff(l, r)):
            exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")

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

people = [-1]*(N)
flag = 0

not_visited = {}
for i in range(N):
    not_visited[i] = True

stack = list(range(N))

while stack:
    now = stack.pop()

    for j in info[now]:
        if not_visited[j[0]]:
            stack.append(j[0])
        
        if people[j[0]] == -1:
            people[j[0]] = people[now] + j[1] 
        else:
            if people[j[0]] != people[now] + j[1]:
                flag = -1

        not_visited[now] = False

if flag != -1:
    print("Yes")
else:
    print("No")

Solution (Python):
from collections import deque
import sys

input = sys.stdin.readline

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

dis = [10**10] * n
edges = [[] for _ in range(n)]

for _ in range(m):
    l,r,d = map(int,input().split())
    edges[l-1].append((r-1, d))
    edges[r-1].append((l-1, -d))

for i in range(n):
    if dis[i] == 10**10:
        dis[i] = 0
        q = [i]
        while q:
            l = q.pop()
            for r,d in edges[l]:
                if dis[r] == 10**10:
                    dis[r] = dis[l] + d
                    q.append(r)
                else:
                    if dis[r] - dis[l] != d:
                        print('No')
                        exit()

print('Yes')

Solution (Python):
from collections import deque
import sys

input = sys.stdin.readline

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

dis = [10**10] * n
edges = [[] for _ in range(n)]

for _ in range(m):
    l,r,d = map(int,input().split())
    edges[l-1].append((r-1, d))
    edges[r-1].append((l-1, -d))

for i in range(n):
    if dis[i] == 10**10:
        dis[i] = 0
        q = deque([i])
        while q:
            l = q.popleft()
            for r,d in edges[l]:
                if dis[r] == 10**10:
                    dis[r] = dis[l] + d
                    q.append(r)
                else:
                    if dis[r] - dis[l] != d:
                        print('No')
                        exit()

print('Yes')

Solution (Python):

from sys import stdin

N, M = map(int, stdin.readline().split())

links = [[] for _ in range(N + 1)]
for _ in range(M):
    L, R, D = map(int, stdin.readline().split())
    links[L].append((R, D))
    links[R].append((L, -D))

t = [None] * (N + 1)
for i in range(1, N + 1):
    if t[i] is not None:
        continue
    t[i] = 0
    s = [i]
    while s:
        j = s.pop()
        for k, l in links[j]:
            if t[k] is None:
                t[k] = t[j] + l
                s.append(k)
            else:
                if t[k] != t[j] + l:
                    print('No')
                    exit()
print('Yes')

Solution (Python):

from sys import setrecursionlimit, stdin


def find(parent, diff_weight, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, diff_weight, t)
    diff_weight[i] += diff_weight[parent[i]]
    parent[i] = t
    return t


def weight(parent, diff_weight, i):
    find(parent, diff_weight, i)
    return diff_weight[i]


def unite(parent, diff_weight, i, j, d):
    d -= weight(parent, diff_weight, j)
    d += weight(parent, diff_weight, i)
    i = find(parent, diff_weight, i)
    j = find(parent, diff_weight, j)
    if i == j:
        return
    diff_weight[j] = d
    parent[i] += parent[j]
    parent[j] = i


setrecursionlimit(10 ** 6)

N, M = map(int, stdin.readline().split())
LRD = [tuple(map(int, stdin.readline().split())) for _ in range(M)]

parent = [-1] * (N + 1)
diff_weight = [0] * (N + 1)
for L, R, D in LRD:
    i = find(parent, diff_weight, L)
    j = find(parent, diff_weight, R)
    if i != j:
        unite(parent, diff_weight, L, R, D)
    else:
        if weight(parent, diff_weight, L) + D != weight(parent, diff_weight, R):
            print('No')
            exit()
print('Yes')

Solution (Python):

from sys import setrecursionlimit


def find(parent, diff_weight, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, diff_weight, t)
    diff_weight[i] += diff_weight[parent[i]]
    parent[i] = t
    return t


def weight(parent, diff_weight, i):
    find(parent, diff_weight, i)
    return diff_weight[i]


def unite(parent, diff_weight, i, j, d):
    d -= weight(parent, diff_weight, j)
    d += weight(parent, diff_weight, i)
    i = find(parent, diff_weight, i)
    j = find(parent, diff_weight, j)
    if i == j:
        return
    diff_weight[j] = d
    parent[i] += parent[j]
    parent[j] = i


setrecursionlimit(10 ** 6)

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

parent = [-1] * (N + 1)
diff_weight = [0] * (N + 1)
for L, R, D in LRD:
    i = find(parent, diff_weight, L)
    j = find(parent, diff_weight, R)
    if i != j:
        unite(parent, diff_weight, L, R, D)
    else:
        if weight(parent, diff_weight, L) + D != weight(parent, diff_weight, R):
            print('No')
            exit()
print('Yes')

Solution (Python):

from sys import setrecursionlimit


def find(parent, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, t)
    parent[i] = t
    return t


def pos(x, i):
    j, k = x[i]
    if i == j:
        return i, 0
    l, m = pos(x, j)
    x[i] = (l, m + k)
    return x[i]


setrecursionlimit(10 ** 6)

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

parent = [-1] * (N + 1)
x = [(i, 0) for i in range(N + 1)]
for L, R, D in LRD:
    i = find(parent, L)
    j = find(parent, R)
    if i != j:
        x[j] = (i, D - pos(x, R)[1] + pos(x, L)[1])
        parent[i] += parent[j]
        parent[j] = i
    else:
        if pos(x, L)[1] + D != pos(x, R)[1]:
            print('No')
            exit()
print('Yes')

Solution (Python):
from collections import deque

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

links = [[] for _ in range(N + 1)]
for _ in range(M):
    L, R, D = map(int, input().split())
    links[L].append((R, D))
    links[R].append((L, -D))

t = [None] * (N + 1)
for i in range(1, N + 1):
    if t[i] is not None:
        continue
    t[i] = 0
    s = deque([i])
    while s:
        j = s.popleft()
        for k, l in links[j]:
            if t[k] is None:
                t[k] = t[j] + l
                s.append(k)
            else:
                if t[k] != t[j] + l:
                    print('No')
                    exit()
print('Yes')

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

links = [[] for _ in range(N + 1)]
for _ in range(M):
    L, R, D = map(int, input().split())
    links[L].append((R, D))
    links[R].append((L, -D))

t = [None] * (N + 1)
for i in range(1, N + 1):
    if t[i] is not None:
        continue
    t[i] = 0
    s = [i]
    while s:
        j = s.pop()
        for k, l in links[j]:
            if t[k] is None:
                t[k] = t[j] + l
                s.append(k)
            else:
                if t[k] != t[j] + l:
                    print('No')
                    exit()
print('Yes')

Solution (Python):
import sys
input=sys.stdin.readline

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x
        P[y]=x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def DD(x):
  dis=0
  while x>=0:
    dis=dis+D[x]
    x=P[x]
  return dis

n,m=map(int,input().split())
uf=UnionFind(n)
D=[0]*n
P=[-1]*n
f=0
for i in range(m):
  l,r,d=map(int,input().split())
  l=l-1
  r=r-1
  if uf.find(l)!=uf.find(r):
    if uf.parents[uf.find(l)]<=uf.parents[uf.find(r)]:
      D[uf.find(r)]=DD(l)+d-DD(r)
    else:
      D[uf.find(l)]=DD(r)-d-DD(l)
    uf.union(l,r)
  else:
    if DD(r)-DD(l)!=d:
      f=1
if f==0:
  print("Yes")
else:
  print("No")

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 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())
uf = WeightedUnionFind(N)

for _ in range(M):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if uf.same(l, r):
        diff = uf.diff(l, r)
        if diff != d:
            print("No")
            exit()
    else:
        uf.union(l, r, d)

print("Yes")

Solution (Python):
import sys
N, M = map(int, sys.stdin.readline().rstrip().split())

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]

unionfind = WeightedUnionFind(N)

for _ in range(M):
    l, r, d = map(int, sys.stdin.readline().rstrip().split())
    if not unionfind.same(l, r):
        unionfind.union(l, r, d)
    else:
        if unionfind.diff(l, r) != d:
            print("No")
            break
else:
    print("Yes")

Solution (Python):


import sys








from collections import deque                
















from operator import itemgetter              




def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())

            


    def no_contradict_p(info):
        visited = [False] * n
        dist_list = [None] * n

        def bfs_and_check_no_contradict(start):
            dist_list[start] = 0
            q = deque([start])
            while q:
                u = q.popleft()
                if not visited[u]:
                    visited[u] = True
                    for v, dist in info[u]:
                        if dist_list[v] is None:
                            dist_list[v] = dist_list[u] + dist
                        elif dist_list[v] != dist_list[u] + dist:
                            return False
                    for v, dist in info[u]:
                        if not visited[v]:
                            q.append(v)
            return True
        
        for i in range(n):
            if not visited[i]:
                if not bfs_and_check_no_contradict(i):
                    return False
        return True


    
    n, m = mi()
    info = [[] for _ in range(n)]
    for _ in range(m):
        l, r, dist = mi_0()
        dist += 1
        info[l].append((r, dist))
        info[r].append((l, -dist))
    
    print('Yes') if no_contradict_p(info) else print('No')



if __name__ == "__main__":
    main()

Solution (Python):
import sys
n,m=map(int,input().split())
par=[-1]*n
wei=[0]*n




def find(x):
    if par[x] < 0:
        return x
    else:
        px = find(par[x])
        wei[x] += wei[par[x]]
        par[x] = px
        return px


def weight(x):
    find(x)
    return wei[x]


def unite(x,y,w):
    w += wei[x]-wei[y]
    x = find(x)
    y = find(y)
    
    if x == y:
        return False
    else:
        
        if par[x] > par[y]:
            x,y = y,x
            w = -w
        par[x] += par[y]
        par[y] = x
        wei[y] = w
        return True


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


def size(x):
    return -par[find(x)]


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


for i in range(m):
    l,r,d=map(int,input().split())
    if same(l-1,r-1):
        if d!=diff(l-1,r-1):
            print('No')
            sys.exit()
    else:
        unite(l-1,r-1,d)

print('Yes')

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

graph = [[] for i in range(N)]
left = set()
right = set()
for i in range(M):
  l, r, d = map(int, input().split())
  l -= 1; r -= 1
  graph[l].append((r, d))
  graph[r].append((l, -d))
  left.add(l); right.add(r)

root = left - right
if M and len(root) == 0:
  print('No')
  quit()

X = [None] * N
while root:
  node = root.pop()
  X[node] = 0
  stack = [node]
  while stack:
    node = stack.pop()
    while graph[node]:
      child, d = graph[node].pop()
      if X[child] is None:
        X[child] = X[node] + d
        stack.append(child)
      elif X[child] != X[node] + d:
        print('No')
        quit()

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 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())
lrd = [[int(i) for i in input().split()] for j in range(m)]

ki = WeightedUnionFind(n)

for i in range(m):
    if ki.same(lrd[i][0],lrd[i][1]):
        if ki.diff(lrd[i][0],lrd[i][1]) != lrd[i][2]:
            print('No')
            exit()
    else:
        ki.union(lrd[i][0],lrd[i][1],lrd[i][2])
    
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 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())
lrd = [[int(i) for i in input().split()] for j in range(m)]

ki = WeightedUnionFind(n)

for i in range(m):
    if ki.same(lrd[i][0],lrd[i][1]):
        if ki.diff(lrd[i][0],lrd[i][1]) != lrd[i][2]:
            print('No')
            exit()
    else:
        ki.union(lrd[i][0],lrd[i][1],lrd[i][2])
    
print('Yes')

Solution (Python):

class PotentialUnionFind:
    
    
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n
        self.weight = [0] * n

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

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

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

    
    def size(self, x):
        return -self.find(x)

    
    
    def unite(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False

        if self.par[x] > self.par[y]:
            x, y = y, x
            w = -w
        self.par[x] += self.par[y]
        self.par[y] = x
        self.weight[y] = w
        return True

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


n, m = map(int, input().split())
PUF = PotentialUnionFind(n)
flag = 0
for _ in range(m):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if PUF.is_same(l, r):
        if abs(PUF.diff(l, r)) == d:
            continue
        else:
            flag = 1
    else:
        PUF.unite(l, r, d)

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

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


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


class WeightedUnionFind:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.parents = [-1] * n_nodes

        
        self.weights = [0] * n_nodes

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            parent = self.find(self.parents[x])
            self.weights[x] += self.weights[self.parents[x]]
            self.parents[x] = parent
            return parent

    
    def unite(self, x, y, w):
        w += self.weights[x]
        w -= self.weights[y]
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w *= -1

        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weights[y] = w
        return

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

    def get_size(self, x):
        return -self.parents[self.find(x)]

    def get_weight(self, x, y):
        return self.weights[y] - self.weights[x]


def main():
    N, M = map(int, input().split())
    tree = WeightedUnionFind(N)
    for _ in range(M):
        L, R, D = map(int, input().split())
        L -= 1
        R -= 1

        if tree.is_same(L, R):
            if tree.get_weight(L, R) == D:
                continue
            else:
                print("No")
                return
        else:
            tree.unite(L, R, D)

    print("Yes")
    return


if __name__ == "__main__":
    main()

Solution (Python):
import sys
import numpy as np


def inputs(func=lambda x: x, sep=None, maxsplit=-1):
	return map(func, sys.stdin.readline().split(sep=sep, maxsplit=maxsplit))

def input_row(n : int, type=np.int, *args, **kwargs):
	return np.fromiter(inputs(type, *args, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, *args, **kwargs):
	data = np.zeros((nrows, ncols), dtype=type)
	for i in range(nrows):
		data[i, :] = input_row(ncols, type, *args, **kwargs)
	return data

class IntAddition (object):
	'''整数の加法'''
	def operate(self, x, y):
		return x + y
	@property
	def identity(self):
		return 0
	def cancel(self, x, y):
		return x - y
	def invert(self, x):
		return -x
	def accumulate(self, x, count):
		return x * count

class UnionFindNode (object):
	__slots__ = [
		'parent_index',
		'size',
		'difference_from_parent'
	]
	
	def __init__(self, index : int, potential_identity):
		self.parent_index = index
		self.size = 1
		self.difference_from_parent = potential_identity

class UnionFind (object):
	'''重み付きUnion-Find木'''
	def __init__(
			self,
			num_nodes=0,
			potential_abelian=IntAddition()):
		self.nodes = []
		self.op = potential_abelian
		
		self.extend(num_nodes)
	
	def append(self):
		self.nodes.append(
			UnionFindNode(len(self.nodes), self.op.identity)
		)
		
	def extend(self, num_nodes):
		self.nodes.extend(
			UnionFindNode(i, self.op.identity)
			for i in range(num_nodes)
		)
	
	def root(self, index : int):
		x = self.nodes[index]
		
		while x.parent_index != index:
			parent = self.nodes[x.parent_index]
			x.difference_from_parent = self.op.operate(
				x.difference_from_parent,
				parent.difference_from_parent
			)
			index = x.parent_index = parent.parent_index
			x = self.nodes[index]
		
		return index
	
	def difference_from_root_to(self, index : int):
		x = self.nodes[index]
		potential = x.difference_from_parent
		
		while x.parent_index != index:
			parent = self.nodes[x.parent_index]
			potential = self.op.operate(
				potential,
				parent.difference_from_parent
			)
			index = x.parent_index
			x = self.nodes[index]
		
		return potential
		
	def size(self, index : int):
		return self.nodes[self.root(index)].size
	
	def difference(self, x, y):
		if not self.issame(x, y):
			raise RuntimeError('x と y は同じ集合に属していません。')
		return self.op.cancel(
			self.difference_from_root_to(y),
			self.difference_from_root_to(x)
		)
	
	def unite(self, x, y, difference=None) -> bool:
		if difference is None:
			difference = self.op.identity
		
		x, px = self.root(x), self.difference_from_root_to(x)
		y, py = self.root(y), self.difference_from_root_to(y)
		if x == y:
			return difference == self.op.cancel(py, px)
		
		difference = self.op.cancel(difference, py)
		difference = self.op.operate(difference, px)
		
		if self.size(x) < self.size(y):
			x, y = y, x
			difference = self.op.invert(difference)
		
		x_node = self.nodes[x]
		y_node = self.nodes[y]
		x_node.size += y_node.size
		y_node.parent_index = x
		y_node.difference_from_parent = difference
		
		return True
	
	def issame(self, x, y):
		return self.root(x) == self.root(y)



N, M = inputs(int)
uf = UnionFind(num_nodes=N)

valid = True
for i in range(M):
	L, R, D = inputs(int)
	L -= 1
	R -= 1
	
	valid = valid and uf.unite(L, R, D)

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