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):
MOD = 10 ** 9 + 7
INF = 10 ** 10
import sys
sys.setrecursionlimit(100000000)
dy = (-1,0,1,0)
dx = (0,1,0,-1)

class WeightedUnionFind():

    def __init__(self,N):
        self.N = N
        self.parents = [-1] * self.N
        self.diff_weight = [0] * self.N
    
    def find(self,x):
        if self.parents[x] < 0:
            return x
        else:
            p = self.find(self.parents[x])
            self.diff_weight[x] += self.diff_weight[self.parents[x]]
            self.parents[x] = p
            return p
    
    def weight(self,x):
        self.find(x)
        return self.diff_weight[x]
    
    def diff(self,x,y):
        if self.find(x) == self.find(y):
            return self.weight(y) - self.weight(x)
        else:
            return 1e10

    def unite(self,x,y,w):
        w += self.weight(x)
        w -= self.weight(y)

        x = self.find(x)
        y = self.find(y)
        if x == y:
            if self.diff(x,y) == w:
                return True
            else:
                return False

        if self.parents[x] > self.parents[y]:
            x,y = y,x
            w *= -1
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.diff_weight[y] = w
        return True
    
    def size(self,x):
        return - self.parents[self.find(x)]

def main():
    n,m = map(int,input().split())
    uf = WeightedUnionFind(n)
    flag = True
    for _ in range(m):
        l,r,d = map(int,input().split())
        l -= 1
        r -= 1
        if uf.unite(l,r,d):
            continue
        else:
            flag = False
            break
    print('Yes' if flag else 'No')
if __name__ == '__main__':
    main()

Solution (Python):
import sys


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


sys.setrecursionlimit(20000000)


class WeightedUnionFind:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.parent = [i for i in range(n_nodes)]
        self.rank = [1] * n_nodes
        self.size = [1] * n_nodes
        
        self.weight = [0] * n_nodes

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

    def unite(self, x, y, w):
        px = self.find(x)
        py = self.find(y)
        if px == py:
            return
        if self.rank[px] > self.rank[py]:
            self.parent[py] = px
            self.size[px] += self.size[py]
            self.weight[py] = -w - self.weight[y] + self.weight[x]
        else:
            self.parent[px] = py
            self.size[py] += self.size[px]
            self.weight[px] = w - self.weight[x] + self.weight[y]
            if self.rank[px] == self.rank[py]:
                self.rank[py] += 1

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

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

    def get_parent_list(self):
        return [i for i in range(self.n_nodes) if self.find(i) == i]

    def get_n_groups(self):
        return len(self.get_parent_list())

    def get_members(self, x):
        parent = self.find(x)
        return [i for i in range(self.n_nodes) if self.find(i) == parent]

    def get_members_dict(self):
        return {par: self.get_members(par) for par in self.get_parent_list()}


def main():
    N, M = map(int, input().split())
    Tree = WeightedUnionFind(N)
    for _ in range(M):
        L, R, D = map(int, input().split())
        if Tree.check(L - 1, R - 1):
            if Tree.diff(L - 1, R - 1) == D:
                continue
            else:
                print("No")
                return
        else:
            Tree.unite(L - 1, R - 1, D)
    print("Yes")


if __name__ == "__main__":
    main()

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

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


seen = ['yet' for _ in range(n)]
todo = []
for i in range(n):
    if seen[i] != 'yet':
        continue
    seen[i] = 0
    todo.append(i)
    while todo != []:
        j = todo.pop(-1)
        for k in range(len(l[j])):
            if seen[l[j][k]] != 'yet':
                if seen[j] + d[j][k] != seen[l[j][k]]:
                    print('No')
                    exit()
                continue
            seen[l[j][k]] = seen[j] + d[j][k]
            todo.append(l[j][k])
print('Yes')

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

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


seen = ['yet' for _ in range(n)]
todo = []
for i in range(n):
    if seen[i] != 'yet':
        continue
    seen[i] = 0
    todo.append(i)
    while todo != []:
        j = todo.pop(-1)
        for k in range(len(l[j])):
            if seen[l[j][k]] != 'yet':
                if seen[j] + d[j][k] != seen[l[j][k]]:
                    print('No')
                    exit()
                continue
            seen[l[j][k]] = seen[j] + d[j][k]
            todo.append(l[j][k])
print('Yes')

Solution (Python):
import sys
import io
import math
import string


sys.setrecursionlimit(100001)
def input():
    return sys.stdin.readline()[:-1]

def dfs(v):
    ret = True
    for u, d in es[v]:
        if x[u] == None:
            x[u] = x[v] + d
            ret = ret and dfs(u)
        elif x[u] != x[v] + d:
            return False
    return ret

N, M = map(int, input().split())
es = [[] for i in range(N+1)]
for i in range(M):
    L, R, D = map(int, input().split())
    es[L].append((R, D))
    es[R].append((L, -D))
x = [None for i in range(N+1)]
flag = True
for v in range(1, N+1):
    if x[v] == None:
        x[v] = 0
        if dfs(v) == False:
            flag = False
            break
if flag:
    print("Yes")
else:
    print("No")

Solution (Python):
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product

def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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=1):
        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=[list(map(int,input().split())) for i in range(m)]

uf=WeightedUnionFind(n)
for i in range(m):
    l,r,d=lrd[i]
    uf.union(l,r,d)
    
    

for i in range(m):
    l,r,d=lrd[i]
    if not uf.same(l,r):
        print("No")
        break
    if uf.diff(l,r)!=d:
        print("No")
        break
else:
    print("Yes")

Solution (Python):
import heapq
n, m = map(int, input().split())
inf = 10 ** 10
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))

dist = [inf for _ in range(n)]

def dfs(v):
    stack = [v]
    dist[v] = 0

    while stack:
        v = stack.pop()
        d = dist[v]
        for to, cost in edges[v]:
            if dist[to] != inf:
                if dist[to] != d + cost:
                    return False
            else:
                dist[to] = d + cost
                stack.append(to)

    return True

flg = True
for i in range(n):
    if dist[i] == inf:
        if dfs(i) == False:
            flg = False
            break

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

Solution (Python):
n, m = map(int, input().split())
inf = 10**10
G = [{} for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    G[l-1][r-1] = d
    G[r-1][l-1] = -d
V = [False for i in range(n)]
D = [inf for i in range(n)]
for i in range(n):
    if V[i]:
        continue
    
    Q = [i]
    D[i] = 0
    while Q:
        j = Q.pop()
        V[j] = True
        for k in G[j].keys():
            if not V[k]:
                Q.append(k)
            if D[k] == inf:
                D[k] = D[j]+G[j][k]
            elif D[k] != D[j]+G[j][k]:
                print('No')
                exit()
print('Yes')

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**5+1)
def dfs(p):
  for edge in g[p]:
    if x[edge[0]] is not None:
      if x[edge[0]]-x[p]!=edge[1]:
        print('No')
        exit()
    else:
      x[edge[0]]=x[p]+edge[1]
      dfs(edge[0])
n,m=map(int,input().split())
g=[[] for i in range(n)]
for i in range(m):
  u,v,c=map(int,input().split())
  g[u-1].append((v-1,c))
  g[v-1].append((u-1,-c))
x=[None]*n
for i in range(n):
  if x[i]==None:
    x[i]=0
    dfs(i)
print('Yes')

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

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

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

    def union(self, x, y, w):
        x_root = self.find(x)
        y_root = self.find(y)
        if x_root == y_root:
            return
        if self.rank[x_root] < self.rank[y_root]:
            self.parent[x_root] = y_root
            self.weight[x_root] = w - self.weight[x] + self.weight[y]
        else:
            self.parent[y_root] = x_root
            self.weight[y_root] = - w - self.weight[y] + self.weight[x]
            if self.rank[x_root] == self.rank[y_root]:
                self.rank[x_root] += 1

    def is_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 wuf.is_same(l, r):
            if wuf.diff(r, l) == d:
                continue
            else:
                print("No")
                sys.exit()
        else:
            wuf.union(r, l, d)
    print("Yes")

if __name__ == '__main__':
    main()

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

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

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

d = [None] * n
visited = [0] * n

for i in range(n):
    if visited[i] != 0:
        continue
    stack = [i]
    d[i] = 1
    while stack:
        u = stack.pop()
        visited[u] = 1
        for v, d_ in g[u] :
            if d[v] is None:
                d[v] = d[u] + d_
                stack.append(v)
            else:
                if d[v] != d[u] + d_ :
                    print("No")
                    sys.exit()
print("Yes")

Solution (Python):

from collections import deque
import sys
try:
    from typing import Deque, Dict, List, Tuple
except ImportError:
    pass
 
 
YESS = "Yes"  
NO = "No"  
 
 
def solve(N: int, M: int, L: "List[int]", R: "List[int]", D: "List[int]"):
    G = [[] for _ in range(N)]  
    for Li, Ri, Di in zip(L, R, D):
        Li -= 1
        Ri -= 1
        G[Li].append((Ri, Di))
        G[Ri].append((Li, -Di))
    pos = {}  
    for i in range(N):
        if i in pos:
            continue
        q = deque()  
        pos[i] = 0
        q.append(i)
        while q:
            s = q.popleft()
            for t, dst in G[s]:
                if t in pos:
                    if pos[t] != pos[s] + dst:
                        print(NO)
                        return
                    continue
                pos[t] = pos[s] + dst
                q.append(t)
    print(YESS)
 
 
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))
    solve(N, M, L, R, D)
 
 
if __name__ == '__main__':
    main()

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

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

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

d = [None] * n
visited = [0] * n

for i in range(n):
    if visited[i] != 0:
        continue
    stack = [i]
    d[i] = 1
    while stack:
        u = stack.pop()
        visited[u] = 1
        for v, d_ in g[u]:
            if d[v] is None:
                d[v] = d[u] + d_
                stack.append(v)
            else:
                if d[v] != d[u] + d_:
                    print("No")
                    sys.exit()
print("Yes")

Solution (Python):
n, m = map(int, input().split())
inf = 10**10
G = [{} for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    G[l-1][r-1] = d
    G[r-1][l-1] = -d
V = [False for i in range(n)]
D = [inf for i in range(n)]
for i in range(n):
    if V[i]:
        continue
    Q = [i]
    D[i] = 0
    while Q:
        j = Q.pop()
        V[j] = True
        for k in G[j].keys():
            if not V[k]:
                Q.append(k)
            if D[k] == inf:
                D[k] = D[j]+G[j][k]
            elif D[k] != D[j]+G[j][k]:
                print('No')
                exit()
print('Yes')

Solution (Python):

from collections import deque
import sys
try:
    from typing import Deque, Dict, List, Tuple
except ImportError:
    pass


YES = "Yes"  
NO = "No"  


def solve(N: int, M: int, L: "List[int]", R: "List[int]", D: "List[int]"):
    G = [[] for _ in range(N)]  
    for Li, Ri, Di in zip(L, R, D):
        Li -= 1
        Ri -= 1
        G[Li].append((Ri, Di))
        G[Ri].append((Li, -Di))
    pos = {}  
    for i in range(N):
        if i in pos:
            continue
        q = deque()  
        pos[i] = 0
        q.append(i)
        while q:
            s = q.popleft()
            for t, dst in G[s]:
                if t in pos:
                    if pos[t] != pos[s] + dst:
                        print(NO)
                        return
                    continue
                pos[t] = pos[s] + dst
                q.append(t)
    print(YES)


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))
    solve(N, M, L, R, D)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
n,m = map(int,input().split())

path = [[] for _ in range(n)]

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

pos = [None] * n

q = deque([0])
not_take = set(range(1,n))

ans = "Yes"

while q:
    
    a = q.popleft()
    if pos[a] is None:
        pos[a] = 0
    
    for b,dx in path[a]:
        
        if pos[b] is None:
            pos[b] = pos[a] + dx
            q.append(b)
            not_take.discard(b)
        elif pos[b] != pos[a] + dx:
            ans = "No"
            break
    if ans == "No": break
        
    if (not q) and (not_take != set()):
        q.append(not_take.pop())

if ans == "Yes" and max(pos) - min(pos) > 1e9:
    ans = "No"

print(ans)

Solution (Python):
import sys
from collections import deque

input = sys.stdin.readline

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

Nvisited = set(range(N))
pos = dict()


def dfs(v):
    D = deque()
    D.append(v)
    pos[v] = 0
    while D:
        x = D.pop()
        for y, d in T[x]:
            if y in Nvisited:
                pos[y] = pos[x] + d
                Nvisited.remove(y)
                D.append(y)
            elif pos[y] - pos[x] != d:
                print('No')
                sys.exit()


while Nvisited:
    dfs(Nvisited.pop())

print('Yes')

Solution (Python):
import sys
from collections import deque

input = sys.stdin.readline

N, M = map(int, input().split())
T = [set() for _ in range(N)]
for _ in range(M):
    l, r, d = map(int, input().split())
    T[l - 1].add((r - 1, d))
    T[r - 1].add((l - 1, -d))

Nvisited = set(range(N))
pos = dict()


def dfs(v):
    D = deque()
    D.append(v)
    pos[v] = 0
    while D:
        x = D.pop()
        for y, d in T[x]:
            if y in Nvisited:
                pos[y] = pos[x] + d
                Nvisited.remove(y)
                D.append(y)
            elif pos[y] - pos[x] != d:
                print('No')
                sys.exit()


while Nvisited:
    dfs(Nvisited.pop())

print('Yes')

Solution (Python):
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import permutations,combinations
from collections import defaultdict,Counter
from pprint import pprint

def myinput():
    return map(int,input().split())

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col):
    data.sort(key=lambda x:x[col],reverse=False)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m


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 = myinput()
lrd = [ list(myinput()) for _ in range(m) ]

wuf = WeightedUnionFind(n)

for i in range(m):
    l = lrd[i][0] - 1
    r = lrd[i][1] - 1
    d = lrd[i][2]
    if wuf.same(l,r):
        diff = wuf.diff(l,r)
        if d!=diff:
            print("No")
            exit()
        else:
            pass
    else:
        wuf.union(l,r,d)

print("Yes")
exit()

Solution (Python):

from collections import deque
import sys
try:
    from typing import Deque, Dict, List, Tuple
except ImportError:
    pass


YES = "Yes"  
NO = "No"  


def solve(N: int, M: int, L: "List[int]", R: "List[int]", D: "List[int]"):
    G = [[] for _ in range(N)]  
    for Li, Ri, Di in zip(L, R, D):
        Li -= 1
        Ri -= 1
        G[Li].append((Ri, Di))
        G[Ri].append((Li, -Di))
    pos = {}  
    for i in range(N):
        if i in pos:
            continue
        q = deque()  
        pos[i] = 0
        q.append(i)
        while q:
            s = q.popleft()
            for t, dst in G[s]:
                if t in pos:
                    if pos[t] != pos[s] + dst:
                        print(NO)
                        return
                    continue
                pos[t] = pos[s] + dst
                q.append(t)
    print(YES)


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))
    solve(N, M, L, R, D)


if __name__ == '__main__':
    main()

Solution (Python):
n,m=map(int,input().split())
lrd=[]
es=[[] for i in range(n)]
for i in range(m):
    l,r,d=map(int,input().split())
    lrd.append((l-1,r-1,d))
    es[l-1].append((d,r-1))
    es[r-1].append((-d,l-1))

from collections import deque
que=deque([])
dist=[float('inf')]*n

for i in range(n):
    if dist[i]==float('inf'):
        dist[i]=int(0)
        que.append(i)
        while que:
            p=que.popleft()
            for d, j in es[p]:
                if dist[j]==float('inf'):
                    dist[j]=int(dist[p]+d)
                    que.append(j)

for l,r,d in lrd:
    if dist[l]-dist[r]!=-d:
        print('No')
        exit()
print('Yes')

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby
    
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    

    inf = 10**17
    

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

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

    x = [inf]*n

    def bfs(v):
        if x[v]==inf:
            x[v] = 0
        d = deque([v])
        while d:
            v  = d.popleft()
            for nv, cost in adj[v]:
                if x[nv] == inf:
                    x[nv] = x[v] + cost
                    d.append(nv)
                else:
                    if x[nv] - x[v] != cost:
                        return False
        return True

    for v in range(n):
        if not bfs(v):
            print('No')
            exit()
    print('Yes')

if __name__ == '__main__':
    main()

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby
    
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    

    inf = 10**17
    

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

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

    x = [inf]*n

    def dfs(v):
        if x[v]==inf:
            x[v] = 0
        d = deque([v])
        while d:
            v  = d.popleft()
            for nv, cost in adj[v]:
                if x[nv] == inf:
                    x[nv] = x[v] + cost
                    d.append(nv)
                else:
                    if x[nv] - x[v] != cost:
                        return False
        return True


    for v in range(n):
        if not dfs(v):
            print('No')
            exit()
    print('Yes')


if __name__ == '__main__':
    main()

Solution (Python):



def Find(x, par, diff_weight):
    if par[x] < 0:
        return x
    else:
        px = Find(par[x], par, diff_weight)
        diff_weight[x] += diff_weight[par[x]]
        par[x] = px
        return px

def Unite(x, y, par, rank, diff_weight, w):
    w += diff_weight[x] - diff_weight[y]
    x = Find(x, par, diff_weight)
    y = Find(y, par, diff_weight)

    if x != y:
        if rank[x] < rank[y]:
            x, y =  y, x
            w = -w
        if rank[x] == rank[y]:
            rank[x] += 1
        par[x] += par[y]
        par[y] = x
        diff_weight[y] = w

def Same(x, y, par, diff_weight):
    return Find(x, par,diff_weight) == Find(y, par, diff_weight)

def Size(x, par, diff_weight):
    return -par[Find(x, par, diff_weight)]

def Weight(x, par, diff_weight):
    Find(x, par, diff_weight)
    return diff_weight[x]

def Diff(x, y, par, diff_weight):
    return Weight(y, par, diff_weight)  - Weight(x, par, diff_weight)

import sys
input = sys.stdin.readline

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

par = [-1]*n
rank = [0]*n
diff_weight = [0]*n
for i in range(m):
    l, r, d = map(int, input().split())
    l, r = l-1 ,r-1
    if not Same(l, r, par, diff_weight):
        Unite(l, r, par, rank, diff_weight, d)
    else:
        if d != Diff(l, r, par, diff_weight):
            print('No')
            exit()
print('Yes')

Solution (Python):
def main():
    n, m = map(int, input().split())
    g = [[] for i 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))
    dis = [0] * n
    visited = [False] * n
    stack = list(range(n))
    while len(stack):
        v = stack[-1]
        stack.pop()
        if visited[v]:
            continue
        visited[v] = True
        for u, d in g[v]:
            if not visited[u]:
                dis[u] = dis[v] + d
                stack.append(u)
    for v in range(n):
        for u, d in g[v]:
            if dis[v] + d != dis[u]:
                print('No')
                return
    print('Yes')


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

n, m = map(int, input().split())
tree = [[] for _ in range(n)]
for _ in range(m):
    L, R, D = map(int, input().split())
    tree[L - 1].append((R - 1, D))
    tree[R - 1].append((L - 1, -D))
visited = [None for _ in range(n)]


def bfs(u):
    q = deque([[u, 0]])
    visited[u] = 0
    while q:
        u, dist = q.popleft()
        for next_u, d in tree[u]:
            next_x = dist + d
            if visited[next_u] is None:
                visited[next_u] = next_x
                q.append([next_u, next_x])
            elif visited[next_u] == next_x:
                continue
            else:
                print("No")
                exit()


for i in range(n):
    if visited[i] is None:
        bfs(i)
else:
    print('Yes')

Solution (Python):
N, M = map(int, input().split())
edges = [[] for _ in range(N)]

for _ in range(M):
    fr, to, dist = map(int, input().split())
    fr -= 1
    to -= 1
    edges[fr].append((to, dist))
    edges[to].append((fr, -dist))

INF = 10**18
minDist = [INF] * N
for s in range(N):
    if minDist[s] < INF:
        continue
    st = [s]
    minDist[s] = 0
    while st:
        now = st.pop()
        dist = minDist[now]
        for to, d in edges[now]:
            if minDist[to] == INF:
                minDist[to] = dist + d
                st.append(to)
                continue
            if minDist[to] != dist + d:
                print('No')
                exit()
print('Yes')

Solution (Python):
import sys
def main():
    input = sys.stdin.readline
    N,M=map(int, input().split())
    G=[[] for _ in range(N)]
    inn=[0]*N
    for _ in range(M):
        l,r,d=map(int, input().split())
        l,r=l-1,r-1
        G[l].append((r, d))
        inn[r] += 1

    ds = [-1] * N
    for i in range(N):
        if inn[i]: continue
        ds[i] = 0
        stk = [(i, 0)]
        while stk:
            v, d = stk.pop()
            for to, dt in G[v]:
                if ds[to] != -1:
                    if ds[to] != d+dt:
                        print('No')
                        return
                    continue
                ds[to] = d+dt
                stk.append((to, d+dt))

    if any([d == -1 for d in ds]):
        print('No')
        return
    print('Yes')

if __name__ == '__main__':
    main()