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



Sample input:
3 3
1 2 1
2 3 1
1 3 2


Sample output:
Yes

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w

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

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

    def size(self, x):
        return -self.parents[self.find(x)]

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


n, m = map(int, input().split())
UF = WeightedUnionFind(n + 1)

for i in range(m):
    l, r, d = map(int, input().split())
    if UF.same(l, r):
        if d != UF.diff(l, r):
            exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.weight[x] += self.weight[self.parents[x]]
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w

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

    def size(self, x):
        return -self.parents[self.find(x)]

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


n, m = map(int, input().split())
UF = WeightedUnionFind(n + 1)

for i in range(m):
    l, r, d = map(int, input().split())
    if UF.same(l, r) and d != UF.diff(l, r):
        exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")

Submission status: Wrong Answer

Solution code:
N,M = map(int,(input().split()))
info = []
for i in range(M):
    l,r,d = map(int,(input().split()))
    if l > r:
        l,r = r,l
        d = -d
    info.append([l,r,d])
info.sort()

people = [-1]*(N+1) # 1index
for i in range(len(info)):
    if people[ info[i][0] ] == -1 and people[ info[i][1] ] == -1:
        people[ info[i][0] ] = 0
        people[ info[i][1] ] = info[i][2]
    elif people[ info[i][0] ] == -1:
        people[ info[i][0] ] = people[ info[i][1] ] - info[i][2]
    elif people[ info[i][1] ] == -1:
        people[ info[i][1] ] = people[ info[i][0] ] + info[i][2]
    else:
        if people[ info[i][1] ] - people[ info[i][0] ] != info[i][2]:
            print("No")
            break
else:
    print("Yes")

Submission status: Wrong Answer

Solution code:
from collections import deque
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =123456
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
connection ={i:set() for i in range(1,N+1)}
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
        connection[l].add(r)
        connection[r].add(l)
    
#1つ仮定して、矛盾するかみる
#x[L[0]] =1
ans ="Yes"
#already =set()
yet =deque(connection.keys())
while yet:
    temp =yet.popleft()
    x[temp] =1
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
            else:
                continue
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            yet.remove(R[i])
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
            yet.remove(L[i])

print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =123456
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
connection ={i:set() for i in range(1,N+1)}
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
        connection[l].add(r)
        connection[r].add(l)
    
#1つ仮定して、矛盾するかみる
#x[L[0]] =1
start =x[L[0]]
ans ="Yes"
already =set()
yet =set(connection.keys())
while yet:
    temp =yet.pop()
    x[temp] =1
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
            else:
                continue
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            already.add(R[i])
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
            already.add(L[i])
    yet -=already

print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =123456
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =1
ans ="Yes"
for j in range(5):
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
            else:
                continue
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =123456
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =1
ans ="Yes"
for j in range(5):
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =1234567890
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =1
ans ="Yes"
for j in range(5):
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =1234567890
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =0
ans ="Yes"
for j in range(2):
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
max_x =1234567
x =[max_x]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =0
ans ="Yes"
for j in range(2):
    for i in range(M):
        if x[L[i]] != max_x and x[R[i]] != max_x:
            if x[R[i]] - x[L[i]] !=D[i]:
                ans ="No"
                break
        elif x[L[i]] == max_x and x[R[i]] == max_x:
            continue
        elif x[L[i]] != max_x:
            x[R[i]] =D[i] +x[L[i]]
            continue
        elif x[R[i]] != max_x:
            x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

Solution code:
# 初期入力
import sys
input = sys.stdin.readline
N,M = (int(x) for x in input().split())
x =[123456]*2*10**5
L=[0]*M
R=[0]*M
D=[0]*M
if M ==0:
    print("Yes")
    exit()
else:
    for i in range(M):
        l,r,d = (int(x) for x in input().split())
        L[i] =l
        R[i] =r
        D[i] =d
    
#1つ仮定して、矛盾するかみる
x[L[0]] =0
ans ="Yes"
for i in range(M):
    if x[L[i]] != 123456 and x[R[i]] != 123456:
        if x[R[i]] - x[L[i]] !=D[i]:
            ans ="No"
            break
    elif x[L[i]] == 123456 and x[R[i]] == 123456:
        continue
    elif x[L[i]] != 123456:
        x[R[i]] =D[i] +x[L[i]]
        continue
    elif x[R[i]] != 123456:
        x[L[i]] =D[i] +x[R[i]]
print(ans)

Submission status: Wrong Answer

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

li = []
dis = [False] * n

for _ in range(m):
    l,r,d = map(int,input().split())
    if l <= r:
        li.append([l,r,d])
    else:
        li.append([r,l,-d])

li.sort(key = lambda x: x[1])
li.sort()

for l,r,d in li:
    l -= 1
    r -= 1
    if not dis[l]:
        dis[l] = 0
        dis[r] = d
    else:
        if not dis[r]:
            dis[r] = dis[l] + d
        else:
            if dis[r] - dis[l] != d:
                print('No')
                exit()

print('Yes')

Submission status: Wrong Answer

Solution code:
# Union Find 木
from sys import setrecursionlimit


def find(parent, diff_weight, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, diff_weight, t)
    diff_weight[i] += diff_weight[parent[i]]
    parent[i] = t
    return t


def weight(parent, diff_weight, i):
    find(parent, diff_weight, i)
    return diff_weight[i]


def unite(parent, diff_weight, i, j, d):
    i = find(parent, diff_weight, i)
    j = find(parent, diff_weight, j)
    if i == j:
        return
    parent[i] += parent[j]
    parent[j] = i
    diff_weight[j] = d - weight(parent, diff_weight, j) + \
        weight(parent, diff_weight, i)


setrecursionlimit(10 ** 6)

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

parent = [-1] * (N + 1)
diff_weight = [0] * (N + 1)
for L, R, D in LRD:
    i = find(parent, diff_weight, L)
    j = find(parent, diff_weight, R)
    if i != j:
        unite(parent, diff_weight, L, R, D)
    else:
        if weight(parent, diff_weight, L) + D != weight(parent, diff_weight, R):
            print('No')
            exit()
print('Yes')

Submission status: Wrong Answer

Solution code:
# Union Find 木
from sys import setrecursionlimit


def find(parent, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, t)
    parent[i] = t
    return t


def unite(parent, i, j):
    i = find(parent, i)
    j = find(parent, j)
    if i == j:
        return
    if i < j:
        parent[i] += parent[j]
        parent[j] = i
    else:
        parent[j] += parent[i]
        parent[i] = j


def pos(x, i):
    j, k = x[i]
    if i == j:
        return i, 0
    l, m = pos(x, j)
    x[i] = (l, m + k)
    return x[i]


setrecursionlimit(10 ** 6)

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

parent = [-1] * (N + 1)
x = [(i, 0) for i in range(N + 1)]
for L, R, D in LRD:
    i = find(parent, L)
    j = find(parent, R)
    if i != j:
        x[j] = (i, D - pos(x, R)[1] + pos(x, L)[1])
        unite(parent, L, R)
    else:
        if pos(x, L)[1] + D != pos(x, R)[1]:
            print('No')
            exit()
print('Yes')

Submission status: Wrong Answer

Solution code:
# Union Find 木
from sys import setrecursionlimit


def find(parent, i):
    t = parent[i]
    if t < 0:
        return i
    t = find(parent, t)
    parent[i] = t
    return t


def unite(parent, i, j):
    i = find(parent, i)
    j = find(parent, j)
    if i == j:
        return
    if i < j:
        parent[i] += parent[j]
        parent[j] = i
    else:
        parent[j] += parent[i]
        parent[i] = j


def pos(x, i):
    j, k = x[i]
    if i == j:
        return i, 0
    l, m = pos(x, j)
    x[i] = (l, m + k)
    return x[i]


setrecursionlimit(10 ** 6)

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

parent = [-1] * (N + 1)
x = [(i, 0) for i in range(N + 1)]
for L, R, D in LRD:
    if find(parent, L) != find(parent, R):
        x[R] = (L, D)
        unite(parent, L, R)
    else:
        if pos(x, L)[1] + D != pos(x, R)[1]:
            print('No')
            exit()
print('Yes')

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def DD(x):
  dis=0
  while x>=0:
    dis=dis+D[x]
    x=uf.parents[x]
  return dis

n,m=map(int,input().split())
uf=UnionFind(n)
D=[0]*n
f=0
for i in range(m):
  l,r,d=map(int,input().split())
  l=l-1
  r=r-1
  if uf.find(l)!=uf.find(r):
    if uf.parents[uf.find(l)]<=uf.parents[uf.find(r)]:
      D[uf.find(r)]=DD(l)+d-DD(r)
    else:
      D[uf.find(l)]=DD(r)-d-DD(l)
    uf.union(l,r)
  else:
    if DD(r)-DD(l)!=d:
      f=1
if f==0:
  print("Yes")
else:
  print("No")

Submission status: Wrong Answer

Solution code:
import sys
input=sys.stdin.readline

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def DD(x):
  dis=0
  while x>=0:
    dis=dis+D[x]
    x=uf.parents[x]
  return dis

n,m=map(int,input().split())
uf=UnionFind(n)
D=[0]*n
f=0
for i in range(m):
  l,r,d=map(int,input().split())
  l=l-1
  r=r-1
  if uf.find(l)!=uf.find(r):
    if uf.find(l)<=uf.find(r):
      D[uf.find(r)]=DD(l)+d-DD(r)
    else:
      D[uf.find(l)]=DD(r)-d-DD(l)
    uf.union(l,r)
  else:
    if DD(r)-DD(l)!=d:
      f=1
if f==0:
  print("Yes")
else:
  print("No")

Submission status: Wrong Answer

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

INF = 10**10

from collections import defaultdict
n,m = map(int,input().split())

visit = [False] * n
D = [INF]*n

def dfs(v):    
  
  for nv,nd in G[v]:
    if D[v] == INF:
      D[nv] = D[v] + nd
      if dfs(nv):
        return True
    else:
      if D[nv] - D[v] != nd:
        return True
  return False

ans = 'Yes'
G = [[] for _ in range(n)]
for i in range(m):
  l,r,d = map(int,input().split())
  G[l-1].append((r-1,d))
  G[r-1].append((l-1,-d))  
  
for i in range(n):
  if D[i]==INF:
    D[i] = 0
    if dfs(i):
      ans = 'No'
      break
  
print(ans)

Submission status: Wrong Answer

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

INF = 10**10

from collections import defaultdict
n,m = map(int,input().split())

visit = [False] * n
D = [INF]*n

def dfs(v):    
  
  for nv,nd in G[v]:
    if D[v] == INF:
      D[nv] = D[v] + nd
      if dfs(nv):
        return True
    else:
      if D[nv] - D[v] != nd:
        return True
  return True

ans = 'Yes'
G = [[] for _ in range(n)]
for i in range(m):
  l,r,d = map(int,input().split())
  G[l-1].append((r-1,d))
  G[r-1].append((l-1,-d))  
  
for i in range(n):
  if D[i]==INF:
    D[i] = 0
    if dfs(i):
      ans = 'No'
      break
  
print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        self.parents[x] = self.find(self.parents[x])
        self.weight[x] += self.weight[self.parents[x]]
        return self.parents[x]

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            return
        if self.size(rx) < self.size(ry):
            rx, ry = ry, rx
        self.parents[rx] += self.parents[ry]
        self.weight[ry] = w + self.weight[y] - self.weight[x]
        self.parents[ry] = rx

    def size(self, x):
        return -self.parents[self.find(x)]

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

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


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

for _ in range(M):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if uf.same(l, r):
        diff = uf.diff(l, r)
        if diff != d:
            print("No")
            exit()
    else:
        uf.union(l, r, d)

print("Yes")

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        self.parents[x] = self.find(self.parents[x])
        self.weight[x] += self.weight[self.parents[x]]
        return self.parents[x]

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            return
        if self.size(rx) < self.size(ry):
            rx, ry = ry, rx
        self.parents[rx] += self.parents[ry]
        self.weight[ry] = w - self.weight[y] - self.weight[x]
        self.parents[ry] = rx

    def size(self, x):
        return -self.parents[self.find(x)]

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

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


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

for _ in range(M):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if uf.same(l, r):
        diff = uf.diff(l, r)
        if diff != d:
            print("No")
            exit()
    else:
        uf.union(l, r, d)

print("Yes")

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        self.parents[x] = self.find(self.parents[x])
        self.weight[x] += self.weight[self.parents[x]]
        return self.parents[x]

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            return
        if self.size(rx) < self.size(ry):
            rx, ry = ry, rx
        self.parents[rx] += self.parents[ry]
        self.weight[ry] = -w - self.weight[y] + self.weight[x]
        self.parents[ry] = rx

    def size(self, x):
        return -self.parents[self.find(x)]

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

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


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

for _ in range(M):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if uf.same(l, r):
        diff = uf.diff(l, r)
        if diff != d:
            print("No")
            exit()
    else:
        uf.union(l, r, d)

print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    class UnionFindTree:
        def __init__(self, num_of_elm):
            '''
            0 ... num_of_elem - 1 まで数字で表される (0-index) グループを管理する union find tree を作成する (O(n))
            '''
            self.n = num_of_elm
            self.table = [i for i in range(self.n)]    # table[ind] は ind の親の index を表す。ind == table[ind] の時そのグループの root である。
            self.rank = [0] * self.n    # root となる ind について rank[ind] はその木の深さを表す。それ以外の ind については意味を持たない。
            self.group_size = [1] * self.n    # root となる ind について group_size[ind] はそのグループに属するメンバの個数を表す。それ以外の ind については意味を持たない。
        
        def _find_set(self, x):
            '''
            x の属するグループ番号を O(α(n)) で求める
            '''
            parent = self.table[x]
            if x == parent:
                return x
            else:
                root = self._find_set(parent)
                # 経路圧縮
                self.table[x] = root
                return root
        
        def is_same(self, x, y):
            '''
            x と y が同じグループに属するか O(α(n)) で判定する
            '''
            return self._find_set(x) == self._find_set(y)
    
        def union(self, x, y):
            '''
            x と y の属するグループを O(α(n)) で統合する
            '''
            shallow_root = self._find_set(x)
            deep_root = self._find_set(y)
            if self.rank[shallow_root] > self.rank[deep_root]:
                shallow_root, deep_root = deep_root, shallow_root
            # そもそも同一グループだった時
            if shallow_root == deep_root:
                return False
            # グループが異なるので union
            else:
                self.table[shallow_root] = deep_root
                self.group_size[deep_root] += self.group_size[shallow_root]
                # 深さが等しかったときはつけ加えられた側の rank をインクリメントする
                if self.rank[shallow_root] == self.rank[deep_root]:
                    self.rank[deep_root] += 1
                return True
    
        def akin_num(self, x):
            '''
            x の属するグループのサイズを O(1) で計算する
            '''
            x_root = self._find_set(x)
            return self.group_size[x_root]
    
        def print_group_id(self):
            print([self._find_set(x) for x in self.table])


    def no_contradict_p(info):
        uf = UnionFindTree(n)
        for l, r, _ in info:
            uf.union(l, r)
        
        point_dict = dict()
        for l, r, dist in info:
            g = uf._find_set(l)
            if g not in point_dict:
                point_dict[g] = dict()
            if (l not in point_dict[g]) and (r not in point_dict[g]):
                # 0 で初期化
                point_dict[g][l] = 0
                point_dict[g][r] = dist
            elif l not in point_dict[g]:
                point_dict[g][l] = point_dict[g][r] - dist
            elif r not in point_dict[g]:
                point_dict[g][r] = point_dict[g][l] + dist
            else:
                if point_dict[g][r] != point_dict[g][l] + dist:
                    return False
                else:
                    continue
        # 距離関係の矛盾は今のところなかった。あとは座標のレンジがおさまるかチェック
        for g, d in point_dict.items():
            if max(d.values()) -  min(d.values()) > 10**9:    # どうスライド移動しても入らない
                return False
        return True

    
    n, m = mi()
    info = []
    for _ in range(m):
        l, r, dist = mi_0()
        dist += 1
        if l > r:
            l, r, dist = r, l, - dist
        info.append([l, r, dist])
    
    info.sort(key=itemgetter(0))
    print('Yes') if no_contradict_p(info) else print('No')



if __name__ == "__main__":
    main()