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
readline = sys.stdin.readline

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

    def find(self, x):
        if self.parents[x] == x:
            return x
        else:
            y = self.find(self.parents[x])
            
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[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.parents[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.parents[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, readline().rstrip().split())    
    uf = WeightedUnionFind(N)

    for _ in range(M):
        l, r, d = map(int, readline().rstrip().split())
        l -= 1
        r -= 1
        if uf.same(l, r):
            if uf.diff(l, r) != d:
                print('No')
                return

        uf.union(l, r, d)
    
    print('Yes')

if __name__ == '__main__':
    main()

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

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

    def find(self, x):
        if self.parents[x] == x:
            return x
        else:
            y = self.find(self.parents[x])
            
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[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.parents[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.parents[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, readline().rstrip().split())    
    uf = WeightedUnionFind(N)

    for _ in range(M):
        l, r, d = map(int, readline().rstrip().split())
        l -= 1
        r -= 1
        if uf.same(l, r):
            if uf.diff(l, r) != d:
                print('No')
                return

        uf.union(l, r, d)
    
    print('Yes')

if __name__ == '__main__':
    main()

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

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

    
    def find(self, x):
        if self.parents[x] == x:
            return x
        else:
            y = self.find(self.parents[x])
            
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[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.parents[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        
        else:
            self.parents[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, readline().rstrip().split())    
    uf = WeightedUnionFind(N)

    for _ in range(M):
        l, r, d = map(int, readline().rstrip().split())
        l -= 1
        r -= 1
        if uf.same(l, r):
            if uf.diff(l, r) != d:
                print('No')
                return

        uf.union(l, r, d)
    
    print('Yes')

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
import sys

input = sys.stdin.readline

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

pos = {}

def bfs(cur, pre, p):
    stack = deque([(cur, pre, p)])
    while stack:
        cur, pre, p = stack.popleft()
        if cur in pos:
            if p != pos[cur]:
                print('No')
                sys.exit()
        else:
            pos[cur] = p

            for e, d in E[cur]:
                if e != pre:
                    stack.append([e, cur, p + d])

for i in range(n):
    if i in pos:
        continue
    bfs(i, -1, 0)

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())
    l -= 1
    r -= 1
    G[l].append([r, d])
    G[r].append([l, -d])
INF = float('inf')
dist = [INF]*N
seen = [False]*N
q = deque([])
for s in range(N):
    if dist[s] != INF:
        continue
    q.append([s,0])
    while len(q) != 0:
        p = q.popleft()
        if seen[p[0]] and dist[p[0]] != p[1]:
            print('No')
            exit()
        elif seen[p[0]] and dist[p[0]] == p[1]:
            continue
        else:
            dist[p[0]] = p[1]
            seen[p[0]] = True
            for np in G[p[0]]:
                q.append([np[0], p[1] + np[1]])
print('Yes')

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count




N,M = IL()
graph = [[] for i in range(N)]
for _ in range(M):
  l,r,d = IL()
  graph[l-1].append((r-1,d))
  graph[r-1].append((l-1,-d))
  
q = deque([i for i in range(N)])
pos = [None for i in range(N)]
while q:
  x = q.popleft()
  if pos[x] == None:
    pos[x] = 0
  for y,d in graph[x]:
    if pos[y] == None:
      pos[y] = pos[x] + d
      q.appendleft(y)
      continue
    if pos[y] != pos[x] + d:
      print("No")
      exit()

print("Yes")

Solution (Python):
import sys
sys.setrecursionlimit(10**5)
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rnk = [0]*(n+1)
        self.weight = [0]*(n+1)
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            r = self.Find_Root(self.root[x])
            self.weight[x] += self.weight[self.root[x]]
            self.root[x] = r
            return r
    def GetWeight(self, x):
        self.Find_Root(x)
        return self.weight[x]
    def Unite(self, x, y, w):
        w += self.GetWeight(x)
        w -= self.GetWeight(y)
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        if(x == y):
            return False
        if self.rnk[x] < self.rnk[y]:
            x, y = y, x
            w = -w
        if self.rnk[x] == self.rnk[y]:
            self.rnk[x] += 1
        self.root[y] = x
        self.weight[y] = w
        return True
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)
    def Count(self, x):
        return -self.root[self.Find_Root(x)]
    def Diff(self, x, y):
        return self.GetWeight(y) - self.GetWeight(x)

N, M = map(int, input().split())
uf = UnionFind(N+1)
for _ in range(M):
    l, r, d = map(int, input().split())
    if not uf.isSameGroup(l, r):
        uf.Unite(l, r, d)
    else:
        if uf.Diff(l, r) != d:
            print('No')
            exit()

print('Yes')

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

no_seen=set(range(n))
inf=float('inf')
dst=[inf]*n
while no_seen:
  todo=[[0,no_seen.pop()]]
  
  while todo:
    d,t=todo.pop()
    no_seen.discard(t)
    l=g[t]
    for di,ti in l:
      if dst[ti]!=inf and dst[ti]!=d+di:
        print('No')
        exit()
      elif dst[ti]!=inf and dst[ti]==d+di:
        pass
      else:
        todo.append([d+di,ti])
        dst[ti]=d+di

print('Yes')

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

no_seen=set(range(n))
inf=float('inf')
dst=[inf]*n
while no_seen:
  todo=[[0,no_seen.pop()]]
  
  while todo:
    d,t=todo.pop()
    no_seen.discard(t)
    l=g[t]
    for di,ti in l:
      if dst[ti]!=inf and dst[ti]!=d+di:
        print('No')
        exit()
      elif dst[ti]!=inf and dst[ti]==d+di:
        pass
      else:
        todo.append([d+di,ti])
        dst[ti]=d+di

print('Yes')

Solution (Python):
from collections import deque

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

max_int = 10 ** 10
point = [None for _ in range(n)]

for v in range(n):
    Q = deque()
    if point[v] is not None:
        continue
    Q.extend(graph[v])
    while Q:
        next_v, v, d = Q.popleft()
        if point[v] is None:
            point[v] = 0
        if point[next_v] is not None:
            if point[next_v] != point[v] + d:
                print('No')
                exit()
            else:
                continue
        point[next_v] = point[v] + d
        Q.extend(graph[next_v])
print('Yes')

Solution (Python):
def resolve():
    N, M = list(map(int, input().split()))
    LRD = [list(map(int, input().split())) for _ in range(M)]
    adj_list = [[] for _ in range(N)]
    for lrd in LRD:
        l, r, d = lrd
        adj_list[l-1].append((l-1, r-1, d))
        adj_list[r-1].append((r-1, l-1, -d))
    
    X = [None]*N
    import collections

    for i in range(N):
        if X[i] is not None:
            continue
        q = collections.deque(adj_list[i])
        X[i] = 0
        while q:
            src, nxt, d = q.pop()
            if X[nxt] is not None:
                if X[nxt] != X[src] + d:
                    print("No")
                    return
            else:
                X[nxt] = X[src] + d
                q.extend(adj_list[nxt])
    print("Yes")

    


if '__main__' == __name__:
    resolve()

Solution (Python):
import sys
from typing import List, Optional

sys.setrecursionlimit(1000000)

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

g = [[] for _ in range(N)]

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


def ok(cur: int, ds: int, dists: List[Optional[int]]) -> bool:
    dists[cur] = ds

    flag = True
    for nx, d in g[cur]:
        if dists[nx] != None:
            flag &= dists[nx] - dists[cur] == d
        elif flag:
            flag &= ok(nx, ds + d, dists)

    return flag


dists = [None] * N
ans = True
for i in range(N):
    if ans and dists[i] == None:
        ans &= ok(i, 0, dists)

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

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

if m <=1:
    print("Yes")
    exit()

from collections import defaultdict
V = defaultdict(list)
 
for _ in range(m):
    a, b,c = map(int, input().split())
    V[a].append([b,c])
    V[b].append([a,-c])

inf  = float("inf") 
dist = [inf]*(n+1)

def dfs(source):
    dist[source] = 0
    q = [source]
    while q:
        a = q.pop()
        for b in V[a]:
            if dist[b[0]]!=inf:
                if dist[b[0]] != dist[a] +b[1]:
                    print("No")
                    exit()
            else:
                dist[b[0]] = dist[a] + b[1]
                q.append(b[0])

for i in range(n):
    if dist[i] ==inf:
        dfs(i)

print("Yes")

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import defaultdict, deque
    n, m = map(int, readline().split())
    edge = defaultdict(list)

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

    visited = [False] * (n + 1)

    for x in range(1, n + 1):
        costs = dict()
        if not visited[x]:
            costs[x] = 0
            que = deque()
            que.append((x, 0))
            while que:
                u, cost = que.popleft()
                visited[u] = True
                while edge[u]:
                    v, w = edge[u].pop()
                    if v in costs:
                        if costs[v] != cost + w:
                            print("No")
                            sys.exit()
                    costs[v] = cost + w
                    que.append((v, cost + w))

    print("Yes")


if __name__ == '__main__':
    main()

Solution (Python):
n, m = map(int, input().split())
edges = [[] for i in range(n)]
for i in range(m):
    li, ri, di = map(int, input().split())
    li, ri = li-1, ri-1
    edges[li].append((ri, di))
    edges[ri].append((li, -di))

coordinate = [None for i in range(n)]
for i in range(n):
    if coordinate[i] == None:
        coordinate[i] = 0
    else:
        continue
    nodes = [i]
    while nodes != []:
        next_nodes = []
        for node in nodes:
            edge = edges[node]
            start = coordinate[node]
            for end, dist in edge:
                if coordinate[end] == None:
                    coordinate[end] = start + dist
                    next_nodes.append(end)
                else:
                    if coordinate[end] != start + dist:
                        print('No')
                        exit()
        nodes = next_nodes[:]
print('Yes')

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

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

def dfs(now):
    for nxt,d in G[now]:
        if pos[nxt] == INF:
            pos[nxt] = pos[now]+d
            dfs(nxt)
        elif pos[nxt] != pos[now]+d:
            print("No")
            exit()

for i in range(n):
    if pos[i] == INF:
        pos[i] = 0
        dfs(i)
print("Yes")

Solution (Python):
def getN():
    return int(input())


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


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


from collections import defaultdict, deque, Counter
from sys import exit
import math
import copy
from bisect import bisect_left, bisect_right
from heapq import *
import sys


INF = 10 ** 17
MOD = 1000000007

from fractions import *


def inverse(f):
    
    return 1 / f


def combmod(n, k, mod=MOD):
    ret = 1
    for i in range(n - k + 1, n + 1):
        ret *= i
        ret %= mod

    for i in range(1, k + 1):
        ret *= pow(i, mod - 2, mod)
        ret %= mod

    return ret

MOD = 10 ** 9 + 7
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 solve():
    n, m = getList()
    uf = WeightedUnionFind(n+1)
    for i in range(m):
        l, r, d = getList()
        if uf.same(l, r):
            if abs(uf.weight[l] - uf.weight[r]) != d:
                print("No")
                return
        else:
            uf.union(l, r, d)
    print("Yes")
def main():
    n = getN()
    for _ in range(n):
        solve()


if __name__ == "__main__":
    solve()

Solution (Python):
def getN():
    return int(input())


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


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


from collections import defaultdict, deque, Counter
from sys import exit
import math
import copy
from bisect import bisect_left, bisect_right
from heapq import *
import sys


INF = 10 ** 17
MOD = 1000000007

from fractions import *


def inverse(f):
    
    return 1 / f


def combmod(n, k, mod=MOD):
    ret = 1
    for i in range(n - k + 1, n + 1):
        ret *= i
        ret %= mod

    for i in range(1, k + 1):
        ret *= pow(i, mod - 2, mod)
        ret %= mod

    return ret

MOD = 10 ** 9 + 7
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 solve():
    n, m = getList()
    uf = WeightedUnionFind(n+1)
    for i in range(m):
        l, r, d = getList()
        if uf.same(l, r):
            if abs(uf.weight[l] - uf.weight[r]) != d:
                print("No")
                return
        else:
            uf.union(l, r, d)
    print("Yes")
def main():
    n = getN()
    for _ in range(n):
        solve()


if __name__ == "__main__":
    solve()

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return

    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
    val = [inf] * N
    global_visited = set()

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        return False
                val[next_v] = val[v] + d
                visited.add(next_v)
                global_visited.add(next_v)
                q.append(next_v)
        return True

    can = True
    for i in range(N):
        if i in global_visited:
            continue
        v = i
        val[v] = 0
        if not bfs(v):
            can = False
            break

    if can:
        print("Yes")
    else:
        print("No")
    return


main()

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    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])

    def dfs(v, p):
        for u, d in tree[v]:
            if u == p:
                continue
            else:
                if dist[u] == f_inf:
                    dist[u] = dist[v] + d
                    dfs(u, v)
                else:
                    if dist[u] != dist[v] + d:
                        print("No")
                        exit()

    dist = [f_inf] * n
    for i in range(n):
        if dist[i] == f_inf:
            dist[i] = 0
            dfs(i, -1)

    print("Yes")


if __name__ == '__main__':
    resolve()

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

def bfs(s):
    visited[s] = True
    q = deque([s])
    
    while q:
        v = q.popleft()
        
        for nv, w in G[v]:
            if not visited[nv]:
                visited[nv] = True
                dist[nv] = dist[v]+w
                q.append(nv)
            else:
                if dist[nv]!=dist[v]+w:
                    return False
    
    return True

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

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

visited = [False]*N
dist = [0]*N
flag = True

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

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

Solution (Python):
n,m=map(int,input().split())
edge=[[]for _ in range(n)]
for _ in range(m):
  l,r,d=map(int,input().split())
  l-=1
  r-=1
  edge[l].append((r,d))
  edge[r].append((l,-d))
ans=[10**20]*n
inf=10**20
for i in range(n):
  if ans[i]!=inf:continue
  stack=[i]
  visited={i}
  ans[i]=0
  for node in stack:
    for mode,d in edge[node]:
      if ans[node]+d!=ans[mode]!=inf:exit(print("No"))
      if mode in visited:continue
      visited.add(mode)
      stack.append(mode)
      if ans[mode]==inf:
        ans[mode]=ans[node]+d
      else:
        if ans[node]+d!=ans[mode]:exit(print("No"))
print("Yes")

Solution (Python):
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    N, M = map(int, input().split())
    E = [[] for _ in range(N)]
    for _ in range(M):
        l, r, d = map(int, input().split())
        E[l-1].append((r - 1, d))
        E[r-1].append((l - 1, -d))
    Pos = [10 ** 20] * N
    q = deque()
    flag = True
    for i in range(N):
        if Pos[i] == 10 ** 20:
            q.append((i, 0))
            minX, maxX = 0, 0
            while q:
                x, p = q.popleft()
                if Pos[x] == 10 ** 20:
                    minX = min(minX, p)
                    maxX = max(maxX, p)
                    Pos[x] = p
                    for ne, d in E[x]: q.append((ne, p + d))
                elif Pos[x] == p: continue
                else:
                    flag = False
                    break
            else:
                if maxX - minX <= 10 ** 9: continue
                else: flag = False
            if not flag:
                print("No")
                break
    else: print("Yes")
    
            
    return 0

if __name__ == "__main__":
    solve()

Solution (Python):
from sys import stdin
from collections import deque
def main():
    
    readline=stdin.readline
    n,m=map(int,readline().split())
    G=[[] for _ in range(n+1)]
    for i in range(m):
        l,r,d=map(int,readline().split())
        G[l].append((r,d))
        G[r].append((l,-d))

    flags=[False]*(n+1)
    flags[0]=True
    inf=10**10
    x=[-inf]*(n+1)
    q=deque([])
    ans=True
    for i in range(1,n+1):
        if ans==False: break
        if flags[i]==False:
            x[i]=0
            flags[i]=True
            q.append(i)
            while len(q)>0:
                now=q.popleft()
                for t in G[now]:
                    nex=t[0]
                    cost=t[1]
                    if x[nex]==-inf:
                        x[nex]=x[now]+cost
                    else:
                        if x[nex]!=x[now]+cost:
                            ans=False
                            break
                    if flags[nex]==False:
                        flags[nex]=True
                        q.append(nex)

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

if __name__ == "__main__":
    main()

Solution (Python):
from sys import stdin
from collections import deque
def main():
    
    readline=stdin.readline
    n,m=map(int,readline().split())
    G=[[] for _ in range(n+1)]
    for i in range(m):
        l,r,d=map(int,readline().split())
        G[l].append((r,d))
        G[r].append((l,-d))

    flags=[False]*(n+1)
    flags[0]=True
    inf=10**10
    x=[-inf]*(n+1)
    q=deque([])
    ans=True
    for i in range(1,n+1):
        if ans==False: break
        if flags[i]==False:
            x[i]=0
            flags[i]=True
            q.append(i)
            while len(q)>0:
                now=q.popleft()
                for t in G[now]:
                    nex=t[0]
                    cost=t[1]
                    if x[nex]==-inf:
                        x[nex]=x[now]+cost
                    else:
                        if x[nex]!=x[now]+cost:
                            ans=False
                            break
                    if flags[nex]==False:
                        flags[nex]=True
                        q.append(nex)

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

if __name__ == "__main__":
    main()