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):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



N, M = MAP()
LRD = [LIST() for _ in range(M)]

graph = [[] for _ in range(N)]
for L, R, D in LRD:
	graph[L-1].append((R-1, D))
	graph[R-1].append((L-1, -D))

check = [1]*N
i = 0
while i < N:
	while check[i] == 0:
		i += 1
		if i == N:
			print("Yes")
			exit()

	check[i] = 0
	dis = defaultdict(int)
	dis[i] = 0
	q = deque([i])
	while q:
		p = q.popleft()
		for v, dist in graph[p]:
			if check[v] == 1:
				check[v] = 0
				dis[v] = dis[p] + dist
				q.append(v)
			if check[v] == 0 and dis[v] != dis[p] + dist:
				print("No")
				exit()

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+1)
for i in range(M):
  l,r,d=map(int,input().split())
  if l>r:
    l,r=r,l
    d=-d
  if uf.same(l,r) and d != uf.diff(l,r):
    print('No')
    exit()
  uf.union(l,r,d)
print('Yes')

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


class UnionFindWeighted:
    
    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:
            root = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = root
            return root

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

        if rx == ry:
            return

        if self.parents[rx] > self.parents[ry]:
            x, y, rx, ry, w = y, x, ry, rx, -w

        self.parents[rx] += self.parents[ry]
        self.parents[ry] = rx
        self.weight[ry] = self.weight[x] - self.weight[y] - w

    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 main():
    N, M, *LRD = map(int, read().split())

    uf = UnionFindWeighted(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


class UnionFindWeighted:
    
    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:
            root = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = root
            return root

    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, w = y, x, -w

        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = -w

    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 main():
    N, M, *LRD = map(int, read().split())

    uf = UnionFindWeighted(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


class UnionFindWeighted:
    
    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:
            root = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = root
            return root

    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, w = y, x, -w

        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = -w

    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 main():
    N, M, *LRD = map(int, read().split())

    uf = UnionFindWeighted(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


class UnionFindWeighted:
    
    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:
            root = self.find(self.parents[x])
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = root
            return root

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

        if rx == ry:
            return

        if self.parents[rx] > self.parents[ry]:
            x, y, rx, ry, w = y, x, ry, rx, -w

        self.parents[rx] += self.parents[ry]
        self.parents[ry] = rx
        self.weight[ry] = self.weight[x] - self.weight[y] - w

    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 main():
    N, M, *LRD = map(int, read().split())

    uf = UnionFindWeighted(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007



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]


def main():
    N, M, *LRD = map(int, read().split())

    uf = WeightedUnionFind(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, *LRD = map(int, read().split())

    G = [[] for _ in range(N)]
    for l, r, d in zip(*[iter(LRD)] * 3):
        G[l - 1].append((r - 1, d))
        G[r - 1].append((l - 1, -d))

    seen = [False] * N
    dist = [-1] * N
    for i in range(N):
        if seen[i]:
            continue

        dist[i] = 0
        queue = deque([i])
        while queue:
            v = queue.popleft()
            for nv, d in G[v]:
                if seen[nv]:
                    if dist[nv] != dist[v] + d:
                        print('No')
                        return
                else:
                    dist[nv] = dist[v] + d
                    seen[nv] = True
                    queue.append(nv)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, M, *LRD = map(int, read().split())

    G = [[] for _ in range(N)]
    for l, r, d in zip(*[iter(LRD)] * 3):
        G[l - 1].append((r - 1, d))
        G[r - 1].append((l - 1, -d))

    dist = [INF] * N
    for i in range(N):
        if dist[i] != INF:
            continue

        dist[i] = 0
        queue = deque([i])
        while queue:
            v = queue.popleft()
            for nv, d in G[v]:
                if dist[nv] != INF:
                    if dist[nv] != dist[v] + d:
                        print('No')
                        return
                else:
                    dist[nv] = dist[v] + d
                    queue.append(nv)

    print('Yes')
    return


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

def bfs():
    visit = [0] * (n + 1)
    e = [0] * (m + 1)
    x = [0] * (n + 1)
    q = deque()
    for i in range(1, n + 1):
        if not visit[i]:
            q.append(i)
            visit[i] = 1
            while q:
                j = q.popleft()
                for g in G[j]:
                    if not e[g[2]]:
                        
                        e[g[2]] = 1
                        if not visit[g[0]]:
                            x[g[0]] = g[1] + x[j]
                            visit[g[0]] = 1
                            q.append(g[0])
                        else:
                            
                            if not x[g[0]] == g[1] + x[j]:
                                return False
    return True

n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
for i in range(m):
    l, r, d = map(int, input().split())
    G[l].append([r, d, i])
    G[r].append([l, -d, i])
print("Yes" if bfs() else "No")

Solution (Python):
n,m=map(int,input().split())
INF=10**18
e=[[]for _ in range(n+1)]
for _ in range(m):
  l,r,d=map(int,input().split())
  e[l]+=[(r,d)]
  e[r]+=[(l,-d)]
d=[INF]*(n+1)
for i in range(n+1):
  if d[i]!=INF:continue
  d[i]=0
  q=[i]
  while q:
    now=q.pop()
    for to,dist in e[now]:
      if d[to]==INF:
        d[to]=d[now]+dist
        q+=[to]
      else:
        if d[to]!=d[now]+dist:
          print('No')
          exit()
print('Yes')

Solution (Python):
import sys
from collections import deque

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

edges = [[] for _ in range(N)]
for _ in range(M):
    l, r, d = map(int, sys.stdin.readline().split())
    edges[l-1].append((r-1, d))
    edges[r-1].append((l-1, -d))

visited = {}

for i in range(N):
    if i in visited:
        continue

    
    
    q = deque([(i, 0)])
    while q:
        l, c = q.popleft()
        if l in visited:
            if visited[l] != c:
                print("No")
                sys.exit()
            continue
        
        visited[l] = c
        

        for r, nd in edges[l]:
            q.append((r, c+nd))
    

print("Yes")

Solution (Python):
import sys
from collections import deque

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

edges = [[] for _ in range(N)]
for _ in range(M):
    l, r, d = map(int, sys.stdin.readline().split())
    edges[l-1].append((r-1, d))
    edges[r-1].append((l-1, -d))

visited = {}

for i in range(N):
    if i in visited:
        continue

    
    
    q = deque([(i, 0)])
    while q:
        l, c = q.popleft()
        if l in visited:
            if visited[l] != c:
                print("No")
                sys.exit()
            continue
        
        visited[l] = c
        

        for r, nd in edges[l]:
            q.append((r, c+nd))
    

print("Yes")

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

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

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

    
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            p = self.par[x]  
            self.par[x] = self.find(self.par[x])
            self.weight[x] += self.weight[p]
            return self.par[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:  
            if self.rank[x] < self.rank[y]:  
                x,y = y,x
                w = -w
            if self.rank[x] == self.rank[y]:  
                self.rank[x] += 1
            
            self.par[x] += self.par[y]
            self.par[y] = x
            self.weight[y] = w

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

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

n,m = readints()

u = UnionFind_weight(n)

ans = 1
for i in range(m):
    l,r,d = readints()
    l-=1;r-=1
    if u.same(l,r):
        if u.diff(l,r) != d:
            ans = 0
            break
    else:
        u.unite(l,r,d)

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

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

N,M = map(int,input().split())
G = [[] for _ in [0]*N]

for _ in [0]*M:
  a, b, d = map(int, input().split())
  a -= 1
  b -= 1
  G[a].append((b, d))
  G[b].append((a, -d))

X = [None]*N

def dfs(i, x=0):
  for j, d in G[i]:
    if X[j] is None:
      X[j] = x+d
      dfs(j, x+d)
    elif X[j] != x+d:
      print('No')
      exit()

for i in range(N):
  if X[i] is not None:
    continue
  X[i] = 0
  dfs(i)
print('Yes')

Solution (Python):
from collections import deque 

s = deque([])

N,M=map(int,input().split())
G = [[] for i in range(N+1)]

LRD = []
for i in range(M):
    L,R,D = map(int,input().split())
    G[L].append([R,D])
    G[R].append([L,-D])

ans = True
X = [None]*(N+1)
for i in range(1,N+1):

    if X[i]==None:
        s.append([i,0])

    while len(s)>0:
        j,x = s.pop()
        if X[j]==None:
            X[j]=x
            for nex in G[j]:
                s.append([nex[0],x+nex[1]])
        else:
            if X[j]!=x:
                ans = False
                break

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

Solution (Python):
import sys
sys.setrecursionlimit(2*10**6)
input = sys.stdin.readline
N, M = map(int, input().split())
G = [[] for _ in [0]*N]
for _ in [0]*M:
    a, b, d = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append((b, d))
    G[b].append((a, -d))

X = [None]*N

def dfs(i, x=0):
    for j, d in G[i]:
        if X[j] is None:
            X[j] = x+d
            dfs(j, x+d)
        elif X[j] != x+d:
            print('No')
            exit()

for i in range(N):
    if X[i] is not None:
        continue
    X[i] = 0
    dfs(i)
print('Yes')

Solution (Python):
from collections import deque
def check():
  N, M = map(int, input().split())
  edge = [[] for _ in range(N)]
  for i in range(M):
    a,b,d = map(int, input().split())
    edge[a-1].append([b-1,d])
    edge[b-1].append([a-1,-d])
  
  visited = [float('inf')]*N
  D = deque()
  for i in range(N):
    if visited[i]==float('inf'):
      visited[i]=0
      D.append(i)
      while len(D)>0:
        v = D.popleft()
        for w,d in edge[v]:
          if visited[w]==float('inf'):
            visited[w] = visited[v]+d
            D.append(w)
          elif visited[w]!=visited[v]+d:
            return 'No'
  return 'Yes'
print(check())

Solution (Python):
n, m = map(int, input().split())
lrd = [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]


uf = WeightedUnionFind(n)
for l, r, d in lrd:
    l, r = l-1, r-1
    if uf.is_same(l, r):
        if uf.diff(l, r) != d:
            print('No')
            exit(0)
    else:
        uf.unite(l, r, d)

print('Yes')

Solution (Python):

import sys

YES = "Yes"  
NO = "No"  


def solve(N: int, M: int, L: "List[int]", R: "List[int]", D: "List[int]"):
    uf = UnionFind(N+1)
    try:
        for l, r, d in zip(L, R, D):
            uf.merge(l, r, d)
        return YES
    except MergeError:
        return NO


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    L = [int()] * (M)  
    R = [int()] * (M)  
    D = [int()] * (M)  
    for i in range(M):
        L[i] = int(next(tokens))
        R[i] = int(next(tokens))
        D[i] = int(next(tokens))
    print(solve(N, M, L, R, D))
    
class MergeError(Exception):
    pass


class UnionFind:
    def __init__(self, size: int):
        self.par = list(range(size))
        self.rank = [0] * size
        self.diff_weight = [0] * size

    def root(self, x: int):
        if self.par[x] == x:
            return x
        r = self.root(self.par[x])
        self.diff_weight[x] += self.diff_weight[self.par[x]] 
        
        self.par[x] = r
        return r

    def weight(self, x: int):
        self.root(x) 
        return self.diff_weight[x]

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

    
    def merge(self, x: int, y: int, w: int):
        
        adjusted_w = w + self.weight(x) - self.weight(y)
        x = self.root(x)
        y = self.root(y)
        if x == y:
            if adjusted_w != 0:
                raise MergeError
            return
        if self.rank[x] < self.rank[y]:
            x, y, adjusted_w = y, x, -adjusted_w
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.par[y] = x
        self.diff_weight[y] = adjusted_w

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    
    main()

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7





N, M = getNM()
dist = [[] for i in range(N)]
for i in range(M):
    l, r, d = getNM()
    dist[l - 1].append([r - 1, d])
    dist[r - 1].append([l - 1, -d])

dis = [float('inf')] * N

pos = deque([i for i in range(N)])
while len(pos) > 0:
    u = pos.popleft()
    
    if dis[u] == float('inf'):
        dis[u] = 0
    
    
    for to, d in dist[u]:
        if dis[to] == float('inf'):
            dis[to] = dis[u] + d
            
            
            
            
            
            
            
            
            pos.appendleft(to)
        else:
            if dis[u] + d != dis[to]:
                print('No')
                exit()
print('Yes')

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7





N, M = getNM()
dist = [[] for i in range(N)]
for i in range(M):
    l, r, d = getNM()
    dist[l - 1].append([r - 1, d])
    dist[r - 1].append([l - 1, -d])

dis = [float('inf')] * N

pos = deque([i for i in range(N)])
while len(pos) > 0:
    u = pos.popleft()
    
    if dis[u] == float('inf'):
        dis[u] = 0
    
    
    for to, d in dist[u]:
        if dis[to] == float('inf'):
            dis[to] = dis[u] + d
            pos.appendleft(to)
        else:
            if dis[u] + d != dis[to]:
                print('No')
                exit()
print('Yes')

Solution (Python):
n,m=list(map(int,input().split()))
g=[[] for _ in range(n+1)]
visited=[0]*(n+1)
x=[0]*(n+1)

for _ in range(m):
    l,r,d=list(map(int,input().split()))

    g[r].append((l,d))
    g[l].append((r,-d))

stack=list(range(1,n+1))

while len(stack)>0:
    u=stack.pop()

    visited[u]=1

    for v,d in g[u]:
        if visited[v]==1:
            continue

        x[v]=x[u]-d

        stack.append(v)

flag=True

for i in range(1,n+1):
    for j,d in g[i]:
        if x[i]-x[j]!=d:
            flag=False

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

Solution (Python):
from collections import deque
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
for _ in range(m):
    l, r, d = map(int, input().split())
    graph[l-1].append((r-1, d))
    graph[r-1].append((l-1, -d))
seen = [False]*n
dist = [None]*n
for i in range(n):
    if seen[i]:
        continue
    q = deque([i])
    dist[i] = 0
    while q:
        node = q.popleft()
        if seen[node]:
            continue
        seen[node] = True
        for c_node, d in graph[node]:
            if dist[c_node] is None:
                dist[c_node] = dist[node] + d
            elif dist[c_node] != dist[node] + d:
                print('No')
                exit(0)
            q.append(c_node)
print('Yes')

Solution (Python):
from collections import deque
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
for _ in range(m):
    l, r, d = map(int, input().split())
    graph[l-1].append((r-1, d))
    graph[r-1].append((l-1, -d))
seen = [False]*n
dist = [None]*n
for i in range(n):
    if seen[i]:
        continue
    q = deque([i])
    dist[i] = 0
    while q:
        node = q.popleft()
        if seen[node]:
            continue
        seen[node] = True
        for c_node, d in graph[node]:
            if dist[c_node] is None:
                dist[c_node] = dist[node] + d
            elif dist[c_node] != dist[node] + d:
                print('No')
                exit(0)
            if not seen[c_node]:
                q.append(c_node)
print('Yes')