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):
from collections import deque

class MakeGraph:
    
    
    
    
    def __init__(self, node_num:int, isMat:bool) -> None:
        self.n = node_num
        self.isMat = isMat

        
        if self.isMat:
            INF = float("inf")
            self.graph = [[INF for _ in range(self.n)] for _ in range(self.n)]
    
        
        else:
            self.graph = [[] for _ in range(self.n)]

    
    
    
    def add_undr_edge_mat(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm][to] = dist
        self.graph[to][frm] = dist
        
    def add_drct_edge_mat(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm][to] = dist
        
    def add_undr_edge_lst(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm].append((dist, to))
        self.graph[to].append((dist, frm))
        
    def add_drct_edge_lst(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm].append((dist, to))

                
    
    def get_graph(self) -> list:
        return self.graph


class DfsAndBfs:
 
  
  
  
  @classmethod
  def dfs(cls, graph:list, node:int) -> list:
    
    INF = float("inf")
    dist = [-INF]*node  
    
    
    for n in range(node):
        if dist[n] != -INF:
            continue
        else:
            stack = [n]
            dist[n] = 0
            
        
        while len(stack):
            cur = stack.pop()
            
            
            for cost, nex_node in graph[cur]:
                if dist[nex_node] != -INF:
                    continue
                else:
                    dist[nex_node] = dist[cur] + cost
                    stack.append(nex_node)

    return dist
 
  
  
  
  
  @classmethod
  def bfs(cls, graph:list, node:int) -> list:
      
      INF = float("inf")
      dist = [-INF]*node

      
      for n in range(node):
          if dist[n] != -INF:
              continue
          else:
              que = deque([n])
              dist[n] = 0

          
          while len(que):
              cur = deque.popleft(que)

              
              for cost, nex_node in graph[cur]:
                  if dist[nex_node] != -INF:
                      continue
                  else:
                      dist[nex_node] = dist[cur] + cost
                      que.append(nex_node)

      return dist
  

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

graphMaker = MakeGraph(N, False)
add_edge = graphMaker.add_drct_edge_lst
for l,r,d in LRD:
    add_edge(l-1,r-1,d)
    add_edge(r-1,l-1,-d)
    
graph = graphMaker.get_graph()

dist = DfsAndBfs.dfs(graph, N)



consistent = True

for l,r,d in LRD:
    if dist[r-1] - dist[l-1] == d:
        continue
    else:
        consistent = False
        break

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

Solution (Python):
class UnionFind:
    __slots__ = ["nodes", "weight"]
    
    def __init__(self, n: int) -> None:
        self.nodes = [-1]*n
        self.weight = [0]*n
        
    def get_root(self, x:int) -> int:
        if x<0:
            raise ValueError("Negative Index")
        
        if self.nodes[x]<0:
            return x
        else:
            parent, self.nodes[x] = self.nodes[x], self.get_root(self.nodes[x])
            self.weight[x] += self.weight[parent]
            return self.nodes[x]

    def unite(self, x:int, y:int) -> None:
        if x<0 or y<0:
            raise ValueError("Negative Index")
            
        root_x, root_y = self.get_root(x), self.get_root(y)
        if root_x != root_y:
            if self.nodes[root_x] < self.nodes[root_y]:
                bigroot, smallroot = root_x, root_y
            else:
                bigroot, smallroot = root_y, root_x
                
            self.nodes[bigroot] += self.nodes[smallroot]
            self.nodes[smallroot] = bigroot

    def relate(self, smaller:int, bigger:int, diff_weight:int) -> None:
        if smaller<0 or bigger<0:
            raise ValueError("Negative Index")
            
        s_root, b_root = self.get_root(smaller), self.get_root(bigger)
        if s_root == b_root:
            if self.weight[smaller] + diff_weight == self.weight[bigger]:
                return
            raise ValueError
            
        else:
            self.weight[b_root] = diff_weight - self.weight[bigger]
            self.nodes[s_root] += self.nodes[b_root]
            self.nodes[b_root] = smaller
            
   
         
N,M = map(int, input().split())
LRD = []
for _ in range(M):
    LRD.append(tuple(map(int, input().split())))
 
uf = UnionFind(N)
relate = uf.relate    

try:
    for l,r,d in LRD:
        relate(l-1,r-1,d)
    print("Yes")
except Exception as e:
    print("No")

Solution (Python):
class WeightedUnionFind:
    """
    重み付きUnionFind

    """
    root_position = 0

    def __init__(self, size: int):
        
        
        self.size = size
        self.parent = [-1] * size
        self.weight = [WeightedUnionFind.root_position] * size

    def find(self, x: int) -> (int, int):
        """
        xを含む集合の代表とxの代表からの位置を求める
        """
        if self.parent[x] < 0:
            return x, self.weight[x]
        root, weight = self.find(self.parent[x])
        self.parent[x] = root
        self.weight[x] += weight
        return root, self.weight[x]

    def union(self, x: int, y: int, weight: int) -> bool:
        """
        xを含む集合とyを含む集合を併合する
        `weight[x] + weight = weight[y]`になるように辺に重みをもたせる。
        xとyがすでに同じ集合に含まれている場合Falseを返す。
        """
        root_x, weight_x = self.find(x)
        root_y, weight_y = self.find(y)

        if root_x == root_y:
            return False

        if self.parent[root_x] >= self.parent[root_y]:
            self.parent[root_x] += self.parent[root_y]
            self.parent[root_y] = root_x
            self.weight[root_y] = weight_x + weight - weight_y
        else:
            self.parent[root_y] += self.parent[root_x]
            self.parent[root_x] = root_y
            self.weight[root_x] = weight_y - weight - weight_x

        return True


def main():
    n, m = map(int, input().split())
    wut = WeightedUnionFind(n)
    for _ in range(m):
        l, r, d = map(int, input().split())
        l -= 1
        r -= 1
        merged = wut.union(l, r, d)
        if not merged:
            root_l, weight_l = wut.find(l)
            root_r, weight_r = wut.find(r)
            if root_l != root_r or weight_l + d != weight_r:
                return False
    return True


if __name__ == '__main__':
    result = main()
    print('Yes' if result else '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 root(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.root(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.root(x)
        ry = self.root(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.root(x) == self.root(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):
    l,r,d = map(int,input().split())
    l -= 1
    r -= 1
    if (wuf.same(l,r)):
        diff = wuf.diff(l,r)
        if (diff != d):
            print("No")
            quit()
    else:
        wuf.union(l,r,d)
print("Yes")

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, M, LRD):
    
    g = [[] for _ in range(N)]
    ns = set([])
    for l ,r, d in LRD:
        g[l-1].append((r-1,d))
        g[r-1].append((l-1,-d))
        ns.add(l-1)
        ns.add(r-1)      
    
    G =  [None for _ in range(N)]

    if M == 0:
        return 'Yes'

    ns = {n:n for n in ns}
    while ns:
        
        for k in ns.keys():
            q = [k]
            break
        ns.pop(q[0])
        
        G[q[0]] = 0
        while q:
            n = q.pop()
            for r, d in g[n]:
                if G[r] is None:
                    G[r] = G[n] + d
                    q.append(r)
                    
                    ns.pop(r)
                else:
                    if G[r] != G[n] + d:
                        return 'No'
                        
    
    return 'Yes'
            



def main():
    N, M = read_int_n()
    LRD = [read_int_n() for _ in range(M)]

    
    
    
    print(slv(N, M, LRD))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(1000000)
def search(i, total):
  for dist, to in edges[i]:
    if dists[to] == None:
      dists[to] = total + dist
      if not search(to, total + dist):
        return False
    else:
      if dists[to] == total + dist:
        continue
      else:
        return False
  return True

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

dists = [None] * n

for i in range(n):
  if dists[i] == None:
    dists[i] = 0
    if not search(i, 0):
      print("No")
      break
else:
  print("Yes")

Solution (Python):
import queue
N,M=map(int,input().split())
G=[dict() for i in range(N)]
for i in range(M):
    L,R,D=map(int,input().split())
    L-=1
    R-=1
    G[L][R]=D
    G[R][L]=-D
P=[0 for i in range(N)]
reached=[0 for i in range(N)]
q=queue.Queue()
for i in range(N):
    if reached[i]==0:
        q.put(i)
        reached[i]=1
        while(not(q.empty())):
            p=q.get()
            for r in G[p]:
                if reached[r]==0:
                    q.put(r)
                    P[r]=P[p]+G[p][r]
                else:
                    if P[r]!=P[p]+G[p][r]:
                        print("No")
                        exit()
                reached[r]=1
print("Yes")

Solution (Python):
class weight_union_find(object):
    def __init__(self, n):
        self.par = [-1 for i in range(n)]
        self.weight_diff = [0 for i in range(n)]
        self.rank = [1 for i in range(n)]
    
    def root(self, ind):
        if self.par[ind] < 0:
            return ind
        else:
            r = self.root(self.par[ind])
            self.weight_diff[ind] += self.weight_diff[self.par[ind]]
            self.par[ind] = r
            return r

    def unite(self, ind1, ind2, w):
        root1 = self.root(ind1)
        root2 = self.root(ind2)
        if root1 == root2:
            
            
            if -(self.weight_diff[ind1] - self.weight_diff[ind2]) == w:
                return True
            else:
                return False
        else:
            
            if self.rank[root1] == self.rank[root2]:
                self.rank[root1] += 1
            if self.rank[root1] < self.rank[root2]:
                root1, root2 = root2, root1
                ind1, ind2 = ind2, ind1
                w *= -1
            self.par[root1] += self.par[root2]
            self.par[root2] = root1
            self.weight_diff[root2] = w + self.weight_diff[ind1] - self.weight_diff[ind2]
            return True



n, m = list(map(int, input().split()))
query = []
for i in range(m):
    query.append(list(map(int, input().split())))
uf = weight_union_find(n)
for l, r, d in query:
    if not uf.unite(l-1, r-1, d):
        print("No")
        exit()
print("Yes")

Solution (Python):
class weight_union_find(object):
    def __init__(self, n):
        self.par = [-1 for i in range(n)]
        self.weight_diff = [0 for i in range(n)]
    
    def root(self, ind):
        if self.par[ind] < 0:
            return ind
        else:
            r = self.root(self.par[ind])
            self.weight_diff[ind] += self.weight_diff[self.par[ind]]
            self.par[ind] = r
            return r

    def unite(self, ind1, ind2, w):
        root1 = self.root(ind1)
        root2 = self.root(ind2)
        if root1 == root2:
            
            
            if -(self.weight_diff[ind1] - self.weight_diff[ind2]) == w:
                return True
            else:
                return False
        else:
            
            if self.par[root1] > self.par[root2]:
                root1, root2 = root2, root1
                ind1, ind2 = ind2, ind1
                w *= -1
            self.par[root1] += self.par[root2]
            self.par[root2] = root1
            self.weight_diff[root2] = w + self.weight_diff[ind1] - self.weight_diff[ind2]
            return True



n, m = list(map(int, input().split()))
query = []
for i in range(m):
    query.append(list(map(int, input().split())))
uf = weight_union_find(n)
for l, r, d in query:
    if not uf.unite(l-1, r-1, d):
        print("No")
        exit()
print("Yes")

Solution (Python):
n, m = list(map(int, input().split()))

graph = [[] for i in range(n)]

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



def func():
    x = [None for i in range(n)]
    for i in range(n):
        if x[i] == None:
            x[i] = 0
            q = [i]
        while q:
            j = q.pop()
            for k, d in graph[j]:
                if x[k] == None:
                    q.append(k)
                    x[k] = x[j] + d
                elif x[k] != x[j] + d:
                    return False
    return True

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

Solution (Python):

N, M = map(int, input().split())
Info = [list(map(int, input().split())) for i in range(M)]

Group = [[i] for i in range(N+1)]  
Distance = [[i, 0] for i in range(N+1)]  

for info in Info:
    l, r, d = info
    lp, rp = Distance[l][0], Distance[r][0]
    lpd, rpd = Distance[l][1], Distance[r][1]

    if lp != rp:
        if len(Group[lp]) > len(Group[rp]):
            Group[lp] += Group[rp]
            for h in Group[rp]:
                Distance[h][0] = lp
                Distance[h][1] += d + lpd - rpd
        else:
            Group[rp] += Group[lp]
            for h in Group[lp]:
                Distance[h][0] = rp
                Distance[h][1] -= d + lpd - rpd
    else:
        if rpd - lpd != d:
            print("No")
            exit()

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))
q = deque()

x = [None] * N


def _BFS(start):
    q.append(start)
    while len(q) != 0:
        p = q.popleft()
        for index, d in G[p]:
            if x[index] is None:
                x[index] = x[p] + d
                q.append(index)
            elif x[index] != x[p] + d:
                return False
    return True


def BFS():
    for i in range(N):
        if x[i] is None:
            x[i] = 0
            if not _BFS(i):
                return "No"
    return "Yes"


print(BFS())

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


class WeightedUnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.diff_weight = [0 for i in range(n)]

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

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

    def union(self, x, y, w):
        w += self.weight(x)
        w -= self.weight(y)
        x = self.find(x)
        y = self.find(y)
        if x != y:
            self.par[y] = x
            self.diff_weight[y] = w

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

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


uf = WeightedUnionFind(N)
ans = 'Yes'
for _ in range(M):
    L, R, D = map(int, input().split())
    L -= 1
    R -= 1
    if uf.is_same(L, R):
        if uf.diff(L, R) != D:
            ans = 'No'
            break
    else:
        uf.union(L, R, D)
print(ans)

Solution (Python):
n,m = (int(i) for i in input().split())
y,z,ans = [[] for i in range(n+1)],[None for i in range(n+1)],"Yes"
for num in range(m):
	i,j,k = (int(i) for i in input().split())
	y[i].append([j,k])
	y[j].append([i,-k])
for i in range(1,n+1):
	if z[i] == None:
		z[i],q = 0,[i]
		while q:
			p = q.pop()
			for j,k in y[p]:
				if z[j] == None:
					q.append(j)
					z[j] = z[p]+k
for i in range(1,n+1):
	for j,k in y[i]:
		if z[i]+k != z[j]: ans = "No"
print(ans)

Solution (Python):
class WeightUnionfindtree:
    def __init__(self,number):
        self.par = [i for i in range(number)]
        self.rank = [0]*(number)
        self.weight=[0]*(number)

    def find(self,x):
        if self.par[x] ==x:
            return x
        else:
            r = self.find(self.par[x])
            self.weight[x]+=self.weight[self.par[x]]
            self.par[x]=r
            return self.par[x]
        
    def weighted(self,x):
        self.find(x)
        return self.weight[x]
    
    def union(self,x,y,w):
        w += self.weighted(x)
        w -= self.weighted(y)
        px = self.find(x)
        py = self.find(y)
        if px == py:
            return 
        if self.rank[px]<self.rank[py]:
            self.par[px]=py
            self.weight[px]=-w
        else:
            self.par[py]=px
            self.weight[py] = w
        if self.rank[px]==self.rank[py]:
            self.rank[px] +=1
    
    def connect(self,x,y):
        return self.find(x)==self.find(y)
    
    def diff(self,x,y):
        return self.weighted(y)-self.weighted(x)
    
N,M = map(int,input().split())
Tree = WeightUnionfindtree(N)
ans = 'Yes'
for i in range(M):
    L,R,D = map(int,input().split())
    if Tree.connect(L-1,R-1):
        if Tree.diff(L-1,R-1)!=D:
            ans = 'No'
    else:
        Tree.union(L-1,R-1,D)
print(ans)

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

parent = [i for i in range(N+1)]
distance = [0 for i in range(N+1)]
depth = [1 for i in range(N+1)]

def root(x):
    if x == parent[x]:
        return x
    else:
        return root(parent[x])

def to_root(x):
    if x == parent[x]:
        return 0
    else:
        return distance[x] + to_root(parent[x])

for _ in range(M):
    L, R, D = map(int, input().split())
    
    
    
    if root(L) == root(R):
        l = to_root(L)
        r = to_root(R)
        
        
        if D != r-l:
            
            
            print("No")
            exit()
    else:
        rootL = root(L)
        rootR = root(R)
        if depth[rootL] < depth[rootR]:
            L,R = R,L
            D = -D
        rootL = root(L)
        rootR = root(R)
        parent[rootR] = rootL
        distance[rootR] = -to_root(R)+to_root(L)+D
        depth[rootL] = max(rootL, depth[rootR]+1)
print("Yes")

Solution (Python):
n,m = map(int, input().split())

g = [[] for _ in range(n+1)]
cood= [None for _ in range(n+1)]


def dfs(start):
    if cood[start] != None:
        return True
    stack = [start]
    cood[start] = 0
    while stack:
        v = stack.pop()
        for to, dist in g[v]:
            if cood[to] == None:
                stack.append(to)
                cood[to] = cood[v] + dist
            elif cood[v] + dist != cood[to]:
                return False
    return True

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

flag = True
for i in range(1,n+1):
    if not dfs(i):
        flag = False
if flag:
    print('Yes')
else:
    print('No')

Solution (Python):
n,m = map(int, input().split())
g = [[] for _ in range(0,n)]
x = [None] * n
ans = "Yes"
for i in range(0,m):
    L,R,D = map(int, input().split())
    g[L-1].append((R-1,D))
    g[R-1].append((L-1,-D))
for i in range(0,n):
    if x[i] is not None:
        continue
    x[i] = 0
    q = [i]
    while len(q) > 0:
        qq = q.pop()
        for r,d in g[qq]:
            if x[r] is None:
                q.append(r)
                x[r] = x[qq] + d
for i in range(0,n):
    for r,d in g[i]:
        if x[i] + d != x[r]:
            ans = "No"
            break
print(ans)

Solution (Python):
import queue,sys

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

G={}
LRD=[]
for i in range(1,N+1):
    G[i]={}
for i in range(M):
    l,r,d=map(int,input().split())
    LRD.append((l,r,d))
    G[l][r]=d
    G[r][l]=-d
if M==0:
    print("Yes")
    sys.exit()
notvisit=set(range(1,N+1))
Q=queue.Queue()
x={}
while notvisit:
    current=notvisit.pop()
    Q.put(current)
    x[current]=0
    while Q.qsize():
        nex=Q.get()
        for k,v in G[nex].items():
            if k in x:
                if x[k]!= x[nex]+G[nex][k]:
                    print("No")
                    sys.exit()
            else:
                x[k]=x[nex]+G[nex][k]
                Q.put(k)
                notvisit.remove(k)
print("Yes")

Solution (Python):
def solve():
    n, m = map(int, raw_input().split())
    edge = {v:[] for v in range(1,n+1)}
    dist = {}
    for i in range(m):
        l, r, d = map(int, raw_input().split())
        edge[l].append(r)
        edge[r].append(l)
        dist[l,r] = d
        dist[r,l] = -d
    return "Yes" if ok(edge, dist, n) else "No"

def ok(edge, dist, n):
    used = [False] * (n+1)
    used[0] = True
    path = {}
    for s in range(1, n+1):
        if used[s]:
            continue
        que = [s]
        path[s, s] = 0
        used[s] = True
        while que:
            u = que.pop()
            for v in edge[u]:
                d = path[s,u] + dist[u,v]
                if not used[v]:
                    path[s,v] = d
                    que.append(v)
                    used[v] = True
                elif d != path[s,v]:
                    return False
    return True

print solve()

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]

def main():
    n, m = map(int, input().split())
    wuf = WeightedUnionFind(n)
    for _ in range(m):
        l, r, d = map(int, input().split())
        if not wuf.same(l, r):
            wuf.union(l, r, d)
        else:
            if wuf.diff(l, r) != d:
                print('No')
                return
    print('Yes')

if __name__ == '__main__':
    main()

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]

def main():
    n, m = map(int, input().split())
    wuf = WeightedUnionFind(n)
    for _ in range(m):
        l, r, d = map(int, input().split())
        if not wuf.same(l, r):
            wuf.union(l, r, d)
        else:
            if wuf.diff(l, r) != d:
                print('No')
                return
    print('Yes')

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
import sys

def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [N, M] = [int(input_raw[0]),int(input_raw[1])]
    adj_list = {}
    for i in range(M):
        input_raw = read_func().strip().split()
        [L, R, D] = [int(input_raw[0]),int(input_raw[1]),int(input_raw[2])]
        if  L not in adj_list :
            adj_list[L] = [(R, D)]
        else:
            adj_list[L].append((R, D))
        if R not in adj_list :
            adj_list[R] = [(L, -D)]
        else:
            adj_list[R].append((L, -D))


    node_list = deque([])
    done_set = {}
    is_ok = True
    for L in adj_list:
        if is_ok == False:
            break
        if L not in done_set:
            node_list.append(L)
            done_set[L] = 0

            while 1:
                if len(node_list) <= 0:
                    break
                nd = node_list.popleft()
                for adj in adj_list[nd]:

                    if adj[0] not in done_set:
                        node_list.append(adj[0])
                        done_set[adj[0]] = done_set[nd] + adj[1]
                    else:
                        if(done_set[adj[0]] != done_set[nd] + adj[1]):
                            is_ok = False
                            break;

    if is_ok == True:
        print "Yes"
    else:
        print "No"







if __name__ == '__main__':
    main()

Solution (Python):
import sys

sys.setrecursionlimit(200002)


def dfs(start, edges, nodes):
    for adj_node, distance in edges[start].items():
        
        if nodes[adj_node] is None:
            nodes[adj_node] = nodes[start] + distance
            
            
            if not dfs(adj_node, edges, nodes):
                return False
        
        else:
            if nodes[adj_node] - nodes[start] != distance:
                return False

    return True


if __name__ == '__main__':
    N, M = map(int, input().split())
    if M == 0:
        print("Yes")
        exit(0)

    Ls, Rs, Ds = zip(*[list(map(int, input().split())) for _ in range(M)])

    
    
    
    

    edges = {i: dict() for i in range(N)}

    for L, R, D in zip(Ls, Rs, Ds):
        edges[L - 1][R - 1] = D
        edges[R - 1][L - 1] = -D

    nodes = [None] * N

    valid_list = []
    for start in range(N):
        if nodes[start] is None:
            nodes[start] = 0
            
            valid_list.append(dfs(start, edges, nodes))

    if all(valid_list):
        print("Yes")
    else:
        print("No")

Solution (Python):
n,m=map(int,input().split())
graph=[[] for i in range(n+1) ]
dist=[None for i in range(n+1)]
dist[0]=0
result=[True]

for i in range(m):
    l,r,d=(int(i) for i in input().split())
    graph[l].append((r,-d))
    graph[r].append((l,d))
def haba(i):
    if dist[i]== None:
        stack=[]
        dist[i]=0
        stack.append(i)
        while len(stack)!=0 :
            l=stack.pop()
            for r,d in graph[l]:
                b=dist[l]+d
                if dist[r]==None :
                    dist[r]=b
                    stack.append(r)
                elif dist[r]!=b:
                     result[0]=False
                     return
        return 
    else:
        return 

for i in range(n+1):
    haba(i)
if result[0]:
    print('Yes')
else:
    print('No')