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:
#!/usr/bin/env python3

def main():
    na = list(map(int, input().split()))
    N = na[0]
    M = na[1]
    lrd_list = []
    for i in range(M):
        na = list(map(int, input().split()))
        lrd_list.append((na[0], na[1], na[2]))

    tpl_list = []
    for lrd in lrd_list:
        l = lrd[0]
        r = lrd[1]
        l_idx = r_idx = -1
        for i, tpl in enumerate(tpl_list):
            if l_idx == -1 and l in tpl[0]:
                l_idx = i
            if r_idx == -1 and r in tpl[0]:
                r_idx = i
            if l_idx != -1 and r_idx != -1:
                break
        if 0 <= l_idx and 0 <= r_idx:
            if l_idx == r_idx:
                tpl_list[l_idx][1].append(lrd)
            else:
                tpl_l = tpl_list[l_idx]
                tpl_r = tpl_list.pop(r_idx)
                tpl_l[0] |= tpl_r[0]
                tpl_l[1].append(lrd)
                tpl_l[1] += tpl_r[1]
        elif 0 <= l_idx:
            tpl_list[l_idx][0].add(r)
            tpl_list[l_idx][1].append(lrd)
        elif 0 <= r_idx:
            tpl_list[r_idx][0].add(l)
            tpl_list[r_idx][1].append(lrd)
        else:
            tpl_list.append((set([l, r]), [lrd]))

    positions = [None for i in range(N+1)]
    consistent = True
    for tpl in tpl_list:
        for lrd in tpl[1]:
            l, r, d = lrd
            if positions[l] is None and positions[r] is None:
                positions[l] = 0
                positions[r] = d
            elif positions[l] is None:
                positions[l] = positions[r] - d
            elif positions[r] is None:
                positions[r] = positions[l] + d
            else:
                if positions[l] + d != positions[r]:
                    consistent = False
                    break
        if not consistent:
            break


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

def main():
    na = list(map(int, input().split()))
    N = na[0]
    M = na[1]
    lrd_list = []
    for i in range(M):
        na = list(map(int, input().split()))
        lrd_list.append((na[0], na[1], na[2]))

    tpl_list = []
    for i, lrd in enumerate(lrd_list):
        l = lrd[0]
        r = lrd[1]
        l_idx = r_idx = -1
        for i, tpl in enumerate(tpl_list):
            if l_idx == -1 and l in tpl[0]:
                l_idx = i
            if r_idx == -1 and r in tpl[0]:
                r_idx = i
            if l_idx != -1 and r_idx != -1:
                break
        if 0 <= l_idx and 0 <= r_idx:
            if l_idx == r_idx:
                tpl_list[l_idx][1].append(lrd)
            else:
                tpl_l = tpl_list[l_idx]
                tpl_r = tpl_list.pop(r_idx)
                tpl_l[0] |= tpl_r[0]
                tpl_l[1].append(lrd)
                tpl_l[1] += tpl_r[1]
        elif 0 <= l_idx:
            tpl_list[l_idx][0].add(r)
            tpl_list[l_idx][1].append(lrd)
        elif 0 <= r_idx:
            tpl_list[r_idx][0].add(l)
            tpl_list[r_idx][1].append(lrd)
        else:
            tpl_list.append((set([l, r]), [lrd]))

    positions = [None for i in range(N+1)]
    consistent = True
    for tpl in tpl_list:
        for lrd in tpl[1]:
            l, r, d = lrd
            if positions[l] is None and positions[r] is None:
                positions[l] = 0
                positions[r] = d
            elif positions[l] is None:
                positions[l] = positions[r] - d
            elif positions[r] is None:
                positions[r] = positions[l] + d
            else:
                if positions[l] + d != positions[r]:
                    consistent = False
                    break
        if not consistent:
            break


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

def main():
    na = list(map(int, input().split()))
    N = na[0]
    M = na[1]
    lrd_list = []
    for i in range(M):
        na = list(map(int, input().split()))
        lrd_list.append((na[0], na[1], na[2]))

    tpl_list = []
    for i, lrd in enumerate(lrd_list):
        l = lrd[0]
        r = lrd[1]
        l_idx = r_idx = -1
        for i, tpl in enumerate(tpl_list):
            if l_idx == -1 and l in tpl[0]:
                l_idx = i
            if r_idx == -1 and r in tpl[0]:
                r_idx = i
            if l_idx != -1 and r_idx != -1:
                break
        if 0 <= l_idx and 0 <= r_idx:
            if l_idx == r_idx:
                tpl_list[l_idx][1].append(lrd)
            else:
                tpl = tpl_list.pop(r_idx)
                tpl_list[l_idx][0] |= tpl[0]
                tpl_list[l_idx][1].append(lrd)
                tpl_list[l_idx][1] += tpl[1]
        elif 0 <= l_idx:
            tpl_list[l_idx][0].add(r)
            tpl_list[l_idx][1].append(lrd)
        elif 0 <= r_idx:
            tpl_list[r_idx][0].add(l)
            tpl_list[r_idx][1].append(lrd)
        else:
            tpl_list.append((set([l, r]), [lrd]))

    positions = [None for i in range(N+1)]
    consistent = True
    for tpl in tpl_list:
        for lrd in tpl[1]:
            l, r, d = lrd
            if positions[l] is None and positions[r] is None:
                positions[l] = 0
                positions[r] = d
            elif positions[l] is None:
                positions[l] = positions[r] - d
            elif positions[r] is None:
                positions[r] = positions[l] + d
            else:
                if positions[l] + d != positions[r]:
                    consistent = False
                    break
        if not consistent:
            break


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


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

"""
参考：https://www.hamayanhamayan.com/entry/2018/01/28/231916
・深さ優先
・幅優先とほとんど一緒だけど練習用にこっちも書いた。
"""

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

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

# 訪問済メモ
visited = [0] * N

def dfs(cur):
    visited[cur] = 1
    # 左から見た右側を確認
    for r, d in l_edges[cur]:
        # 訪問済なら矛盾がないか検証する
        if visited[r]:
            if pos[r] - pos[cur] != d:
                print('No')
                exit()
        # 未訪問なら今回の情報を記録する
        else:
            visited[r] = 1
            pos[r] = pos[cur] + d
            # 確認した位置を次の現在位置として見に行く
            dfs(r)
    # 右から見た左側を確認
    for l, d in r_edges[cur]:
        if visited[l]:
            if pos[cur] - pos[l] != d:
                print('No')
                exit()
        else:
            visited[l] = 1
            pos[l] = pos[cur] - d
            dfs(l)

for i in range(N):
    # 訪問済(確認済)でなければ走破しに行く
    if not visited[i]:
        # この開始位置を基準とした相対位置を記録する
        pos = {i: 0}
        dfs(i)
        pos = {}
# 最後まで矛盾がなければOK
print('Yes')

Submission status: Runtime Error

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

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

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            if w != self.diff(x, y):
                print("No")
                exit()

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

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

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

import sys
sys.setrecursionlimit(10**8)
N, M = map(int, input().split())
lrd = []
for i in range(M):
    l, r, d = map(int, input().split())
    lrd.append([l, r, d])
w_union_find = WeightedUnionFind(N)
for i in range(M):
    l, r, d = lrd[i]
    w_union_find.union(l, r, d)
print("Yes")

Submission status: Runtime Error

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

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

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            if w != self.diff(x, y):
                print("No")
                exit()

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

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

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

import sys
sys.setrecursionlimit(10**8)
N, M = map(int, input().split())
w_union_find = WeightedUnionFind(N)
for i in range(M):
    l, r, d = map(int, input().split())
    w_union_find.union(l, r, d)
print("Yes")

Submission status: Runtime Error

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

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

    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        if rx == ry:
            if w != self.diff(x, y):
                print("No")
                exit()

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

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

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


N, M = map(int, input().split())
w_union_find = WeightedUnionFind(N)
lrd = []
for i in range(M):
    l, r, d = map(int, input().split())
    w_union_find.union(l, r, d)
print("Yes")

Submission status: Runtime Error

Solution code:
import numpy as np

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

if m == 0:
    print("Yes")
    exit(0)

aarray = np.zeros((m,n))
barray = np.zeros((m,n+1))

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

rank1 = int(np.linalg.matrix_rank(aarray))
rank2 = int(np.linalg.matrix_rank(barray))
if rank1 == rank2:
    print("Yes")
else:
    print("No")

Submission status: Runtime Error

Solution code:
import sys

def DFS(graph,start,visited):
    visited[start]=1
    start_num=graph[start][0]

    for edge in graph[start][1]:
        if(visited[edge[0]]==0):
            graph[edge[0]][0]=start_num+edge[1]
            if(DFS(graph,edge[0],visited)==0):
                return 0
        else:
            if(start_num+edge[1]!=graph[edge[0]][0]):
                return 0
    
    return 1
            






n,m=map(int,input().split())
visited={}
for i in range(n):
    visited[i+1]=0

graph={}
for i in range(1,n+1):
    graph[i]=[0,[]]
graph[1][0]=0

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

for i in range(1,n+1):
    if(visited[i]==0):
        if(DFS(graph,i,visited)==0):
            print("No")
            sys.exit()


print("Yes")

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    global X, G
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        else:
            if X[w] != X[u] + d:
                return False

    return True


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

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    global X, G
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        elif X[w] - X[u] != d:
            return False

    return True


flag = True
for i, x in enumerate(X):
    if x is None:
        X[i] = 0
        flag &= dfs(i)

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

Submission status: Runtime Error

Solution code:
import sys
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            f = dfs(w)
            if not f:
                return False
        elif X[w] - X[u] != d:
            return False

    return True


for i, x in enumerate(X):
    if x is None:
        X[i] = 0
        f = dfs(i)
        if not f:
            print("No")
            sys.exit(0)

print("Yes")

Submission status: Runtime Error

Solution code:
import sys
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, q = map(int, input().split())
    G[l - 1].append((r - 1, q))
    G[r - 1].append((l - 1, -q))
X = [None] * N


def dfs(u):
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        elif X[w] - X[u] != d:
            return False

    return True


for i, x in enumerate(X):
    if x is None:
        X[i] = 0
        if not dfs(i):
            print("No")
            sys.exit(0)

print("Yes")

Submission status: Runtime Error

Solution code:
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))
X = [None] * N


def dfs(u):
    for w, d in G[u]:
        if X[w] is None:
            X[w] = X[u] + d
            if not dfs(w):
                return False
        elif X[w] - X[u] != d:
            return False

    return True


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

print("Yes")

Submission status: Runtime Error

Solution code:
from collections import defaultdict
N, M = map(int, input().split())
G = defaultdict(list)
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * (N + 1)
dist = [0] * (N + 1)
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

    if v in G:
        for w, d1 in G[v]:
            dfs(w, d0 + d1)


for i in range(1, N + 1):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N + 1)]
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * (N + 1)
dist = [0] * (N + 1)
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

    if len(G[v]) != 0:
        for w, d1 in G[v]:
            dfs(w, d0 + d1)


for i in range(1, N + 1):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N + 1)]
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * (N + 1)
dist = [0] * (N + 1)
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

    for w, d1 in G[v]:
        dfs(w, d0 + d1)


for i in range(1, N + 1):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
def insert(L,R,D,

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N + 1)]
for i in range(M):
    l, r, d = map(int, input().split())
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * (N + 1)
dist = [0] * (N + 1)
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

    for w, d1 in G[v]:
        dfs(w, d0 + d1)


for i in range(1, N + 1):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * N
dist = [0] * N
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

    for w, d1 in G[v]:
        dfs(w, d0 + d1)


for i in range(N):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * N
dist = [0] * N
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
        return
    else:
        used[v] = True
        dist[v] = d0

        for w, d1 in G[v]:
            dfs(w, d0 + d1)


for i in range(N):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
N, M = map(int, input().split())
G = [[] for i in range(N)]
for i in range(M):
    l, r, d = map(int, input().split())
    l, r = l - 1, r - 1
    G[l].append((r, d))
    G[r].append((l, -d))
used = [False] * N
dist = [0] * N
flag = False


def dfs(v, d0):
    global flag
    if used[v]:
        if dist[v] != d0:
            flag = True
            return
    else:
        used[v] = True
        dist[v] = d0

        for w, d1 in G[v]:
            dfs(w, d0 + d1)


for i in range(N):
    if not used[i]:
        dfs(i, 0)

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

Submission status: Runtime Error

Solution code:
# coding:utf-8

import sys

input = sys.stdin.readline
INF = float('inf')


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


def show(X):
    for row in X:
        print(row)


def solve(N, M, info):
    distance = {}
    for L, R, D in info:
        if L not in distance.keys():
            distance[L] = {}
        if R in distance[L].keys():
            if D != distance[L][R]:
                return 'No'
            else:
                continue
        distance[L][R] = D

    for L, R, D in info:
        if L + 1 == R:
            continue
        if R - 1 not in distance[L].keys() or R not in distance[L + 1].keys():
            continue
        if distance[L][R - 1] + distance[L + 1][R] != D:
            break
    else:
        return 'Yes'
    return 'No'


N, M = inpl()
info = []
for i in range(M):
    L, R, D = inpl()
    if L > R:
        L, R = R, L
        D = -D
    info.append([L - 1, R - 1, D])

print(solve(N, M, info))

Submission status: Runtime Error

Solution code:
# coding:utf-8

import sys

input = sys.stdin.readline
INF = float('inf')


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


def show(X):
    for row in X:
        print(row)


def solve(N, M, info):
    distance = {}
    for L, R, D in info:
        if L not in distance.keys():
            distance[L] = {}
        distance[L][R] = D
    for L, R, D in info:
        if L + 1 == R:
            continue
        if R - 1 not in distance[L].keys() or R not in distance[L + 1].keys():
            continue
        if distance[L][R - 1] + distance[L + 1][R] != D:
            break
    else:
        return 'Yes'
    return 'No'


N, M = inpl()
info = []
for i in range(M):
    L, R, D = inpl()
    if L > R:
        L, R = R, L
        D = -D
    info.append([L - 1, R - 1, D])

print(solve(N, M, info))

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

N, M = map(int, input().split())
L, R, D = [None] * M, [None] * M, [None] * M
for i in range(M):
    L[i], R[i], D[i] = map(int, input().split())

x = {}
if M > 0:
    x[L[0]] = 0
ans = 'Yes'
for l, r, d in zip(L, R, D):
    if l in x and r in x:
        if x[r] - x[l] != d:
            ans = 'No'
            break
    elif l in x:
        x[r] = x[l] + d
    elif r in x:
        x[l] = x[r] - d
    else:
        raise Exception
print(ans, x)

Submission status: Runtime Error

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

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

lines = input().splitlines()

for line in lines:
    l, r, d = map(int, line.split())
    graph[l - 1].append(( d,r - 1))
    graph[r - 1].append((-d,l - 1))

INF = float("inf")
dist = [-INF]*n

# 未探索ノードの距離を0とする
for n in range(n):
    if dist[n] != -INF:
        continue
    else:
        stack = [n]
        dist[n] = 0
        
    # stackが空になるまで探索を繰り返す
    while len(stack):
        cur = stack.pop()
        
        # ノードcurと隣り合う未探索ノードをstackに追加
        for cost, nex_node in graph[cur]:
            if dist[nex_node] != -INF:
                continue
            else:
                dist[nex_node] = dist[cur] + cost
                stack.append(nex_node)

flag = True
for i in range(n):
    if not flag:
        break
    for d,node in graph[i]:
        if dist[node]-dist[i] != d:
            print("No")
            flag = False

if flag:
    print("Yes")

Submission status: Runtime Error

Solution code:
from collections import deque

class MakeGraph:
    
    # 隣接行列もしくは隣接リストの初期化
    # node_num：ノード数
    # isMat：隣接行列(True) / 隣接リスト(False)
    def __init__(self, node_num:int, isMat:bool) -> None:
        self.n = node_num
        self.isMat = isMat

        # 隣接行列の初期化
        if self.isMat:
            INF = float("inf")
            self.graph = [[INF for _ in range(self.n)] for _ in range(self.n)]
    
        # 隣接リストの初期化
        else:
            self.graph = [[] for _ in range(self.n)]

    # エッジの追加
    # frm, to：起点ノード, 終点ノード
    # dist：frm→toへのコスト
    def add_undr_edge_mat(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm][to] = dist
        self.graph[to][frm] = dist
        
    def add_drct_edge_mat(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm][to] = dist
        
    def add_undr_edge_lst(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm].append((dist, to))
        self.graph[to].append((dist, frm))
        
    def add_drct_edge_lst(self, frm:int, to:int, dist:int) -> None:
        self.graph[frm].append((dist, to))

                
    # 完成したグラフを取り出す
    def get_graph(self) -> list:
        return self.graph


class DfsAndBfs:
 
  # グラフは隣接リスト 0-originであることに注意
  # graph[i]はi番目のノードと隣り合うノードの(距離, ノード番号)を格納している
  # 例：0番と3番の距離が7 -> graph[0] = [[(7,3)]] 
  @classmethod
  def dfs(cls, graph:list, node:int) -> list:
    # 未探索のノードは距離を-1とする
    INF = float("inf")
    dist = [-INF]*node  
    
    # 未探索ノードの距離を0とする
    for n in range(node):
        if dist[n] != -INF:
            continue
        else:
            stack = [n]
            dist[n] = 0
            
        # stackが空になるまで探索を繰り返す
        while len(stack):
            cur = stack.pop()
            
            # ノードcurと隣り合う未探索ノードをstackに追加
            for cost, nex_node in graph[cur]:
                if dist[nex_node] != -INF:
                    continue
                else:
                    dist[nex_node] = dist[cur] + cost
                    stack.append(nex_node)

    return dist
 
  
  # グラフは隣接リスト 0-originであることに注意
  # graph[i]はi番目のノードと隣り合うノードの(距離, ノード番号)を格納している
  # 例：0番と3番の距離が7 -> graph[0] = [[(7,3)]]
  @classmethod
  def bfs(cls, graph:list, node:int) -> list:
      # 未探索のノードは距離を-1とする
      INF = float("inf")
      dist = [-INF]*node

      # 未探索ノードの距離を0とする
      for n in range(node):
          if dist[n] != -INF:
              continue
          else:
              que = deque([n])
              dist[n] = 0

          # queが空になるまで探索を繰り返す
          while len(que):
              cur = deque.popleft(que)

              # ノードcurと隣り合う未探索ノードをqueに追加
              for cost, nex_node in graph[cur]:
                  if dist[nex_node] != -INF:
                      continue
                  else:
                      dist[nex_node] = dist[cur] + cost
                      que.append(nex_node)

      return dist
  
file = open("sampleABC087D.txt", "r")

N,M = map(int ,file.readline().split())
LRD = []
for i in range(M):
    LRD.append(tuple(map(int ,file.readline().split())))

graphMaker = MakeGraph(N, False)
add_edge = graphMaker.add_drct_edge_lst
for l,r,d in LRD:
    add_edge(l-1,r-1,d)
    add_edge(r-1,l-1,-d)
    
graph = graphMaker.get_graph()

dist = DfsAndBfs.dfs(graph, N)



consistent = True

for l,r,d in LRD:
    if dist[r-1] - dist[l-1] == d:
        continue
    else:
        consistent = False
        break

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

Submission status: Runtime Error

Solution code:
def search(i, total):
  for dist, to in edges[i]:
    if dists[to] == None:
      dists[to] = total + dist
      if not search(to, total + dist):
        return False
    else:
      if dists[to] == total + dist:
        continue
      else:
        return False
  return True

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

dists = [None] * n

for i in range(n):
  if dists[i] == None:
    dists[i] = 0
    if not search(i, 0):
      print("No")
      break
else:
  print("Yes")