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
sys.setrecursionlimit(200002)
N, M = map(int, input().split())
xrd = [[] for i in range(N)]
x = [None]*N


def check(s):
    global xrd,x
    for t, d in xrd[s]:
        if x[t] is None:
            x[t] = x[s] + d
            check(t)
        else:
            if x[t] != x[s] + d:
                print("No")
                exit()


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

for i in range(N):
    if x[i] is None:
        x[i] = 0
        check(i)


print("Yes")

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

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

def fail():
    print("No")
    exit()

def dfs(s):
    global x, G
    for t, d in G[s]:
        if x[t] is None:
            x[t] = x[s] + d
            dfs(t)
        else:
            if x[t] != x[s] + d:
                fail()

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])

for i in range(N):
    if x[i] is None:
        x[i] = 0
        dfs(i)

print("Yes")

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

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

def fail():
    print("No")
    exit()

def dfs(s):
    global x, G
    for t, d in G[s]:
        if x[t] is None:
            x[t] = x[s] + d
            dfs(t)
        else:
            if x[t] != x[s] + d:
                fail()

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])

for i in range(N):
    if x[i] is None:
        x[i] = 0
        dfs(i)

print("Yes")

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

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

def dfs(s):
    global x, G
    for t, d in G[s]:
        if x[t] is None:
            x[t] = x[s] + d
            if not dfs(t):
                return False
        else:
            if x[t] != x[s] + d:
                return False
    return True

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])

ans = True
for i in range(N):
    if x[i] is None:
        x[i] = 0
        ans &= dfs(i)

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

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

def dfs(s):
	global x, G
	for t, d in G[s]:
		if x[t] is None:
			x[t] = x[s] + d
			if not dfs(t):
				return False
		else:
			if x[t] != x[s] + d:
				return False
	return True

N,M = map(int,input().split())
x = [None] * N
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])

res = True
for i in range(N):
	if x[i] is None:
		x[i] = 0
		res &= dfs(i)

print("Yes" if res == True else "No")

Solution (Python):
def check(graph):
    import queue
    N = len(graph)
    tmp_position = [None] * N
    for i in range(N):
        if tmp_position[i] is None:
            tmp_position[i] = 0
            qu = queue.Queue()
            qu.put(i)
            while not qu.empty():
                now = qu.get()
                now_dist = tmp_position[now]
                for nxt, nxt_dist in graph[now]:
                    if tmp_position[nxt] is None:
                        tmp_position[nxt] = now_dist + nxt_dist
                        qu.put(nxt)
                    elif tmp_position[nxt] != now_dist + nxt_dist:
                        return False
    return True


N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
    L, R, D = map(int, input().split())
    L-=1;R-=1
    graph[L].append((R, D))
    graph[R].append((L, -D))
print("Yes" if check(graph)else "No")

Solution (Python):
from collections import deque

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

X = [0 for _ in range(N+1)]
edges = [[] for _ in range(N+1)]

contradiction = False

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

searched = set()
q = deque()


for i in range(N+1):
    if i in searched:
        continue
    q.append(i)
    searched.add(i)
    X[i] = 0
    while len(q) != 0:
        a = q.pop()
        for b, d in edges[a]:
            if b not in searched:
                q.append(b)
                searched.add(b)
                X[b] = X[a] + d
            else:
                if X[b] != X[a] + d:
                    contradiction = True
                    print("No")
                    break
        if contradiction:
            break
    if contradiction:
        break    
else:
    print("Yes")

Solution (Python):
from queue import Queue
import sys

inf = float("inf")
N, M = list(map(int, input().split()))
dist = [[] for x in range(N+1)]
value = [inf for x in range(N+1)]

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

for i in range(1, N+1):
    if value[i] != inf: continue
    
    value[i] = 0
    q = Queue()
    q.put(i)
    while not q.empty():
        tmp = q.get()
        for x in dist[tmp]:
            nxt = x[0]
            nxt_val = value[tmp] + x[1]
            if value[nxt] != inf:
                if value[nxt] == nxt_val: continue
                print("No")
                sys.exit()
            value[nxt] = nxt_val
            q.put(nxt)
print("Yes")

Solution (Python):
from collections import deque


def bfs(x, graph, people):
    
    if people[x] is not None:
        return
    unvisited = deque([x])
    people[x] = 0
    while unvisited:
        now = unvisited.popleft()
        for Next, d in graph[now]:
            if people[Next] is None:
                people[Next] = people[now] + d
                unvisited.append(Next)

def main():
    N, M = list(map(int, input().split()))
    graph = [ [] for i in range(N+1)]
    people = [None] * (N+1)

    
    for i in range(M):
        L, R, D = list(map(int, input().split()))
        graph[L].append((R, D))
        graph[R].append((L, -D))
    
    for i in range(1,N+1):
        bfs(i, graph, people)

    for i in range(1,N+1):
        for j,d in graph[i]:
            if people[j] - people[i] != d:
                print("No")
                exit()
    print("Yes")
if __name__ == '__main__':
    main()

Solution (Python):


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

adj = [ [] for i in range(N+1)]
distance = [-1 for i in range(N+1)]
visited = [1] + [0 for i in range(N)]
ans = True

def dfs(node):
	stack = [node]
	visited[node] = 1
	if(distance[node] == -1):
		distance[node] = 0
	while(len(stack)):
		v = stack.pop()
		p = distance[v]
		for n, d in adj[v]:
			if(visited[n] == 0):
				distance[n] = p + d
				visited[n] = 1
				stack.append(n)
			else:
				if(distance[n] != p + d):
					return False
	return True


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

for v in range(1, N+1):
	if(visited[v] == 1):
		continue
	if(not dfs(v)):
		ans = False
		break


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

Solution (Python):
from collections import deque

def bfs(x, graph, people):
    if people[x] is not None:
        return
    unvisited = deque([x])
    people[x] = 0
    while unvisited:
        now = unvisited.popleft()
        for next, d in graph[now]:
            if people[next] is None:
                people[next] =  people[now] + d
                unvisited.append(next)

def main():
    N, M = list(map(int, input().split()))

    graph = [ [] for n in range(N+1)]
    people = [None] * (N+1)

    for n in range(M):
        L, R, D = list(map(int, input().split()))
        graph[L].append((R, D))
        graph[R].append((L, -D))
    for i in range(1, N+1):
        bfs(i, graph, people)

    for i in range(1, N+1):
        for j, d in graph[i]:
            if people[j] - people[i] != d:
                print("No")
                exit()
    else:
        print("Yes")


if __name__ == "__main__":
    main()

Solution (Python):
import sys

N, M = (int(i) for i in input().split())
P = [None for i in range(N+1)]
Graph = [list() for i in range(N+1)]
for index in range(M):
	L, R, D = (int(i) for i in input().split())
	Graph[L].append((R, D))
	Graph[R].append((L,-D))

def determine(i):
	if P[i] is not None:
		return
	P[i] = 0
	stack = [i]
	while len(stack) != 0:
		I = stack.pop()
		for j, d in Graph[I]:
			if P[j] is None:
				P[j] = P[I] + d
				stack.append(j)

def check(i):
	for j, d in Graph[i]:
		if P[j] - P[i] != d:
			print("No")
			exit(0)

for i in range(1,N+1):
	determine(i)

for i in range(1,N+1):
	check(i)

print("Yes")

Solution (Python):



import sys

def main():
    n, m = map(int, sys.stdin.readline().split())
    lrds = ((map(int, line.split())) for line in sys.stdin.readlines())

    g = tuple([] for _ in range(n))
    x = [None] * n

    for l, r, d in lrds:
        l -= 1
        r -= 1
        g[l].append((r, d))
        g[r].append((l, -d))

    for i in range(n):
        if x[i] is not None:
            continue
        stack = [i]
        x[i] = 0
        while len(stack):
            v = stack.pop()
            for u, d in g[v]:
                if x[u] is None:
                    stack.append(u)
                    x[u] = x[v] + d

    for v in range(n):
        for u, d in g[v]:
            if x[v] + d != x[u]:
                print('No')
                sys.exit()

    print('Yes')

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

def main():
    N, M = map(int, input().split())
    link = [[] for _ in range(N+1)]
    value = [0 for _ in range(N+1)]

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

    searched = set()
    q = deque()
    for u in range(N+1):
        if u in searched:
            continue
        q.append(u)
        searched.add(u)
        value[u] = 0

        
        while q:
            x = q.popleft()
            for y, d in link[x]:
                if y not in searched:
                    value[y] = value[x] + d
                    q.append(y)
                    searched.add(y)

    
    for x in range(N+1):
        for y, d in link[x]:
            if value[y] != value[x] + d:
                print('No')
                return
    else:
        print('Yes')

if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque
N,M = map(int,input().split())
link = [ [] for _ in range(N+1)]
value = [ -1 for _ in range(N+1)]

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

searched = set()
queue = deque()
for u in range(N+1):
  if u not in searched:
    queue.append(u)
    searched.add(u)
    value[u] = 0
    while queue:
      v = queue.popleft()
      for w,d in link[v]:
        if w not in searched:
          value[w] = value[v] + d
          queue.append(w)
          searched.add(w)


for v in range(N+1):
  for w,d in link[v]:
    if value[w] != value[v] + d:
      print("No")
      exit()
print("Yes")

Solution (Python):
def main():
    """
    N,M:10^6より N^2->NG
    矛盾する情報を見つける
    距離情報の保持

    1-2:1, 2-3:1, 1-3:2 <-OK
    1-2:1, 2-3:1, 1-3:5 <-NG(over)
    1-2:1, 2-3:1, 1-3:1 <-NG(less)
    1-2:1, 2-4:3, 1-3:3 <-OK(2-3:2, 3-4:1)
    1-2:1, 2-4:3, 1-3:5 <-NG

    (Li,Ri,Di)
    人Ri は人Li よりも距離 Di だけ右にいる
    すなわち、xRi − xLi = Di
    Ri > Li のとき(人7の右に人8がいる)処理上問題なし
    Ri < Li のとき(人8の右に人7がいる)場合、
    xLi - xRi = -Di
    """
    N, M = map(int, input().split())
    lrd = [
        tuple(map(int, input().split()))
        for _ in range(M)
    ]

    editorial(N, M, lrd)


def editorial(N, M, lrd):
    import sys
    sys.setrecursionlimit(10 ** 7)

    xs = [None] * N
    graph = [[] for _ in range(N)]
    for l, r, d in lrd:
        graph[l - 1].append((r - 1, d))
        graph[r - 1].append((l - 1, -d))

    def dfs(i):
        
        for j, d in graph[i]:
            if xs[j] is None:
                xs[j] = xs[i] + d
                f = dfs(j)
                if not f:
                    return False
            elif xs[j] - xs[i] != d:
                
                return False

        return True

    for i, x in enumerate(xs):
        if x is None:
            
            
            
            xs[i] = 0
            f = dfs(i)
            if not f:
                print("No")
                return

    print("Yes")

if __name__ == '__main__':
    main()

Solution (Python):
import sys


def main():
    n, m = map(int, sys.stdin.readline().split())
    g = [[] for i in range(n)]
    deg = [0] * n
    for i in range(m):
        l, r, d = map(int, sys.stdin.readline().split())
        g[l - 1].append((r - 1, d))
        deg[r - 1] += 1
    dis = [-1] * n
    for i in range(n):
        if deg[i]:
            continue
        stack = list([i])
        dis[i] = 0
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if dis[u] == -1:
                    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):
import sys


def main():
    n, m = map(int, sys.stdin.readline().split())
    g = [[] for i in range(n)]
    deg = [0] * n
    lines = sys.stdin.read().splitlines()
    for line in lines:
        l, r, d = map(int, line.split())
        g[l - 1].append((r - 1, d))
        deg[r - 1] += 1
    dis = [-1] * n
    for i in range(n):
        if deg[i]:
            continue
        stack = list([i])
        dis[i] = 0
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if dis[u] == -1:
                    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):
import sys


def main():
    n, m = map(int, sys.stdin.readline().split())
    g = [[] for i in range(n)]
    deg = [0] * n
    lines = sys.stdin.read().splitlines()
    for line in lines:
        l, r, d = map(int, line.split())
        g[l - 1].append((r - 1, d))
        deg[r - 1] += 1
    dis = [-1] * n
    for i in range(n):
        if deg[i]:
            continue
        stack = list([i])
        dis[i] = 0
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if dis[u] == -1:
                    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):
import sys


def main():
    n, m = map(int, sys.stdin.readline().split())
    g = [[] for i in range(n)]
    for i in range(m):
        l, r, d = map(int, sys.stdin.readline().split())
        g[l - 1].append((r - 1, d))
        g[r - 1].append((l - 1, -d))
    dis = [0] * n
    visited = [False] * n
    for i in range(n):
        if visited[i]:
            continue
        stack = list([i])
        visited[i] = True
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if not visited[u]:
                    dis[u] = dis[v] + d
                    stack.append(u)
                    visited[u] = True
    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):
import sys


def main():
    n, m = map(int, sys.stdin.readline().split())
    g = [[] for i in range(n)]
    for i in range(m):
        l, r, d = map(int, sys.stdin.readline().split())
        g[l - 1].append((r - 1, d))
        g[r - 1].append((l - 1, -d))
    dis = [0] * n
    visited = [False] * n
    for i in range(n):
        if visited[i]:
            continue
        stack = list([i])
        visited[i] = True
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if not visited[u]:
                    dis[u] = dis[v] + d
                    stack.append(u)
                    visited[u] = True
    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):
import sys


def main():
    n, m = map(int, input().split())
    g = [[] for i in range(n)]
    lines = sys.stdin.read().splitlines()
    for i in range(m):
        l, r, d = map(int, lines[i].split())
        g[l - 1].append((r - 1, d))
        g[r - 1].append((l - 1, -d))
    dis = [0] * n
    visited = [False] * n
    for i in range(n):
        if visited[i]:
            continue
        stack = list([i])
        visited[i] = True
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if not visited[u]:
                    dis[u] = dis[v] + d
                    stack.append(u)
                    visited[u] = True
    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):
import sys


def main():
    n, m = map(int, input().split())
    g = [[] for i in range(n)]
    lines = sys.stdin.read().splitlines()
    for i in range(m):
        l, r, d = map(int, lines[i].split())
        g[l - 1].append((r - 1, d))
        g[r - 1].append((l - 1, -d))
    dis = [0] * n
    visited = [False] * n
    for i in range(n):
        if visited[i]:
            continue
        stack = list([i])
        visited[i] = True
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if not visited[u]:
                    dis[u] = dis[v] + d
                    stack.append(u)
                    visited[u] = True
    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):
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
    for i in range(n):
        if visited[i]:
            continue
        stack = list([i])
        visited[i] = True
        while len(stack):
            v = stack[-1]
            stack.pop()
            for u, d in g[v]:
                if not visited[u]:
                    dis[u] = dis[v] + d
                    stack.append(u)
                    visited[u] = True
    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):
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 defaultdict
g = defaultdict(list)

n, m = map(int, input().split())
if m==0:
    print('Yes')
    exit()
for i in range(m):
    l, r, d = map(int, input().split())
    g[l].append((r, d))
    g[r].append((l, -1*d))
    
visited = {}
vv = {k:None for k in g.keys()}
def dfs(v):
    stack = []
    visited[v] = True
    stack.append((v,0))
    while len(stack)!=0:
        v,w = stack.pop()
        vv[v] = w
        for c,d in g[v]:
            if not visited.get(c, False):
                visited[c] = True
                stack.append((c,w+d))

for f in g.keys():
    if not visited.get(f):
        dfs(f)

for k in g.keys():
    v = vv[k]
    for c,w in g[k]:
        if not v + w == vv[c]:
            print('No')
            exit()

print('Yes')

Solution (Python):

"""
https://beta.atcoder.jp/contests/abc087/tasks/arc090_b

"""
import sys
from sys import stdin
from heapq import heappush, heappop
input = stdin.readline


def solve(data, N):
    scores = [-1] * (N+1)       
    graphs = [[] for _ in range(N+1)] 
    in_degs = [0] * (N+1)       

    
    for l, r, d in data:
        in_degs[r] += 1
        graphs[l].append((r, d))

    pq = []                     
    for pos in range(1, N+1):
        if in_degs[pos] == 0:
            heappush(pq, pos)   

    cs = 1                      
    while pq:
        pos = heappop(pq)
        if scores[pos] < 0:     
            scores[pos] = cs
        for r, d in graphs[pos]: 
            if scores[r] < 0:
                scores[r] = scores[pos] + d
            else:
                if scores[r] != scores[pos] + d: 
                    return 'No'
            in_degs[r] -= 1     
            if in_degs[r] == 0:
                heappush(pq, r)

    for d in in_degs[1:]:       
        if d > 0:
            return 'No'
    return 'Yes'


def main(args):
    N, M = map(int, input().split())
    data = []
    for _ in range(M):
        l, r, d = map(int, input().split())
        data.append((l, r, d))
    ans = solve(data, N)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
def try_dfs_fill_distance(graph, starting_node, distance_cache):
    found_conflicts = False
    traverse_stack = []
    traverse_stack.append((starting_node, 0))

    while traverse_stack:
        node, node_dist_from_origin = traverse_stack.pop()
        if distance_cache[node] == None:
            distance_cache[node] = node_dist_from_origin
            for neighbor_data in graph[node]:
                neighbor_id, neighbor_diff = neighbor_data
                traverse_stack.append((neighbor_id, node_dist_from_origin + neighbor_diff))

        elif distance_cache[node] != node_dist_from_origin:
            found_conflicts = True
            break

    return found_conflicts

if __name__ == '__main__':
    n, m = list(map(int, input().split(" ")))
    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        l, r, d = list(map(int, input().split()))
        graph[l].append((r, d))
        graph[r].append((l, -d))

    distance_cache = [None for _ in range(n + 1)]
    has_conflict = False
    for i in range(1, len(distance_cache)):
        if distance_cache[i] == None:
            has_conflict = try_dfs_fill_distance(graph, i, distance_cache)
            if has_conflict:
                break

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

Solution (Python):
def try_dfs_fill_distance(graph, starting_node, distance_cache):
    found_conflicts = False
    traverse_stack = []
    traverse_stack.append((starting_node, 0))

    while traverse_stack:
        node, node_dist_from_origin = traverse_stack.pop()
        if distance_cache[node] == None:
            distance_cache[node] = node_dist_from_origin
            for neighbor_data in graph[node]:
                neighbor_id, neighbor_diff = neighbor_data
                traverse_stack.append((neighbor_id, node_dist_from_origin + neighbor_diff))

        elif distance_cache[node] != node_dist_from_origin:
            found_conflicts = True
            break

    return found_conflicts

if __name__ == '__main__':
    n, m = list(map(int, input().split(" ")))
    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        l, r, d = list(map(int, input().split()))
        graph[l].append((r, d))
        graph[r].append((l, -d))

    distance_cache = [None for _ in range(n + 1)]
    has_conflict = False
    for i in range(1, len(distance_cache)):
        if distance_cache[i] == None:
            
            
            has_conflict = try_dfs_fill_distance(graph, i, distance_cache)
            if has_conflict:
                break

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

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

def try_dfs_fill_distance(graph, cur_node, cur_dist_from_origin, distance_cache):
    found_conflicts = False
    for neighbor_node_data in graph[cur_node]:
        neighbor_node, neighbor_distance_from_cur = neighbor_node_data
        neighbor_dist_from_origin = (cur_dist_from_origin + neighbor_distance_from_cur)
        
        if distance_cache[neighbor_node] == None:
            distance_cache[neighbor_node] = neighbor_dist_from_origin
            found_conflicts = try_dfs_fill_distance(graph, neighbor_node, neighbor_dist_from_origin, distance_cache)
        else:
            if distance_cache[neighbor_node] != neighbor_dist_from_origin:
                
                found_conflicts = True

        if found_conflicts:
            break

    return found_conflicts

if __name__ == '__main__':
    n, m = list(map(int, input().split(" ")))
    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        l, r, d = list(map(int, input().split()))
        graph[l].append((r, d))
        graph[r].append((l, -d))

    distance_cache = [None for _ in range(n + 1)]
    has_conflict = False
    for i in range(1, len(distance_cache)):
        if distance_cache[i] == None:
            distance_cache[i] = 0
            has_conflict = try_dfs_fill_distance(graph, i, 0, distance_cache)
            if has_conflict:
                break

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

Solution (Python):
class UnionFindTree:
    def __init__(self, size):
        self.parent = list(range(size))
        self.dist = [0]*size

    def find_root(self, x):
        if self.parent[x] == x:
            return x, 0
        else:
            self.parent[x], d = self.find_root(self.parent[x])
            self.dist[x] += d
            return self.parent[x], self.dist[x]

    def union(self, x, y, d):
        r1, d1 = self.find_root(x)
        r2, d2 = self.find_root(y)

        if r1 != r2:
            self.parent[r2] = r1
            self.dist[r2] = (d1 - d2) + d
        else:
            if (d2 - d1) != d:
                return False

        return True

def main():
    (N, M) = tuple(map(int, input().split(' ')))

    tree = UnionFindTree(N)

    for i in range(M):
        l, r, d = map(int, input().split(' '))

        if not tree.union(l-1, r-1, d):
            print('No')
            return

    print('Yes')

main()

Solution (Python):
import numpy as np

N, M = tuple(map(int, input().split()))
Ls = np.zeros((M,), dtype=int)
Rs = np.zeros((M,), dtype=int)
Ds = np.zeros((M,), dtype=int)

for i in range(M):
    Ls[i], Rs[i], Ds[i] = tuple(map(int, input().split()))



Ls = Ls - 1
Rs = Rs - 1

adjacency_list = []
for i in range(N):
    adjacency_list.append([])

for i in range(M):
    adjacency_list[Ls[i]].append((Rs[i], Ds[i]))
    adjacency_list[Rs[i]].append((Ls[i], -Ds[i]))




visited = np.zeros(N, dtype=bool)
weights = np.zeros(N, dtype=int)
to_be_visited = []


pointer = 0
for pointer in range(N):
    if not visited[pointer]:
        to_be_visited.append(pointer)
        while len(to_be_visited) != 0:
            node_index = to_be_visited.pop()
            candidate = adjacency_list[node_index]
            for _i, weight in candidate:
                if not visited[_i]:
                    visited[_i] = True
                    weights[_i] = weights[node_index] + weight
                    to_be_visited.append(_i)

for i in range(M):
    
    if weights[Rs[i]] - weights[Ls[i]] == Ds[i]:
        
        pass
    else:
        
        print("No")
        exit()
print("Yes")

Solution (Python):
def root(x):
    if x == parent[x]:
        return x
    y = root(parent[x])
    dist[x] += dist[parent[x]]
    parent[x] = y
    return y
def unite(x, y, d):
    px = root(x); py = root(y)
    if px < py:
        parent[py] = px
        dist[py] = dist[x] - dist[y] - d
    else:
        parent[px] = py
        dist[px] = dist[y] - dist[x] + d

n, m = map(int, input().split())
*parent, = range(n)
dist = [0]*n
for i in range(m):
    l, r, d = map(int, input().split())
    l -= 1; r -= 1
    if root(l) == root(r):
        if dist[l] - dist[r] != d:
            print("No")
            exit(0)
    else:
        unite(l, r, d)
print("Yes")

Solution (Python):
from collections import deque
n, m = map(int, raw_input().split())
graph = {_: set() for _ in xrange(n + 1)}
in_deg, dist = [0] * (n + 1), [-1] * (n + 1)
for _ in xrange(m):
    l, r, d = map(int, raw_input().split())
    graph[l].add((r, d))
    in_deg[r] += 1
que = deque([i for i in xrange(n + 1) if not in_deg[i]])
cst = 1
while que:
    stp = que.popleft()  
    if in_deg[stp] < 0:
        in_deg[stp] = cst
    for v, d in graph[stp]:
        if dist[v] < 0:
            dist[v] = dist[stp] + d
        else:
            if dist[v] != dist[stp] + d:
                print 'No'
                exit()
        in_deg[v] -= 1
        if not in_deg[v]:
            que.append(v)
print 'No' if [_ for _ in in_deg[1:] if _ > 0] else 'Yes'