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 sys
sys.setrecursionlimit(10**9)
N, M = map(int, input().split())

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

ans = 'Yes'
dist = [None] * N
def dfs(v, pv, d):
    global ans
    dist[v] = d
    for nv, nd in edge[v]:
        if nv == pv: continue
        if dist[nv] == None:
            dfs(nv, v, d+nd)
        else:
            if d+nd != dist[nv]:
                ans = 'No'

for i in range(N):
    if dist[i] == None:
        dfs(i, 0, 0)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, M = map(int, input().split())

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

ans = 'Yes'
dist = [None] * N
def dfs(v, pv, d):
    global ans
    if dist[v] != None and dist[v] != d:
        ans = 'No'
        return
    dist[v] = d
    for i, (nv, nd, nj) in enumerate(edge[v]):
        if nv == pv: continue
        if nj: continue
        edge[v][i][2] = True
        dfs(nv, v, d+nd)

# dist2 = [None] * N
# def dfs2(v, pv, d):
#     if dist2[v] != None: return
#     dist2[v] = d
#     for nv, nd in edge[v]:
#         if nv == pv: continue
#         dfs2(nv, v, d+nd)

for i in range(N):
    if dist[i] == None:
        dfs(i, 0, 0)
# for i in range(N-1,-1,-1):
#     dfs2(i, 0, 0)

# m = min(dist)
# for i in range(N):
#     dist[i] -= m
# m = min(dist2)
# for i in range(N):
#     dist2[i] -= m

# ans = 'Yes' if all(i1 == i2 for i1, i2 in zip(dist, dist2)) else 'No'
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
from copy import deepcopy
from operator import itemgetter

n, m = (int(x) for x in input().split())
LRD = [tuple(int(x) for x in input().split()) for _ in range(m)]
LRD.sort(key=itemgetter(0, 1))
INF = 10**18

while LRD:
    X = [INF] * n
    TBD = []  # To be determined
    X[LRD[0][0] - 1] = 0
    for l, r, d in LRD:
        l -= 1
        r -= 1
        if X[l] == X[r] == INF:
            TBD.append((l, r, d))
        elif X[l] != INF and X[r] == INF:
            X[r] = X[l] + d
        elif X[l] == INF and X[r] != INF:
            X[l] = X[r] - d
        else:
            if X[r] - X[l] != d:
                print("No")
                exit()
            else:
                continue
    LRD = deepcopy(TBD)
    LRD.sort(key=itemgetter(0, 1))
    X.sort()
    xmax = X[bisect_left(X, INF) - 1]
    xmin = X[0]
    if xmax - xmin >= 10**9:
        print("No")
        exit()

print("Yes")

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
vertices = {i: [] for i in range(n)}
for _ in range(m):
    l, r, d = map(int, input().split())
    vertices[l - 1].append((r - 1, d))
    vertices[r - 1].append((l - 1, -d))


def answer():
    x = [None] * n

    while any(i is None for i in x):
        i = x.index(None)
        x[i] = 0
        queue = [i]

        while queue:
            i0 = queue.pop()
            for i1, d in vertices[i0]:
                # print(i0, i1, x[i0], x[i1], d)
                if x[i1] is None:
                    x[i1] = x[i0] + d
                    queue.append(i1)
                elif x[i1] != x[i0] + d:
                    return False

    return True


if answer():
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
inf = pow(10, 10)

n, m = map(int, input().split())
a = [inf] * n

edge = [[] for i in range(n)]

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

flag = True
for i in range(n):
    if not flag: break
    dist = [10**10]*n
    dist[i] = 0
    dq = deque([i])
    while dq:
        now = dq.popleft()
        for e in edge[now]:
            nnode, d = e
            if dist[nnode] == inf:
                dist[nnode] = dist[now] + d
                dq.append(nnode)
            else:
                if dist[nnode] != dist[now] + d:
                    flag = False
                    break
if flag:
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
a = [10**10] * n

edge = [[] for i in range(n)]

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

flag = True
for i in range(n):
    if not flag: break
    dist = [10**10]*n
    dist[i] = 0
    dq = deque([i])
    while dq:
        now = dq.popleft()
        for e in edge[now]:
            nnode, d = e
            if dist[nnode] == 10**10:
                dist[nnode] = dist[now] + d
                dq.append(nnode)
            else:
                if dist[nnode] != dist[now] + d:
                    flag = False
                    break
if flag:
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, m = map(int, input().split())
a = [10**10] * n

edge = [[] for i in range(n)]

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

flag = True
for i in range(n):
    if not flag: break
    dist = [10**10]*n
    dist[i] = 0
    dq = deque([i])
    while dq:
        now = dq.popleft()
        for e in edge[now]:
            nnode, d = e
            if dist[nnode] == 10**10:
                dist[nnode] = dist[now] + d
                dq.append(nnode)
            else:
                if dist[nnode] != dist[now] + d:
                    flag = False
                    break
if flag:
    print('Yes')
else:
    print('No')

Submission status: Time Limit Exceeded

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

from collections import deque
no_seen=set(range(n))
inf=float('inf')
dst=[inf]*n
while no_seen:
  todo=deque([[0,no_seen.pop()]])
  #print(todo)
  while todo:
    d,t=todo.popleft()
    no_seen.discard(t)
    dst[t]=d
    l=g[t]
    for di,ti in l:
      if dst[ti]!=inf and dst[ti]!=d+di:
        print('No')
        exit()
      elif dst[ti]!=inf and dst[ti]==d+di:
        pass
      else:
        todo.append([d+di,ti])

print('Yes')

Submission status: Time Limit Exceeded

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

from collections import deque
no_seen=set(range(n))
inf=float('inf')
while no_seen:
  todo=deque([[0,no_seen.pop()]])
  dst=[inf]*n
  #print(todo)
  while todo:
    d,t=todo.popleft()
    dst[t]=d
    l=g[t]
    for di,ti in l:
      if dst[ti]!=inf and dst[ti]!=d+di:
        print('No')
        exit()
      elif dst[ti]!=inf and dst[ti]==d+di:
        no_seen.discard(t)
        pass
      else:
        todo.append([d+di,ti])

print('Yes')

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
lrd=[list(map(int,input().split())) for _ in range(m)]
ds={} # ds[(l,r)]:rがlのどれだけ右にいるか
dr={} # dr[i]:r=iのヒントのlの集合
import sys
sys.setrecursionlimit(10**7)
def add(l,r,d):
  if (r,l) in ds:
    print('No')
    exit()
  if (l,r) in ds and ds[(l,r)]!=d:
    print('No')
    #print(ds)
    exit()
  ds[(l,r)]=d
  if r in dr:
    dr[r].add(l)
  else:
    dr[r]=set([l])
  if l in dr:
    for i in dr[l]:
      add(i,r,ds[(i,l)]+d)

for l,r,d in lrd:
  add(l,r,d)

print('Yes')
#print(ds)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
lrd=[list(map(int,input().split())) for _ in range(m)]
ds={} # ds[(l,r)]:rがlのどれだけ右にいるか
dr={} # dr[i]:r=iのヒントのlの集合
import sys
sys.setrecursionlimit(10**7)
def add(l,r,d):
  if (l,r) in ds and ds[(l,r)]!=d:
    print('No')
    #print(ds)
    exit()
  ds[(l,r)]=d
  if r in dr:
    dr[r].add(l)
  else:
    dr[r]=set([l])
  if l in dr:
    for i in dr[l]:
      add(i,r,ds[(i,l)]+d)

for l,r,d in lrd:
  add(l,r,d)

print('Yes')
#print(ds)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

check_v = [False for _ in range(n)]
check_e = [False for _ in range(m)]
max_int = 10 ** 10
point = [max_int for _ in range(n)]

for v in range(n):
    Q = deque()
    if not check_v[v]:
        Q.append(v)
    while Q:
        v = Q.popleft()
        for next_v, e, d in graph[v]:                
            if not check_e[e]:
                if point[v] == max_int:
                    point[v] = 0
                if point[next_v] == max_int:
                    point[next_v] = point[v] + d
                else:
                    if point[next_v] != point[v] + d:
                        print('No')
                        exit()
            check_e[e] = True
            if not check_v[next_v]:
                Q.append(next_v)
            check_v[v] = True
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

check_v = [False for _ in range(n)]
check_e = [False for _ in range(m)]
max_int = 10 ** 10
point = [max_int for _ in range(n)]

for v in range(n):
    Q = deque()
    if not check_v[v]:
        Q.append(v)
    while Q:
        v = Q.popleft()
        for next_v, e, d in graph[v]:                
            if not check_e[e]:
                if point[v] == max_int:
                    point[v] = 0
                if point[next_v] == max_int:
                    point[next_v] = point[v] + d
                else:
                    if point[next_v] != point[v] + d:
                        print('No')
                        exit()
            check_e[e] = True
            if not check_v[next_v]:
                Q.append(next_v)
            check_v[v] = True
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
def topo_sort(g):
    from collections import deque
    V = len(g)
    deg = [0]*V
    for src in range(V):
        for dst in g[src]:
            deg[dst] += 1
    ans = list(v for v in range(V) if deg[v]==0)
    deq = deque(ans)
    used = [0]*V

    while deq:
        v = deq.popleft()
        for t in g[v]:
            deg[t] -= 1
            if deg[t]==0:
                deq.append(t)
                ans.append(t)
    return ans

def resolve():
    N, M = list(map(int, input().split()))
    LRD = [list(map(int, input().split())) for _ in range(M)]
    adj_list = [[] for _ in range(N)]
    adj_matrix = [[None for _ in range(N)] for __ in range(N)]
    for lrd in LRD:
        l, r, d = lrd
        adj_list[l-1].append(r-1)
        adj_matrix[l-1][r-1] = d
    
    #top_order = topological_sort(adj_list)
    top_order = topo_sort(adj_list)
    
    if len(top_order) != len(adj_list):
        print("No")
        return
    
    acc = 0
    start = top_order[0]
    now = top_order[0]
    for i in range(1, len(top_order)):
        nxt = top_order[i]
        if adj_matrix[now][nxt] is not None:
            if adj_matrix[start][nxt] is not None and acc+adj_matrix[now][nxt] != adj_matrix[start][nxt]:
                print("No")
                return
            acc += adj_matrix[now][nxt]
        now = nxt
        
    print("Yes")


if '__main__' == __name__:
    resolve()

Submission status: Time Limit Exceeded

Solution code:
def topological_sort(dag):
    n_nodes = len(dag)
    n_ins = [0]*n_nodes
    in_zeros = []
    sorted_nodes = []

    for src in range(n_nodes):
        for dst in dag[src]:
            n_ins[dst] += 1

    for i, v in enumerate(n_ins):
        if v == 0:
            in_zeros.append(i)

    while in_zeros:
        node = in_zeros.pop()
        sorted_nodes.append(node)
        for dst in dag[node]:
            n_ins[dst] -= 1
            if n_ins[dst] == 0:
                in_zeros.append(dst)
    
    return sorted_nodes

def resolve():
    N, M = list(map(int, input().split()))
    LRD = [list(map(int, input().split())) for _ in range(M)]
    adj_list = [[] for _ in range(N)]
    adj_matrix = [[None for _ in range(N)] for __ in range(N)]
    for lrd in LRD:
        l, r, d = lrd
        adj_list[l-1].append(r-1)
        adj_matrix[l-1][r-1] = d
    top_order = topological_sort(adj_list)
    if len(top_order) != len(adj_list):
        print("No")
        return
    
    acc = 0
    start = top_order[0]
    now = top_order[0]
    for i in range(1, len(top_order)):
        nxt = top_order[i]
        if adj_matrix[now][nxt] is not None:
            if adj_matrix[start][nxt] is not None and acc+adj_matrix[now][nxt] != adj_matrix[start][nxt]:
                print("No")
                return
            acc += adj_matrix[now][nxt]
        now = nxt
        
    print("Yes")


if '__main__' == __name__:
    resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    def dfs(u, cost):
        visited[u] = True
        for v, w in edge[u]:
            if costs.get(v) and costs[v] != cost + w:
                print("No")
                sys.exit()
            costs[v] = cost + w
            dfs(v, cost + w)

    from collections import defaultdict
    n, m = map(int, readline().split())
    edge = defaultdict(list)

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

    visited = [False] * (n + 1)

    for u in range(1, n + 1):
        costs = dict()
        if not visited[u]:
            dfs(u, 0)
    print("Yes")


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return

    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
    val = [inf] * N
    global_visited = set()

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        return False
                val[next_v] = val[v] + d
                visited.add(next_v)
                global_visited.add(next_v)
                q.append(next_v)
        return True

    can = True
    for i in range(N):
        if i in global_visited:
            continue
        v = i
        val[v] = 0
        if not bfs(v):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return


main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return
    uf = UnionFind(N)
    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))

    val = [inf] * N
    glb_visited = set()

    def bfs(ini):
        q = deque([ini])
        visited = set()
        visited.add(ini)
        glb_visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        return False
                val[next_v] = val[v] + d
                visited.add(next_v)
                glb_visited.add(next_v)
                q.append(next_v)
        return True

    can = True

    for k in range(N):
        if k in glb_visited:
            continue
        val[k] = 0
        if not bfs(k):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return

main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return
    uf = UnionFind(N)
    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
        uf.union(l, r)
        uf.find(r)

    val = [inf] * N
    glb_visited = set()

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        glb_visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        flag = False
                        break
                val[next_v] = val[v] + d
                visited.add(next_v)
                glb_visited.add(next_v)
                q.append(next_v)
        if flag:
            return True
        return False

    can = True

    for k in range(N):
        if k in glb_visited:
            continue
        val[k] = 0
        if not bfs(k):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return

main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return
    uf = UnionFind(N)
    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
        uf.union(l, r)
        uf.find(r)

    val = [inf] * N

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        flag = False
                        break
                val[next_v] = val[v] + d
                visited.add(next_v)
                q.append(next_v)
        if flag:
            return True
        return False

    can = True

    for k, v in uf.all_group_members().items():
        val[k] = 0
        if not bfs(k):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return

main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

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

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

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

        if x == y:
            return

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

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

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

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

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

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

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

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

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

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return
    uf = UnionFind(N)
    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
        uf.union(l, r)

    val = [inf] * N

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        flag = False
                        break
                val[next_v] = val[v] + d
                visited.add(next_v)
                q.append(next_v)
        if flag:
            return True
        return False

    can = True

    for k, v in uf.all_group_members().items():
        val[k] = 0
        if not bfs(k):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return

main()

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     

def main():
    N, M = LI()
    if M == 0:
        print("Yes")
        return

    G = [[] for _ in range(N)]
    for i in range(M):
        l, r, d = LI()
        l -= 1
        r -= 1
        G[l].append((r, d))
        G[r].append((l, -d))
    val = [inf] * N
    global_visited = set()

    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        visited.add(ini)
        global_visited.add(ini)
        while q:
            v = q.popleft()
            for next_v, d in G[v]:
                if next_v in visited:
                    if val[next_v] == val[v] + d:
                        continue
                    else:
                        flag = False
                        break
                val[next_v] = val[v] + d
                visited.add(next_v)
                global_visited.add(next_v)
                q.append(next_v)
        if flag:
            return True
        return False

    can = True
    for i in range(N):
        if i in global_visited:
            continue
        v = i
        val[v] = 0
        if not bfs(v):
            can = False

    if can:
        print("Yes")
    else:
        print("No")
    return




main()