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: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, size):
        self.parent = [-1 for i in range(size)]#非負なら親ノード，負ならグループの要素数
        self.diff_p = [0 for i in range(size)]#親ノードを基準としたポテンシャル

    def root(self, x): #root(x): xの根ノードを返す．
        if self.parent[x] < 0:
            return x
        else:
            rx = self.root(self.parent[x]) #xをxの根rxに直接つなぎたい
            self.diff_p[x] += self.diff_p[self.parent[x]] #そのために，diff(rx,x)を計算
            self.parent[x] = rx #xをrxに直接つなげる
            return rx

    def merge(self, x, y, dxy): #ポテンシャル差の条件p(y)-p(x)=dxyでxとyのグループをまとめる
        dxy = self.diff_p[x] + dxy - self.diff_p[y] #dxyをdiff(rx,ry)で置き換え
        x = self.root(x) #rxを新たにxと名づける
        y = self.root(y) #ryを新たにyと名づける
        if x == y:
            return False
        if self.parent[x] > self.parent[y]: #xの要素数がyの要素数より「小さい」とき入れ替える
            x,y=y,x
            diffxy = -diffxy
        self.parent[x] += self.parent[y] #xの要素数を更新
        self.parent[y] = x #yをxにつなぐ
        self.diff_p[y] = dxy #yの相対ポテンシャルを更新
        return True

    def issame(self, x, y): #issame(x,y): xとyが同じグループにあるならTrue
        return self.root(x) == self.root(y)
        
    def diff(self,x,y): #diff(x,y): xを基準としたyのポテンシャルを返す 
        if self.root(x) == self.root(y): #この時点でxの親はroot(x)
            return self.diff_p[y] - self.diff_p[x]
        else:
            return None

    def size(self,x): #size(x): xのいるグループの要素数を返す
        return -self.parent[self.root(x)]
#>>>>>>>>>>>>>>EhdCutHere>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

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

uf = UnionFind(n)
ans = True
for i in range(m):
    l,r,d=list(map(int,input().split()))
    l-=1;r-=1;
    if uf.issame(l,r):
        ans = d==uf.diff(l,r)
    else:
        uf.merge(l,r,d)
    if ans == False:
        break

if ans == False:
    print('No')
else:
    print('Yes')
#print([uf.root(i) for i in range(n)])
#print([uf.parent[i] for i in range(n)])
#print([uf.size(i) for i in range(n)])

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, size):
        self.parent = [-1 for i in range(size)]#非負なら親ノード，負ならグループの要素数
        self.diff_potential = [0 for i in range(size)]#親ノードを基準としたポテンシャル

    def root(self, x): #root(x): xの根ノードを返す．
        if self.parent[x] < 0:
            return x
        else:
            rx = self.root(self.parent[x]) #xをxの根rxに直接つなぎたい
            self.diff_potential[x] += self.diff_potential[self.parent[x]] #そのために，diff(rx,x)を計算
            self.parent[x] = rx #xをrxに直接つなげる
            return rx

    def merge(self, x, y, diffxy): #merge(x,y): xのいるグループと$y$のいるグループをまとめる
        diffxy = self.diff_potential[x] + diffxy - self.diff_potential[y] #diffxyをdiff(rx,ry)で置き換え
        x = self.root(x) #rxを新たにxと名づける
        y = self.root(y) #ryを新たにyと名づける
        if x == y:
            return False
        if self.parent[x] > self.parent[y]: #xの要素数がyの要素数より「小さい」とき入れ替える
            x,y=y,x
            diffxy = -diffxy
        self.parent[x] += self.parent[y] #xの要素数を更新
        self.parent[y] = x #yをxにつなぐ
        self.diff_potential[y] = diffxy #yの相対ポテンシャルを更新
        return True

    def issame(self, x, y): #same(x,y): xとyが同じグループにあるならTrue，違うならFalse
        return self.root(x) == self.root(y)
        
    def diff(self,x,y): #diff(x,y): xを基準としたyのポテンシャルを返す 
        if self.root(x) == self.root(y): #この時点でxの親はroot(x)
            return self.diff_potential[y] - self.diff_potential[x]
        else:
            return None

    def size(self,x): #size(x): xのいるグループの要素数を返す
        return -self.parent[self.root(x)]
#>>>>>>>>>>>>>>EhdCutHere>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

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

uf = UnionFind(n)
ans = True
for i in range(m):
    l,r,d=list(map(int,input().split()))
    if uf.issame(l,r):
        ans = d==uf.diff(l,r)
    else:
        uf.merge(l,r,d)
    if ans == False:
        break

if ans == False:
    print('No')
else:
    print('Yes')
#print([uf.root(i) for i in range(n)])
#print([uf.parent[i] for i in range(n)])
#print([uf.size(i) for i in range(n)])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
n, m = map(int, input().split())
dic_list = []
listind = [-1]*n
maxind = 0
for i in range(m):    
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if listind[l] == -1 and listind[r] == -1:
        listind[l] = maxind
        listind[r] = maxind
        dic_list.append({l : 0, r : d})
        maxind +=1
    elif listind[l] == listind[r]:
        dic_tmp = dic_list[listind[l]]
        if dic_tmp[r] - dic_tmp[l] != d:
            print('No')
            exit()
    elif listind[l] != -1 and listind[r] != -1:
        dicl = dic_list[listind[l]]
        dicr = dic_list[listind[r]]
        dicl[r] = dicl[l] + d
        offset = dicl[r] = dicr[r]
        for key, x in dic_list[listind[r]]:
            dicl[key] = dicr[key] + offset
            listind[key] = listind[l]
    elif listind[l] == -1 and listind[r] != -1:
        dic_tmp = dic_list[listind[r]]
        dic_tmp[l] = dic_tmp[r] - d
        listind[l] = listind[r]

    elif listind[l] != -1 and listind[r] == -1:
        dic_tmp = dic_list[listind[l]]
        dic_tmp[r] = dic_tmp[l] + d
        listind[r] = listind[l]
print('Yes')

Submission status: Runtime Error

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

for i in range(N):
    if dist[i] is not None: continue
    dist = [None] * N
    dist[i] = 0
    stack = [i]
    while stack:
        v = stack.pop()
        for to,d in es[v]:
            if dist[to] is None:
                dist[to] = dist[v] + d
                if not checked[to]:
                    stack.append(to)
            else:
                if dist[to] != dist[v] + d:
                    print('No')
                    exit()
print('Yes')

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
arcs = {}
for _ in range(M):
    l, r, d = tuple(map(int, input().split()))
    arcs[l, r] = d

def consistent(arcs):
    for (u, v), d in arcs.items():
        for w in range(1, n + 1): # u + 1, v
            if w == u or w == v:
                continue
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != d:
                    return False
    return True

if consistent(arcs):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
arcs = {}
for _ in range(M):
    l, r, d = tuple(map(int, input().split()))
    arcs[l, r] = d

def consistent(arcs):
    for (u, v), d in arcs.items():
        for w in range(1, n + 1): # u + 1, v
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != d:
                    return False
    return True

if consistent(arcs):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
arcs = {}
for _ in range(M):
    l, r, d = tuple(map(int, input().split()))
    arcs[l, r] = d

def consistent(arcs):
    for (u, v), d in arcs.items():
        for w in range(n): # u + 1, v
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != d:
                    return False
    return True

if consistent(arcs):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
arcs = {}
for _ in range(M):
    l, r, d = tuple(map(int, input().split()))
    arcs[l, r] = d

def consistent(arcs):
    for u, v, d in LRD:
        for w in range(u + 1, v):
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != arcs[u, v]:
                    return False
    return True

if consistent(arcs):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

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

def consistent(LRD):
    L, R, D = zip(*LRD)
    arcs = dict(zip(zip(L, R), D))
    for u, v, d in LRD:
        for w in range(u + 1, v):
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != arcs[u, v]:
                    return False
    return True

if consistent(LRD):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
def consistent(LRD):
    L, R, D = zip(*LRD)
    arcs = dict(zip(zip(L, R), D))
    for u, v, d in LRD:
        for w in range(u + 1, v):
            if (u, w) in arcs and (w, v) in arcs:
                if arcs[u, w] + arcs[w, v] != arcs[u, v]:
                    return False
    return True

if consistent(LRD):
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)
def depth_dp(v):
    if point[v] == float('inf'):
        point[v] = 0
    flag[v] = True
    for e in E[v]:
        if point[e[0]] == float('inf'):
            point[e[0]] = point[v] + e[1]
        elif point[e[0]] != point[v] + e[1]:
            return False
    for e in E[v]:
        if not flag[e[0]]:
            if not depth_dp(e[0]):
                return False
    return True

N,M = list(map(int,input().split()))
E = [[] for _ in range(N)]
flag = [False]*N
ans = True
point = [float('inf')]*N
for i in range(M):
    L,R,D = list(map(int,input().split()))
    E[L-1].append((R-1,D))
    E[R-1].append((L-1,-D))
for i in range(N):
    if not flag[i]:
        if not depth_dp(i):
            ans = False
            break
if ans:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
def depth_dp(v):
    if point[v] == float('inf'):
        point[v] = 0
    flag[v] = True
    for e in E[v]:
        if point[e[0]] == float('inf'):
            point[e[0]] = point[v] + e[1]
        elif point[e[0]] != point[v] + e[1]:
            return False
    for e in E[v]:
        if not flag[e[0]]:
            if not depth_dp(e[0]):
                return False
    return True

N,M = list(map(int,input().split()))
E = [[] for _ in range(N)]
flag = [False]*N
ans = True
point = [float('inf')]*N
for i in range(M):
    L,R,D = list(map(int,input().split()))
    E[L-1].append((R-1,D))
    E[R-1].append((L-1,-D))
for i in range(N):
    if not flag[i]:
        if not depth_dp(i):
            ans = False
            break
if ans:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
import numpy as np

class Solver:
    def __init__(self, N, edge):
        self.N = N
        self.edge = edge
        
    def dfs(self, i, x):
        self.x_arr[i] = x
        self.visited[i] = True

        isValid = True
        for (to, cost) in self.edge[i]:
            if self.visited[to] and self.x_arr[to] != x + cost:
                isValid = False
            elif not(self.visited[to]):
                isValid = self.dfs(to, x + cost)
            if not(isValid):
                break
        return isValid
        
    def solve(self):
        self.x_arr = np.zeros(self.N).astype(int)
        self.visited = np.zeros(self.N).astype(bool)
        
        isValid = True
        for i in range(self.N):
            if not(self.visited[i]):
                isValid = self.dfs(i, 0)
                if not(isValid):
                    break
        return isValid
    
def main():
    N, M = [int(_) for _ in input().split()]
    edge = [[] for _ in range(N)]

    for _ in range(M):
        left, right, dist = [int(_) for _ in input().split()]
        left -= 1
        right -= 1
        edge[left].append((right, dist))
        edge[right].append((left, -dist))
        
    solver = Solver(N, edge)
    if (solver.solve()):
        print("Yes")
    else:
        print("No")
        
if __name__=="__main__":
    main()

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
LRD = [list(map(int, input().split())) for i in range(M)]


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

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 重さの検索
    def weighting(self, x):
        self.find(x)
        return self.weight[x]

    # 併合
    def union(self, x, y, w):
        w -= self.weighting(x)
        w += self.weighting(y)
        x = self.find(x)
        y = self.find(y)

        if self.rank[x] < self.rank[y]:
            self.weight[y] = w
            self.par[y] = w
        else:
            self.weight[y] = -w
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # 各頂点間の絶対距離
    def diff(self, x, y):
        return self.weighting(x) - self.weighting(y)


wuf = WeightedUnionFind(N)
for l, r, d in LRD:
    if wuf.same(l, r):
        if wuf.diff(l, r) != d:
            print("No")
            break
    else:
        wuf.union(l, r, d)
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
LRD = [list(map(int, input().split())) for i in range(M)]


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

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 重さの検索
    def weighting(self, x):
        self.find(x)
        return self.weight[x]

    # 併合
    def union(self, x, y, w):
        w -= self.weighting(x)
        w += self.weighting(y)
        x = self.find(x)
        y = self.find(y)

        if self.rank[x] < self.rank[y]:
            self.weight[y] = w
            self.par[y] = w
            self.find(x)
            self.find(y)
        else:
            self.weight[y] = -w
            self.par[y] = x
            self.find(x)
            self.find(y)
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # 各頂点間の絶対距離
    def diff(self, x, y):
        return self.weighting(x) - self.weighting(y)


wuf = WeightedUnionFind(N)
for l, r, d in LRD:
    if wuf.same(l, r):
        if wuf.diff(l, r) != d:
            print("No")
            break
    else:
        wuf.union(l, r, d)
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10000)
[n,m]=[int(i) for i in input().split()]
g=[[] for i in range(10**5+1)]
s=[]
d=[-1 for i in range(10**5+1)]
for i in range(m):
 a=[int(i) for i in input().split()]
 g[a[0]].append([a[1],a[2]])
 s.append(a[0])
s.sort()
ss="Yes"
def dfs(v):
    global ss
    for i in range(len(g[v])):
        if d[g[v][i][0]]==-1:
            d[g[v][i][0]]=d[v]+g[v][i][1]
            dfs(g[v][i][0])
        else:
            if d[g[v][i][0]]!=(d[v]+g[v][i][1]):
              ss="No"
for i in range(m):
  if d[s[i]]==-1:
     d[s[i]]=0
     dfs(s[i])
print(ss)

Submission status: Runtime Error

Solution code:
[n,m]=[int(i) for i in input().split()]
g=[[] for i in range(10**5+1)]
s=[]
d=[-1 for i in range(10**5+1)]
for i in range(m):
 a=[int(i) for i in input().split()]
 g[a[0]].append([a[1],a[2]])
 s.append(a[0])
s.sort()
ss="Yes"
def dfs(v):
    global ss
    for i in range(len(g[v])):
        if d[g[v][i][0]]==-1:
            d[g[v][i][0]]=d[v]+g[v][i][1]
            dfs(g[v][i][0])
        else:
            if d[g[v][i][0]]!=(d[v]+g[v][i][1]):
              ss="No"
for i in range(m):
  if d[s[i]]==-1:
     d[s[i]]=0
     dfs(s[i])
print(ss)

Submission status: Runtime Error

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

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

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

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

def check(y):
    for z,d in a[y]:
        if x[z] == None:
            x[z] = x[y] + d
            return check(z)
        elif x[z] != x[y] + d:
            return False
    return True

for i in range(n):
    if x[i] == None:
        x[i] = 0
        if not check(i):
            print('No')
            exit(0)
print('Yes')

Submission status: Runtime Error

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

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

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

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

def check(y):
    for z,d in a[y]:
        if x[z] == None:
            x[z] = x[y] + d
            return check(z)
        elif x[z] != x[y] + d:
            return False
    return True

for i in range(n):
    if x[i] == None:
        x[i] = 0
        if not check(i):
            print('No')
            break
else:
    print('Yes')

Submission status: Runtime Error

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

a = [[] for _ in range(n+1)]

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

x = [float('inf') for _ in range(n+1)]

flag = [True]



def check(start,destination,cost):
    #x[destination] = x[start] + cost
    if x[destination] == float('inf'):
        x[destination] = x[start] + cost
        while a[destination]:
            n_destination, n_cost = a[destination].pop()
            check(destination,n_destination,n_cost)
    else:
        if x[destination] == x[start] + cost:
            while a[destination]:
                n_destination, n_cost = a[destination].pop()
                check(destination,n_destination,n_cost)
        else:
            flag[0] = False

for i in range(1,n+1):
    if x[i] == float('inf'):
        x[i] = 0
        for y in a[i]:
            check(i,y[0],y[1])
    else:
        pass

if flag[0]:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

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

a = [[] for _ in range(n+1)]

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

x = [float('inf') for _ in range(n+1)]

flag = [True]



def check(start,destination,cost):
    #x[destination] = x[start] + cost
    if x[destination] == float('inf'):
        x[destination] = x[start] + cost
        while a[destination]:
            n_destination, n_cost = a[destination].pop()
            check(destination,n_destination,n_cost)
    else:
        if x[destination] == x[start] + cost:
            while a[destination]:
                n_destination, n_cost = a[destination].pop()
                check(destination,n_destination,n_cost)
        else:
            flag[0] = False

for i in range(1,n+1):
    if a[i]:
        x[i] = 0
        for y in a[i]:
            check(i,y[0],y[1])
    else:
        pass

if flag[0]:
    print('Yes')
else:
    print('No')

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(100000)


def check(i, xs, checked):
    xi = xs[i]
    children = set()
    for j, d in links[i]:
        if checked[j]:
            continue
        if j not in xs:
            xs[j] = xi + d
        elif xi + d != xs[j]:
            return False
        children.add(j)
    checked[i] = True
    return all(check(j, xs, checked) for j in children)


def solve():
    checked = [False] * n
    for i in range(n):
        if not checked[i]:
            xs = {}
            xs[i] = 0
            if not check(i, xs, checked):
                return False
    return True


n, m = map(int, input().split())
links = [set() for _ in range(n)]
for _ in range(m):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    links[l].add((r, d))
    links[r].add((l, -d))
print('Yes' if solve() else 'No')

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


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


def check(v):
    for next_v, d in g[v]:
        if ds[next_v] is None:
            ds[next_v] = ds[v] + d
            if check(next_v) is False:
                return False
        elif not (ds[next_v] - ds[v] == d):
            return False
    return True


valid = True
for v in range(1, n + 1):
    if ds[v] is None:
        ds[v] = 0
    if check(v):
        valid = False
        break

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


checked = {}
ds = [None for _ in range(n + 1)]


def check(v):
    for next_v, d in g[v]:
        if ds[next_v] is None:
            ds[next_v] = ds[v] + d
            if check(next_v) is False:
                return False
        elif not (ds[next_v] - ds[v] == d):
            return False
    return True


valid = True
for v in range(1, n + 1):
    if ds[v] is None:
        ds[v] = 0
    if check(v):
        valid = False
        break

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


checked = {}
ds = defaultdict(int)


def check(v):
    for next_v, d in g[v]:
        if not (next_v in ds):
            ds[next_v] = ds[v] + d
            if check(next_v) is False:
                return False
        elif not (ds[next_v] - ds[v] == d):
            return False
    return True


valid = True
for v in range(1, n + 1):
    if (not (v in ds)):
        ds[v] = 0
    if check(v):
        valid = False
        break

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


checked = {}
ds = defaultdict(int)


def check(v):
    if (not (v in ds)):
        ds[v] = 0
    for next_v, d in g[v]:
        if not (next_v in ds):
            ds[next_v] = ds[v] + d
            if check(next_v) is False:
                return False
        elif not (ds[next_v] - ds[v] == d):
            return False
    return True


valid = True
for v in range(1, n + 1):
    if check(v):
        valid = False
        break

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


checked = {}
ds = defaultdict(int)


def check(v):
    if (not (v in ds)):
        ds[v] = 0
    if v in checked:
        return True
    checked[v] = True
    for next_v, d in g[v]:
        if not (next_v in ds):
            ds[next_v] = ds[v] + d
        if not (ds[next_v] - ds[v] == d):
            return False
        elif check(next_v) is False:
            return False
    return True


valid = True
for v in range(1, n + 1):
    if v in checked:
        continue
    valid &= check(v)

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict


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

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


checked = {}
ds = defaultdict(int)


def check(v, cur_d=0):
    if (not (v in ds)):
        ds[v] = cur_d
    if v in checked:
        return True
    checked[v] = True
    for next_v, d in g[v]:
        if not (next_v in ds):
            ds[next_v] = ds[v] + d
        if not (ds[next_v] - ds[v] == d):
            return False
        elif check(next_v) is False:
            return False
    return True


valid = True
for v in range(1, n + 1):
    if v in checked:
        continue
    valid &= check(v)

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

Submission status: Runtime Error

Solution code:
pos = [[] for i in range(100002)]
por = [[] for s in range(200004)]
posvis = [[1] for y in range(100002)]
qe = []
n, m = map(int, input().split())
for i in range(m):
    l, r, d = map(int, input().split())
    pos[l].append([r, d, i])
    pos[r].append([l, -d, i])
    qe.append([l, r, d])


def deep(self, vis=1):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if vis:
                por[self] = [100001]
            if len(set(por[self])) > 1:
                print("No")
                exit()
                por[j[0]].append(por[self][0] + j[1])
            por[j[0]].append(por[self][0] + j[1])
            deep(j[0], 0)

for qww in qe:
    if posvis[qww[0]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
pos = [[] for i in range(600010)]
por = [[] for s in range(600010)]
posvis = [1 for y in range(600010)]
qe = []
n, m = map(int, input().split())
for i in range(m):
    l, r, d = map(int, input().split())
    pos[l].append([r, d, i])
    pos[r].append([l, -d, i])
    qe.append([l, r, i])
 
 
def deep(self):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if len(por[self]) < 1:
                por[self] = [100000]
            if len(set(por[self])) > 1:
                print("No")
                exit()
            por[j[0]].append(por[self][0] + j[1])
            por[j[0]] = list(set(por[j[0]]))
            if len(set(por[j[0]])) > 1:
                print("No")
                exit()
            deep(j[0])
for qww in qe:
    if posvis[qww[2]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
pos = [[] for i in range(600010)]
por = [[] for s in range(600010)]
posvis = [1 for y in range(600010)]
qe = []
n, m = map(int, input().split())
for i in range(m):
    l, r, d = map(int, input().split())
    pos[l].append([r, d, i])
    pos[r].append([l, -d, i])
    qe.append([l, r, i])
 
 
def deep(self):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if len(por[self]) < 1:
                por[self] = [100000]
            if len(set(por[self])) > 1:
                print("No")
                exit()
            por[j[0]].append(por[self][0] + j[1])
            por[j[0]] = set(por[j[0]])
            if len(set(por[j[0]])) > 1:
                print("No")
                exit()
            deep(j[0])
for qww in qe:
    if posvis[qww[2]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
pos = [[] for i in range(600010)]
por = [[] for s in range(600010)]
posvis = [1 for y in range(600010)]
qe = []
n, m = map(int, input().split())
for i in range(m):
    l, r, d = map(int, input().split())
    pos[l].append([r, d, i])
    pos[r].append([l, -d, i])
    qe.append([l, r, i])
 
 
def deep(self):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if len(por[self]) < 1:
                por[self] = [100000]
            if len(set(por[self])) > 1:
                print("No")
                exit()
            por[j[0]].append(por[self][0] + j[1])
            if len(set(por[j[0]])) > 1:
                print("No")
                exit()
            deep(j[0])
for qww in qe:
    if posvis[qww[2]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")

Submission status: Runtime Error

Solution code:
pos = [[] for i in range(600010)]
por = [[] for s in range(600010)]
posvis = [1 for y in range(600010)]
qe = []
n, m = map(int, input().split())
for i in range(m):
    l, r, d = map(int, input().split())
    pos[l].append([r, d, i])
    pos[r].append([l, -d, i])
    qe.append([l, r, i])
 
 
def deep(self):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if len(por[self]) < 1:
                por[self] = [100000]
            if len(set(por[self])) > 1:
                print("No")
                exit()
            por[j[0]].append(por[self][0] + j[1])
            deep(j[0])
for qww in qe:
    if posvis[qww[2]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")