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: Time Limit Exceeded

Solution code:
import heapq

INF = float('inf')


class UnionFind:
    def __init__(self, size: int):
        self.__size = size
        self.__root = [-1] * size

    def find(self, u: int)->int:
        if self.__root[u] < 0:
            return u
        self.__root[u] = self.find(self.__root[u])
        return self.__root[u]

    def same(self, u: int, v: int)->bool:
        return self.find(u) == self.find(v)

    def unite(self, u: int, v: int):
        x, y = self.find(u), self.find(v)

        if x == y:
            return

        if self.__root[y] < self.__root[x]:
            x, y = y, x

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

    def print(self):
        print(self.__root)


class PriorityQueue:
    def __init__(self):
        self.__queue = []
        self.__count = 0

    def enqueue(self, v):
        self.__count += 1
        heapq.heappush(self.__queue, v)

    def dequeue(self):
        self.__count -= 1
        return heapq.heappop(self.__queue)

    def is_empty(self)->bool:
        return self.__count == 0


def dijkstra(V: int, E: list, s: int, t: int)->int:
    '''dijkstra 法を使って u -> v の距離を求める。
    :param V: 頂点数
    :param E: 辺の集合
    :param s: 始点
    :param t: 終点
    :return: 距離
    '''
    d = [INF] * (V)
    d[s] = 0

    q = PriorityQueue()
    for v in range(V):
        q.enqueue((d[v], v))

    while not q.is_empty():
        _, u = q.dequeue()
        for v, c in E[u]:
            if d[u] + c < d[v]:
                d[v] = d[u] + c
                q.enqueue((d[v], v))

    return d[t]


def people_on_a_line(N: int, M: int, queries: list)->bool:
    E = [[] for _ in range(N)]
    uf = UnionFind(N)
    for l, r, d in queries:
        if uf.same(l-1, r-1):
            if d != dijkstra(N, E, l-1, r-1):
                return False
        else:
            uf.unite(l-1, r-1)
            E[l-1].append((r-1, d))
            E[r-1].append((l-1, -d))

    return True


if __name__ == "__main__":
    M = 0
    N, M = map(int, input().split())
    queries = [tuple(int(s) for s in input().split()) for _ in range(M)]
    yes = people_on_a_line(N, M, queries)
    print('Yes' if yes else 'No')

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = float('inf')


class PriorityQueue:
    def __init__(self):
        self.__queue = []
        self.__count = 0

    def enqueue(self, v):
        self.__count += 1
        heapq.heappush(self.__queue, v)

    def dequeue(self):
        self.__count -= 1
        return heapq.heappop(self.__queue)

    def is_empty(self)->bool:
        return self.__count == 0


def dijkstra(V: int, E: list, s: int, t: int)->int:
    '''dijkstra 法を使って u -> v の距離を求める。
    :param V: 頂点数
    :param E: 辺の集合
    :param s: 始点
    :param t: 終点
    :return: 距離
    '''
    d = [INF] * (V)
    d[s] = 0

    q = PriorityQueue()
    for v in range(V):
        q.enqueue((d[v], v))

    while not q.is_empty():
        _, u = q.dequeue()
        for v, c in E[u]:
            if d[u] + c < d[v]:
                d[v] = d[u] + c
                q.enqueue((d[v], v))

    return d[t]


def people_on_a_line(N: int, M: int, queries: list)->bool:
    E = [[] for _ in range(N)]
    for l, r, d in queries:
        cur_d = dijkstra(N, E, l-1, r-1)
        if cur_d == INF:
            E[l-1].append((r-1, d))
            E[r-1].append((l-1, d))
        else:
            if cur_d != d:
                return False
    return True


if __name__ == "__main__":
    M = 0
    N, M = map(int, input().split())
    queries = [tuple(int(s) for s in input().split()) for _ in range(M)]
    yes = people_on_a_line(N, M, queries)
    print('Yes' if yes else 'No')

Submission status: Time Limit Exceeded

Solution code:
import sys
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        # 根への距離を管理
        self.weight = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            # 親への重みを追加しながら根まで走査
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    # 併合
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        # xの木の高さ < yの木の高さ
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        # xの木の高さ ≧ yの木の高さ
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            # 木の高さが同じだった場合の処理
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

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

    # xからyへのコスト
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

def main():
    max_v, max_e =  map(int, sys.stdin.readline().split())
    uf = WeightedUnionFind(max_v)
    k = []
    s = 0
    for i in range(max_e):
        a,b,w=  map(int, sys.stdin.readline().split())
        if (a in k and b in k) and uf.diff(a,b) != w:
            #print(uf.diff(a,b) , w)
            s =1
        else:uf.union(a,b,w)
        if a not in k:
            k.append(a)
        if b not in k:
            k.append(b)
    if s == 0:
        print("Yes")
    else:
        print("No")

 
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        # 根への距離を管理
        self.weight = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            # 親への重みを追加しながら根まで走査
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    # 併合
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        # xの木の高さ < yの木の高さ
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        # xの木の高さ ≧ yの木の高さ
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            # 木の高さが同じだった場合の処理
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

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

    # xからyへのコスト
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]

def main():
    max_v, max_e = map(int, input().split())
    uf = WeightedUnionFind(max_v)
    k = []
    s = 0
    for i in range(max_e):
        a,b,w= map(int, input().split())
        if (a in k and b in k) and uf.diff(a,b) != w:
            #print(uf.diff(a,b) , w)
            s =1
        else:uf.union(a,b,w)
        if a not in k:
            k.append(a)
        if b not in k:
            k.append(b)
    if s == 0:
        print("Yes")
    else:
        print("No")

 
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#連立方程式が解けるか否かを決める
#numpyでやってみる
#rank(A)=rank(Ab)ならば解ける、その他は不可
import numpy as np
N,M = map(int, input().split())
a_list = []
ab_list = []
l_list = []
r_list = []
d_list = []
for i in range(M):
    l,r,d = map(int, input().split())
    l_list.append(l)
    r_list.append(r)
    d_list.append(d)
    org_list = [0]*N
    org_list[l-1] = -1
    org_list[r-1] = 1
    a_list.append(org_list)
A = np.array(a_list)
for i in range(M):
    org_list = [0]*N
    org_list[l_list[i]-1] = -1
    org_list[r_list[i]-1] = 1
    org_list.append(d_list[i])
    ab_list.append(org_list)
Ab = np.array(ab_list)
if np.linalg.matrix_rank(A) == np.linalg.matrix_rank(Ab):
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
class vertex : 
    def __init__(self) : 
        self.edges = []

    def add_edge(self, u, weight) : 
        self.edges.append((u, weight))


def dfs(graph, V, s) : 
    for node in s : 
        travelled = [0 for _ in xrange(V)]
        if travelled[node] : 
            continue
        
        stack = []
        stack.append((node, 0))

        while stack : 
            index, full_weight = stack.pop()

            for dst, weight in graph[index].edges :
                if travelled[dst] :
                    if travelled[dst] != travelled[index] + weight : 
                        return False
                    continue
                
                travelled[dst] = travelled[index] + weight
                stack.append((dst, travelled[index] + weight))

    
    return True


V, E = map(int, raw_input().strip().split(' '))

graph = [vertex() for _ in xrange(V)]

memo  = [False for _ in xrange(V)]
s     = set([])
for _ in xrange(E) : 
    l, r, d = map(int, raw_input().strip().split(' '))
    l -= 1
    r -= 1
    graph[l].add_edge(r, d)
    memo[r] = True
    s.add(l)
    s.add(r)


if dfs(graph, V, s) :
    print "Yes"
else : 
    print "No"

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

graph = [[] for i in range(N)]

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

#print(graph)
x = [None for i in range(N)]

def f():
    for i in range(N):
        if x[i] == None:
            x[i] = 0
            q = deque([i])
            while len(q):
                j = q.popleft()
                for k,d in graph[j]:
                    if x[k] == None:
                        q.append(k)
                        x[k] = x[j]+d
                    elif x[k] != x[j]+d:
                        return False
                        
    return True

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

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())

Dlist = [[0 for i in range(N+1)] for j in range(N+1)]

L2Rdic = {i:[] for i in range(N+1)}
R2Ldic = {i:[] for i in range(N+1)}

flag=True

for _ in range(M):
    L,R,D=map(int,input().split())

    if Dlist[L][R]==0:
        Dlist[L][R]=D
        L2Rdic[L].append(R)
        R2Ldic[R].append(L)
    elif Dlist[L][R]!=D:
        flag=False

    for r in L2Rdic[R]:
        if Dlist[L][r]==0:
            Dlist[L][r]=D+Dlist[R][r]
            L2Rdic[L].append(r)
            R2Ldic[r].append(L)
        elif Dlist[L][r]!=D+Dlist[R][r]:
            flag=False

    for l in R2Ldic[L]:
        if Dlist[l][R]==0:
            Dlist[l][R]=Dlist[l][L]+D
            L2Rdic[l].append(R)
            R2Ldic[R].append(l)
        elif Dlist[l][R]!=Dlist[l][L]+D:
            flag=False

    if flag==False:
        print('No')
        exit()
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N, M = map(int, input().split())
L = []
R = []
D = []
G = [[] for _ in range(N+1)]
for _ in range(M):
    tmpl, tmpr, tmpd = map(int, input().split())
    # if tmpl > tmpr:
    #    tmpl, tmpr = tmpr, tmpl
    #    tmpd *= -1
    L.append(tmpl)
    R.append(tmpr)
    D.append(tmpd)
    G[tmpl].append((tmpr, tmpd))
    G[tmpr].append((tmpl, -tmpd))

field = [None] * (N+1)


def dfs(i):
    q = deque()
    q.append(i)
    field[i] = 0
    used = [False]*(N+1)
    used[i] = True
    while q:
        tmp = q.pop()
        for elem in G[tmp]:
            if used[elem[0]]:
                if field[elem[0]] is not None:
                    if field[elem[0]] != field[tmp]+elem[1]:
                        return False
                continue
            q.append(elem[0])
            if field[elem[0]] == None:
                field[elem[0]] = field[tmp]+elem[1]
                used[elem[0]] = True
            else:
                if field[elem[0]] != field[tmp]+elem[1]:
                    return False

    return True


for i in range(1, N+1):
    if field[i] == None:
        if not dfs(i):
            print('No')
            exit()
print('Yes')

Submission status: Time Limit Exceeded

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_list[l_idx] = (tpl_l[0] | tpl_r[0], tpl_l[1] + [lrd] + 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: Time Limit Exceeded

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

from collections import deque

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

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

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

def bfs(start):
    # この開始位置を基準とした相対位置を記録する
    pos = {start: 0}
    que = deque()
    que.append(start)
    visited[start] = 1
    while len(que) != 0:
        cur = que.popleft()
        # 辺のループ
        for l, r, d in edges:
            # 左から見た右側を確認
            if l == cur:
                # 訪問済なら矛盾がないか検証する
                if visited[r]:
                    if pos[r] - pos[l] != d:
                        print('No')
                        exit()
                # 未訪問なら今回の情報を記録する
                else:
                    visited[r] = 1
                    pos[r] = pos[l] + d
                    # 次回以降、開始位置として使うのでキューに詰める
                    que.append(r)
            # 右から見た左側を確認
            elif r == cur:
                if visited[l]:
                    if pos[r] - pos[l] != d:
                        print('No')
                        exit()
                else:
                    visited[l] = 1
                    pos[l] = pos[r] - d
                    que.append(l)

for i in range(N):
    # 訪問済(確認済)でなければ走破しに行く
    if not visited[i]:
        bfs(i)
# 最後まで矛盾がなければOK
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from pprint import pprint
import random
from collections import deque, defaultdict
N, M = map(int, input().split())

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

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

# N,M = 100000,200000
# LRD = [[i+10+random.randint(-9,100),i+20+random.randint(-18,200),random.randint(1,300)] for i in range(M)]
# print("run")

# 速めのdfs（非再帰）
graph = defaultdict(lambda: defaultdict(int))
# graph = [[0 for _ in range(N+1)] for _ in range(N+1)]
# graph = [defaultdict(int) for _ in range(N+1)]
visited = defaultdict()

for L,R,D in LRD:
    graph[L][R] = D
    graph[R][L] = -D
    visited[L] = None
    visited[R] = None

# print("step1")
# pprint(graph)

def xfs(v):
    que = deque()
    que.append((v,0))
    while len(que) > 0:
        i,cnt = que.pop()  # 深さ優先探索
        visited[i] = cnt
        # print("step3:i",i)
        for n,val in graph[i].items():
            if visited[n] == None:
                # print("if:v,i,n,cnt,val", v,i,n, cnt, val)
                que.append((n, cnt+val))
            else:
                # print("el:v,i,n,cnt,val,visited[n]",
                #       v, i, n, cnt, val, visited[n])
                if cnt + val != visited[n]:
                    return False

    return True


que2 = deque()
L, _, _ = LRD[0]
que2.append(L)
while len(que2) > 0:
    L = que2.pop()
    # print("step2:L",L)
    if xfs(L):
        for k,v in [(k,v) for k,v in visited.items() if v==None]:
            # print("step4:k", k)
            que2.append(k)
            break
    else:
        # pprint(visited)
        # print("L=",L)
        print("No")
        exit()

# pprint(visited)
print("Yes")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from pprint import pprint
from collections import deque, defaultdict
N, M = map(int, input().split())

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

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

# 速めのdfs（非再帰）
graph = defaultdict(lambda: defaultdict(int))
visited = defaultdict(bool)

for L,R,D in LRD:
    graph[L][R] = D
    graph[R][L] = -D
    visited[L] = False
    visited[R] = False

# pprint(graph)

def xfs(v):
    que = deque()
    # visited[v] = True
    vis_set = set([v])
    que.append((v,0,[v]))
    while len(que) > 0:
        i,cnt,vis = que.pop()  # 深さ優先探索
        for n,val in graph[i].items():
            if n not in vis:
            # if visited[n] == False:
                # visited[n] = True
                # print("if:v,i,n,cnt,val", v,i,n, cnt, val)
                vis_set.add(n)
                que.append((n, cnt+val,vis+[n]))
            elif n == v:
                # print("el:v,i,n,cnt,val", v,i,n, cnt, val)
                if cnt + val != 0:
                    return False

    for i in list(vis_set):
        visited[i] = True
    return True


que2 = deque()
L, _, _ = LRD[0]
que2.append(L)
while len(que2) > 0:
    L = que2.pop()
    if xfs(L):
        for k,v in [(k,v) for k,v in visited.items() if v==False]:
            que2.append(v)
            break
    else:
        # pprint(visited)
        # print("L=",L)
        print("No")
        exit()

# pprint(visited)
print("Yes")

Submission status: Time Limit Exceeded

Solution code:
class WeightsUnionfind:
  def __init__(self,n):
    self.Tree=[i for i in range(n)]
    self.dWeights=[0]*n
    self.wrong=0

  def find(self,x):
    if x==self.Tree[x]:
      return x
    else:
      root=self.find(self.Tree[x])
      self.dWeights[x]=self.weigh(x)
      self.Tree[x]=root
      return root
  
  def weigh(self,x):
    if x==self.Tree[x]:
      return 0
    else:
      w=self.weigh(self.Tree[x])+self.dWeights[x]
      return w

  def unite(self,x,y,w):
    s1=self.find(x)
    s2=self.find(y)
    if s1==s2:
      if self.weigh(y)-self.weigh(x)!=w:
        self.wrong=1
    else:
      self.Tree[s1]=s2
      self.dWeights[s1]=self.weigh(y)-self.weigh(x)-w
      
N,M=map(int,input().split())
wuf=WeightsUnionfind(N)
F=0
for m in range(M):
  l,r,d=map(int,input().split())
  wuf.unite(l-1,r-1,d)
if wuf.wrong==1:
  print("No")
else:
  print("Yes")

Submission status: Time Limit Exceeded

Solution code:
class WeightsUnionfind:
  def __init__(self,n):
    self.Tree=[i for i in range(n)]
    self.dWeights=[0]*n
    self.wrong=0

  def find(self,x):
    if x==self.Tree[x]:
      return x
    else:
      root=self.find(self.Tree[x])
      self.dWeights[x]=self.weigh(x)
      self.Tree[x]=root
      return root
  
  def weigh(self,x):
    if x==self.Tree[x]:
      return 0
    else:
      w=self.weigh(self.Tree[x])+self.dWeights[x]
      return w

  def unite(self,x,y,w):
    s1=self.find(x)
    s2=self.find(y)
    if s1==s2:
      if self.weigh(y)-self.weigh(x)!=w:
        self.wrong=1
    else:
      self.Tree[s1]=s2
      self.dWeights[s1]=self.weigh(y)-self.weigh(x)-w
      
N,M=map(int,input().split())
List=[[int(i) for i in input().split()] for i in range(M)] 
wuf=WeightsUnionfind(N)
F=0
for l in List:
  wuf.unite(l[0]-1,l[1]-1,l[2])
if wuf.wrong==1:
  print("No")
else:
  print("Yes")

Submission status: Time Limit Exceeded

Solution code:
class WeightsUnionfind:
  def __init__(self,n):
    self.Tree=[i for i in range(n)]
    self.dWeights=[0]*n

  def find(self,x):
    if x==self.Tree[x]:
      return x
    else:
      root=self.find(self.Tree[x])
      self.dWeights[x]=self.weigh(x)
      self.Tree[x]=root
      return root
  
  def weigh(self,x):
    if x==self.Tree[x]:
      return 0
    else:
      w=self.weigh(self.Tree[x])+self.dWeights[x]
      return w

  def unite(self,x,y,w):
    s1=self.find(x)
    s2=self.find(y)
    if s1==s2:
      pass
    else:
      self.Tree[s1]=s2
      self.dWeights[s1]=self.weigh(y)-self.weigh(x)-w
      
N,M=map(int,input().split())
List=[[int(i) for i in input().split()] for i in range(M)] 
wuf=WeightsUnionfind(N)
F=0
for l in List:
  wuf.unite(l[0]-1,l[1]-1,l[2])
for l in List:
  if wuf.weigh(l[1]-1)-wuf.weigh(l[0]-1)!=l[2]:
    F=1
    break
if F==1:
  print("No")
else:
  print("Yes")

Submission status: Time Limit Exceeded

Solution code:
import heapq
N, M = map(int, input().split())
S = [False] * N
G = [[] for i in range(N)]
def root(i):
  if R[i] == i:
    return i
  else:
    R[i] = root(R[i])
    return R[i]
loop = False
for i in range(M):
  l, r, d = map(int, input().split())
  G[l - 1].append([r - 1, d])
for i in range(N):
  if not S[i] and G[i]:
    _X = [None for i in range(N)]
    _X[i] = 0
    Q = []
    heapq.heappush(Q, [0, i])
    contract = False
    while Q:
      s = heapq.heappop(Q)
      S[s[1]] = True
      for adj, d in G[s[1]]:
        if _X[adj] == None:
          _X[adj] = s[0] + d
          if _X[adj] <= 10 ** 9:
            heapq.heappush(Q, [_X[adj], adj])
          else:
            contract = True
            break
        elif _X[adj] != s[0] + d:
          contract = True
          break
      if contract:
        break
    if contract:
      print('No')
      break
else:
  print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import heapq
N, M = map(int, input().split())
S = [False] * N
G = [[] for i in range(N)]
def root(i):
  if R[i] == i:
    return i
  else:
    R[i] = root(R[i])
    return R[i]
loop = False
for i in range(M):
  l, r, d = map(int, input().split())
  G[l - 1].append([r - 1, d])
for i in range(N):
  if not S[i]:
    _X = [None for i in range(N)]
    _X[i] = 0
    Q = []
    heapq.heappush(Q, [0, i])
    contract = False
    while Q:
      s = heapq.heappop(Q)
      S[s[1]] = True
      for adj, d in G[s[1]]:
        if _X[adj] == None:
          _X[adj] = s[0] + d
          if _X[adj] <= 10 ** 9:
            heapq.heappush(Q, [_X[adj], adj])
          else:
            contract = True
            break
        elif _X[adj] != s[0] + d:
          contract = True
          break
      if contract:
        break
    if contract:
      print('No')
      break
else:
  print('Yes')

Submission status: Time Limit Exceeded

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 v not 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: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
graph = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    graph[l-1].append((r-1, d))
    graph[r-1].append((l-1, -d))

for i in range(n):
    x = [-1 for i in range(n)]
    if x[i] == -1:
        x[i] = 0
        q = deque([i])
        while q:
            s = q.popleft()
            for node, dist in graph[s]:
                if x[node] == -1:
                    q.append(node)
                    x[node] = x[s] + dist
                elif x[node] != x[s] + dist:
                    print("No")
                    exit()
print("Yes")

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8

import sys

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


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


def solve(N, M, info):
    distance = [[None] * N for _ in range(N)]
    for i in range(N):
        distance[i][i] = 0

    for L, R, D in info:
        distance[L][R] = D

    for L, R, D in info:
        if L + 1 == R:
            continue
        if distance[L][R - 1] is None or distance[L + 1][R] is None:
            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: Time Limit Exceeded

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

MAX = 999999

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

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

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

a[lrd[0][0]] = 0
temp = [lrd[0][0]]
next = []
t = 0
s = 0
max_a = 0
min_a = 0
while 1:
    next = []
    for x in temp:
        for y in p[x]:
            if lrd[y][0] == x:
                t = lrd[y][1]
                s = a[x] + lrd[y][2]
            else:
                t = lrd[y][0]
                s = a[x] - lrd[y][2]

            lrd[y][3] = 1
            if a[t] == MAX:
                a[t] = s
                next.append(t)
            elif a[t] != s:
                print('No')
                exit()

    if len(next) == 0:
        target = 0
        i = 0
        check = 0
        for i in range(m):
            if lrd[i][3] == 0:
                target = lrd[i][0]
                check = 1
        if check == 0:
            break
        a[target] = 0
        next = [target]

    temp = [] + list(set(next))

print('Yes')

Submission status: Time Limit Exceeded

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

MAX = 999999

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

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

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

a[lrd[0][0]] = 0
temp = [lrd[0][0]]
next = []
t = 0
s = 0
max_a = 0
min_a = 0
while 1:
    next = []
    #print("temp", temp)
    for x in temp:
        for y in p[x]:
            if lrd[y][0] == x:
                t = lrd[y][1]
                s = a[x] + lrd[y][2]
            else:
                t = lrd[y][0]
                s = a[x] - lrd[y][2]

            lrd[y][3] = 1
            if a[t] == MAX:
                a[t] = s
                next.append(t)
            elif a[t] != s:
                #print(temp, t, a[t])
                print('No')
                exit()

    #print(next)
    if len(next) == 0:
        target = 0
        i = 0
        check = 0
        for i in range(m):
            if lrd[i][3] == 0:
                target = lrd[i][0]
                check = 1
        if check == 0:
            break
        a[target] = 0
        next = [target]

    #print(next)
    temp = [] + list(set(next))

print('Yes')

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
X = [-1] * N
E = [[] for i in range(N)]
I = [0] * N
for i in range(M):
  L, R, D = map(int, input().split())
  E[L - 1].append([R - 1, D])
  X[R - 1] = -2
  I[R - 1] += 1
ans = True
for i in range(N):
  if X[i] == -1:
    _X = [x for x in X]
    _X[i] = 0
    Q = [i]
    while Q:
      s = Q[0]
      Q = Q[1:]
      X[s] = -3
      for e, d in E[s]:
        if _X[e] <= -2 and _X[s] + d <= 10 ** 9:
          _X[e] = _X[s] + d
          Q.append(e)
        elif _X[e] != _X[s] + d:
          ans = False
          break
    if not ans:
      break
for i in range(N):
  if X[i] == -2 and I[i]:
    ans = False
    break
print('Yes' if ans else 'No')

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split())
n,m=I()
r=range(n)
y=[[] for i in r]
z=[None for i in r]

for _ in [0]*m:
  i,j,k=I()
  y[i-1]+=[[j-1, k]]
  y[j-1]+=[[i-1,-k]]

for i in r:
  if z[i]==None:
    z[i]=0
    q=[i]
    while q:
      p=q.pop()
      for j,k in y[p]:
        if z[j]==None:
          q+=[j]
          z[j]=z[p]+k
        elif z[j]!=z[p]+k:
          print("No")
          exit()
print("Yes")

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split())
n,m=I()
r=range(n)
y=[[] for i in r]
z=[None for i in r]

for _ in [0]*m:
  i,j,k=I()
  y[i-1]+=[[j-1, k]]
  y[j-1]+=[[i-1,-k]]

for i in r:
  if z[i]==None:
    z[i]=0 
  q=[i]
  while q:
    p=q.pop()
    for j,k in y[p]:
      if z[j]==None:
        q+=[j]
        z[j]=z[p]+k
      elif z[j]!=z[p]+k:
        print("No")
        exit()
print("Yes")