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:
N, M = map(int, raw_input().split())
a = []
for i in range(M):
	a.append(map(int, raw_input().split()))
x = [0 for i in range(N)]
y = [0 for i in range(N)]
layer = 1
answer = 'Yes'
for i in range(M):
	L = a[i][0]
	R = a[i][1]
	D = a[i][2]
	if y[L-1] == 0 and y[R-1] == 0:
		x[R-1] = x[L-1] + D
		y[L-1] = layer
		y[R-1] = layer
	elif y[L-1] == 0 and y[R-1] > 0:
		x[L-1] = x[R-1] - D
		y[L-1] = y[R-1]
	elif y[L-1] > 0 and y[R-1] == 0:
		x[R-1] = x[L-1] + D
		y[R-1] = y[L-1]
	elif y[L-1] > 0 and y[R-1] > 0:
		if y[L-1] == y[R-1]:
			if x[R-1] - x[L-1] != D:
				answer = 'No'
		else:
			dx = x[L-1] + D - x[R-1]
			for j in range(N):
				if y[j] == y[R-1]:
					x[j] = x[j] + dx
					y[j] = y[L-1]
	layer = layer + 1
print answer

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start, dist_all):
    q = deque([[start]])
    dist_all[i] = 0
    while(len(q) > 0):
        path = q.popleft()
        w = path[len(path) - 1]
        for x in adj_list[w]:
            if dist_all[x[0]] is None:
                dist_all[x[0]] = dist_all[w] + x[1]
                new_path = path[:]
                new_path.append(x[0])
                q.append(new_path)
            elif dist_all[x[0]] != dist_all[w] + x[1]:
                return False
    return True
dist_all = [None for i in range(n)]
for i in range(n):
    if dist_all[i] is None:
        if not search(i, dist_all):
            print('No')
            exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start, dist_all):
    q = deque([[start]])
    q_d = deque([0])
    while(len(q) > 0):
        path = q.popleft()
        dist = q_d.popleft()
        w = path[len(path) - 1]
        for x in adj_list[w]:
            if dist_all[x[0]] is None:
                dist_all[x[0]] = dist + x[1]
                new_path = path[:]
                new_path.append(x[0])
                q.append(new_path)
                q_d.append(dist + x[1])
            elif dist_all[x[0]] != dist + x[1]:
                return False
    return True
dist_all = [None for i in range(n)]
for i in range(n):
    if dist_all[i] is None:
        if not search(i, dist_all):
            print('No')
            exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start, dist_all):
    q = deque([[start]])
    q_d = deque([0])
    while(len(q) > 0):
        path = q.popleft()
        dist = q_d.popleft()
        w = path[len(path) - 1]
        for x in adj_list[w]:
            if x[0] not in path:
                new_path = path[:]
                new_path.append(x[0])
                if dist_all[x[0]] is None:
                    dist_all[x[0]] = dist + x[1]
                elif dist_all[x[0]] != dist + x[1]:
                    return False
                q.append(new_path)
                q_d.append(dist + x[1])
    return True
dist_all = [None for i in range(n)]
for i in range(n):
    if dist_all[i] is None:
        if not search(i, dist_all):
            print('No')
            exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start):
    q = deque([[start]])
    q_d = deque([0])
    dist_all = [None for i in range(n)]
    while(len(q) > 0):
        path = q.popleft()
        dist = q_d.popleft()
        w = path[len(path) - 1]
        for x in adj_list[w]:
            if x[0] not in path:
                new_path = path[:]
                new_path.append(x[0])
                if dist_all[x[0]] is None:
                    dist_all[x[0]] = dist + x[1]
                elif dist_all[x[0]] != dist + x[1]:
                    return False
                q.append(new_path)
                q_d.append(dist + x[1])
    return True
for i in range(n):
    if not search(i):
        print('No')
        exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start):
    q = [[start]]
    q_d = [0]
    q_d = [0]
    dist_all = [None for i in range(n)]
    while(len(q) > 0):
        path = q.pop(0)
        dist = q_d.pop(0)
        w = path[len(path) - 1]
        for x in adj_list[w]:
            if x[0] not in path:
                new_path = path[:]
                new_path.append(x[0])
                if dist_all[x[0]] is None:
                    dist_all[x[0]] = dist + x[1]
                elif dist_all[x[0]] != dist + x[1]:
                    return False
                q.append(new_path)
                q_d.append(dist + x[1])
    return True
for i in range(n):
    if not search(i):
        print('No')
        exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start, goal):
    q = [[start]]
    q_d = [0]
    d_set = set()
    while(len(q) > 0):
        path = q.pop(0)
        dist = q_d.pop(0)
        w = path[len(path) - 1]
        if w == goal:
            d_set.add(dist)
            if len(d_set) > 1:
                return False
        else:
            for x in adj_list[w]:
                if x[0] not in path:
                    new_path = path[:]
                    new_path.append(x[0])
                    q.append(new_path)
                    q_d.append(dist + x[1])
    return True
for i in range(n):
    for j in range(i + 1):
        if not search(i, j):
            print('No')
            exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys

n,m = map(int, input().split())
adj_list = [[] for i in range(n)]
for i in range(m):
    l, r, d = map(int, input().split())
    adj_list[l-1].append((r-1, d))
    adj_list[r-1].append((l-1, -d))
def search(start, goal):
    q = [[start]]
    q_d = [0]
    d_set = set()
    while(len(q) > 0):
        path = q.pop(0)
        dist = q_d.pop(0)
        w = path[len(path) - 1]
        if w == goal:
            d_set.add(dist)
        else:
            for x in adj_list[w]:
                if x[0] not in path:
                    new_path = path[:]
                    new_path.append(x[0])
                    q.append(new_path)
                    q_d.append(dist + x[1])
    if len(d_set) <= 1:
        return True
    else:
        return False
for i in range(n):
    for j in range(n):
        if not search(i, j):
            print('No')
            exit(0)
print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys 

temp=input().split(" ")
n=int(temp[0])
m=int(temp[1])
p=[]
con={} #連結の情報を表す
for i in range(n+1):
    con[i]=[]
dis=[[-1 for i in range(n+1)] for j in range(n+1)] #[y][x] y→xのコストを表す

cos=[None for i in range(n+1)] #あるvのコスト(暫定)を表す

for i in range(m):
    temp=input()
    temp=list(map(int,temp.split(" ")))
    p.append(temp)
for temp in p: #yからxの距離d をdis[y][x]=dとして確保 グラフの作成フェイズ
    x=int(temp[0])
    y=int(temp[1])    
    d=int(temp[2])
    dis[y][x]=d
    dis[x][y]=-d
    con[y].append(x) 
for v in range(1,n+1):
   # print(con)
    while len(con[v])!=0:
        temp=con[v].pop()
        #print((cos[temp],cos[v]))
        if cos[v] is None:
            if cos[temp] is None:
                cos[temp]=0
            cos[v]=cos[temp]+dis[temp][v]
        if cos[temp] is None:
                cos[temp]=0
       # print((cos[temp],cos[v]))
        if cos[v]!=cos[temp]+dis[temp][v]:
            print("No")
            sys.exit()
print("Yes")

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    e = [set() for _ in range(n)]
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].add((r-1,d))
            e[r-1].add((l-1,-d))

    b = [False] * n

    for i in range(n):
        if b[i] != False:
            continue
        b[i] = 0
        q = [i]
        qi = 0
        nq = []
        while True:
            if len(q) == qi:
                if not nq:
                    break
                q = nq
                qi = 0
                nq = []
            j = q[qi]
            qi += 1
            c = b[j]
            for r,d in e[j]:
                if b[r] == False:
                    b[r] = c+d
                    nq.append(r)
                else:
                    if b[r] != c+d:
                        return 'No'
                    if e[r] in (j,-d):
                        e[r].remove((j,-2))

    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    e = [[] for _ in range(n)]
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].append((r-1,d))
            e[r-1].append((l-1,-d))

    b = [False] * n

    for i in range(n):
        if b[i] != False:
            continue
        b[i] = 0
        q = [i]
        qi = 0
        nq = []
        while True:
            if len(q) == qi:
                if not nq:
                    break
                q = nq
                qi = 0
                nq = []
            j = q[qi]
            qi += 1
            c = b[j]
            for r,d in e[j]:
                if b[r] == False:
                    b[r] = c+d
                    nq.append(r)
                else:
                    if b[r] != c+d:
                        return 'No'

    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    e = [[] for _ in range(n)]
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].append((r-1,d))
            e[r-1].append((l-1,-d))

    b = [False] * n
    def g(i):
        b[i] = 0
        q = [i]
        qi = 0
        nq = []
        while True:
            if len(q) == qi:
                if not nq:
                    return True
                q = nq
                qi = 0
                nq = []
            j = q[qi]
            qi += 1
            c = b[j]
            for r,d in e[j]:
                if b[r] == False:
                    b[r] = c+d
                    nq.append(r)
                else:
                    if b[r] != c+d:
                        return False
        return True

    for i in range(n):
        if b[i] != False:
            continue
        if not g(i):
            return 'No'
    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    n,m = LI()
    e = [[] for _ in range(n)]
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].append((r-1,d))
            e[r-1].append((l-1,-d))

    b = [False] * n
    def g(i):
        b[i] = 0
        q = [i]
        qi = 0
        while len(q) > qi:
            j = q[qi]
            qi += 1
            c = b[j]
            for r,d in e[j]:
                if b[r] == False:
                    b[r] = c+d
                    q.append(r)
                else:
                    if b[r] != c+d:
                        return False
        return True

    for i in range(n):
        if b[i] != False:
            continue
        if not g(i):
            return 'No'
    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    start = time.time()
    n,m = LI()
    e = collections.defaultdict(list)
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].append((r-1,d))
            e[r-1].append((l-1,-d))

    b = [False] * n
    def g(i):
        b[i] = 0
        q = [i]
        qi = 0
        while len(q) > qi:
            j = q[qi]
            qi += 1
            c = b[j]
            for r,d in e[j]:
                if b[r] == False:
                    b[r] = c+d
                    q.append(r)
                else:
                    if b[r] != c+d:
                        return False
        return True

    for i in range(n):
        if b[i] != False:
            continue
        if not g(i):
            return 'No'
    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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

def deep(self):
    for j in pos[self]:
        if posvis[j[2]]:
            posvis[j[2]] = 0
            if len(por[self]) < 1:
                por[self] = [100000]
            if len(set(por[self])) > 1:
                print("No")
                exit()
            por[j[0]].append(por[self][0] + j[1])
            por[j[0]] = list(set(por[j[0]]))
            if len(set(por[j[0]])) > 1:
                print("No")
                exit()
            deep(j[0])
for qww in qe:
    if posvis[qww[2]]:
        deep(qww[0])
for i in por:
    if i:
        if len(set(i)) > 1:
            print("No")
            exit()
else:
    print("Yes")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

class Edge:
	def __init__(self, t, w):
		self.to = t
		self.ew = w

class Graph:
	def __init__(self, N):
		self.nw = [-1] * N
		self.al = [[] for i in range(N)]

	def add_edge(self, fr, to, weight):
		self.al[fr].append(Edge(to, weight))
		self.al[to].append(Edge(fr, -weight))

	def dfs(self, s, used):
		self.nw[s] = 0
		q = deque([s])
		while q:
			h = q.popleft()
			if h in used:
				continue
			used.add(h)
			for e in self.al[h]:
				if e.to in used and self.nw[h] + e.ew != self.nw[e.to]:
					return False
				self.nw[e.to] = self.nw[h] + e.ew
				q.appendleft(e.to)
		return True


def main():
	N, M = map(int, input().split())
	graph = Graph(N)
	for i in range(M):
		l, r, d = map(int, input().split())
		graph.add_edge(l - 1, r - 1, d)

	used = set()
	for i in range(N):
		if i in used or graph.dfs(i, used):
			continue
		print("No")
		break
	else:
		print("Yes")


if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
def solve(N, M, lrd):
    vs = {}
    def calc(l, r):
        cs = set([l])
        xs = [(l, 0)]
        while xs:
            x = xs.pop()
            if x[0] in vs:
                for y, d in vs[x[0]].items():
                    if y == r:
                        return d + x[1]
                    if y not in cs: 
                        xs.append((y, d + x[1]))
                        cs.add(y)
        return None
    for l, r, d in lrd:
        x = calc(l, r)
        if not x is None and x != d:
            return False
        if l not in vs:
            vs[l] = {}
        if r not in vs:
            vs[r] = {}
        vs[l][r] = d
        vs[r][l] = -d
    return True

if __name__ == "__main__":
    N, M = [int(x) for x in input().split()]
    lrd = []
    for i in range(M):
        lrd.append([int(x) for x in input().split()])
    if solve(N, M, lrd):
        print("Yes")
    else:
        print("No")

Submission status: Time Limit Exceeded

Solution code:
def solve(N, M, lrd):
    vs = {}
    def calc(l, r):
        cs = set([l])
        xs = [(l, 0)]
        while xs:
            x = xs.pop()
            if x[0] in vs:
                for y, d in vs[x[0]].items():
                    if y == r:
                        return d + x[1]
                    if y not in cs: 
                        xs.append((y, d + x[1]))
                        cs.add(y)
        return None
    for l, r, d in lrd:
        x = calc(l, r)
        if x is None:
            if l not in vs:
                vs[l] = {}
            if r not in vs:
                vs[r] = {}
            vs[l][r] = d
            vs[r][l] = -d
        elif x != d:
            return False
    return True

if __name__ == "__main__":
    N, M = [int(x) for x in input().split()]
    lrd = []
    for i in range(M):
        lrd.append([int(x) for x in input().split()])
    if solve(N, M, lrd):
        print("Yes")
    else:
        print("No")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import  deque
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
 
adj = [[] for _ in range(N+1)]  
 
for _ in range(M):
    l, r, d = inpl()
    adj[l].append([r, d])
    adj[r].append([l, -d])
 
X = [-1 for _ in range(N+1)]
searched = [False for _ in range(N+1)]
S = 0 # == sum(searched)
res = True
g = 1
Q = deque([])
while True:
    if S >= N:
        break
    g = g + searched[g:].index(False)
    X[g] = 0
    Q.append(g)
    searched[g] = True
    S += 1
    while Q:
        p = Q.popleft()
        for np, d in adj[p]:
            if searched[np]:
                if X[np] != X[p] + d:
                    Q = []
                    res = False
                    break
            else:
                X[np] = X[p] + d
                Q.append(np)
                searched[np] = True
                S += 1
    if not res:
        break
 
if res:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import  deque
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
Q = [inpl() for _ in range(M)]
 
adj = [[] for _ in range(N+1)]  
 
for l, r, d in Q:
    adj[l].append([r, d])
    adj[r].append([l, -d])
 
X = [-1 for _ in range(N+1)]
searched = [False for _ in range(N+1)]
S = 0 # == len(searched)
res = True
g = 0 
while True:
    if S >= N:
        break
    g = g + searched[g:].index(False)
    X[g] = 0
    Q = deque([g])
    searched[g] = True
    S += 1
    while Q:
        p = Q.popleft()
        for np, d in adj[p]:
            if searched[np]:
                if X[np] != X[p] + d:
                    Q = []
                    res = False
                    break
            else:
                X[np] = X[p] + d
                Q.append(np)
                searched[np] = True
                S += 1
    if not res:
        break
 
if res:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10000)
from collections import defaultdict, deque
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
Q = [inpl() for _ in range(M)]
 
tree = [[-1, 1]  for _ in range(N+1)] # [next, rank]
  
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
 
adj = [[] for _ in range(N+1)]  
 
for l, r, d in Q:
    if find(l) != find(r):
        unite(l, r)
    adj[l].append([r, d])
    adj[r].append([l, -d])
 
 
G = set([find(n) for n in range(1, N+1)])
 
X = [-1 for _ in range(N+1)]
searched = [False for _ in range(N+1)]
res = True
 
for g in G:
    X[g] = 0
    Q = deque([g])
    searched[g] = True
    while Q:
        p = Q.popleft()
        for np, d in adj[p]:
            if searched[np]:
                if X[np] != X[p] + d:
                    Q = []
                    res = False
                    break
            else:
                X[np] = X[p] + d
                Q.append(np)
                searched[np] = True
    if not res:
        break
 
if res:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import math
import itertools
import heapq
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect, bisect_left, bisect_right
from collections import defaultdict, deque


# d = defaultdict(lambda: 0)
# setrecursionlimit(10**7)
# inf = float("inf")


##### stdin ####
def LM(t, r): return list(map(t, r))
def R(): return stdin.readline()
def RS(): return R().split()
def I(): return int(R())
def F(): return float(R())
def LI(): return LM(int,RS())
def LF(): return LM(float,RS())
def ONE_SL(): return list(input())
def ONE_IL(): return LM(int, ONE_SL())
def ALL_IL(): return LM(int,stdin)

##### tools #####
def ap(f): return f.append
def pll(li): print('\n'.join(LM(str,li)))
def pljoin(li, s): print(s.join(li))



##### main #####

def main():
	N,M = LI()

	dist = defaultdict(lambda: 0)
	memo = defaultdict(lambda: False)
	f = True
	tmp = []


	for m in range(M):
		l,r,d = LI()
		l -= 1; r -= 1

		if abs(l-r) == 1:
			dist[(l,r)] = d
			dist[(r,l)] = d
			memo[(l,r)] = True
			memo[(r,l)] = True


		else:
			tmp.append([l,r,d])



	for t in tmp:
		l,r,d = t


		diff = 0
		rest = False

		for i in range(l+1,r+1):
			if memo[(i-1,i)]:
				diff += dist[i-1,i]
			else:
				rest = True

		if diff != 0:
			if not rest:
				if diff != d:
					f = False
					break
				
		dist[(l,r)] = d
		dist[(r,l)] = d


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



if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10000)
from collections import defaultdict, deque
def inpl(): return tuple(map(int, input().split()))
 
N, M = inpl()
Q = [inpl() for _ in range(M)]
# グループごとにトポロジカルソートをして、最後の方から遡って計算
 
tree = [[-1, 1]  for _ in range(N+1)] # [next, rank]
  
def find(i):
    if tree[i][0] == -1:
        group = i
    else:
        group = find(tree[i][0]) 
        tree[i][0] = group
    return group
  
def unite(x, y):
    px = find(x)
    py = find(y)
      
    if tree[px][1] == tree[py][1]: # rank is same
        tree[py][0] = px
        tree[px][1] += 1
    else:
        if tree[px][1] < tree[py][1]:
            px, py = py, px
        tree[py][0] = px
 
adj = [[] for _ in range(N+1)]  
 
for l, r, d in Q:
    if find(l) != find(r) or find(l) == -1:
        unite(l, r)
    adj[l].append([r, d])
    adj[r].append([l, -d])
 
 
G = set([find(n) for n in range(1, N+1)])
 
X = [-1 for _ in range(N+1)]
searched = [False for _ in range(N+1)]
res = True
 
for g in G:
    X[g] = 0
    Q = deque([g])
    searched[g] = True
    while Q:
        p = Q.popleft()
        for np, d in adj[p]:
            if searched[np]:
                if X[np] != X[p] + d:
                    Q = []
                    res = False
                    break
            else:
                X[np] = X[p] + d
                Q.append(np)
                searched[np] = True
    if not res:
        break
 
if res:
    print("Yes")
else:
    print("No")

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7

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 pf(s): return print(s, flush=True)


def main():
    start = time.time()
    n,m = LI()
    e = collections.defaultdict(list)
    if m > 0:
        for _ in range(m):
            l,r,d = LI()
            e[l-1].append((r-1,d))
            e[r-1].append((l-1,-d))

    b = [False] * n
    def g(i,c):
        if b[i] != False:
            if c == False:
                return True
            return b[i] == c
        if c == False:
            c = 0
        b[i] = c
        for r,d in e[i]:
            if time.time() - start > 1.5:
                return True
            if not g(r,c+d):
                return False
        return True

    for i in range(n):
        if not g(i,False):
            return 'No'
    return 'Yes'


print(main())

Submission status: Time Limit Exceeded

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


def dfs(i, pos):
    done[i] = True
    if position[i] is None or position[i] == pos:
        position[i] = pos
        for r, d in rights[i]:
            dfs(r, pos+d)
    else:
        print('No')
        sys.exit()



rights = [[] for _ in range(N)]
indeg = [0]*N
done = [False] * N
for m in range(M):
    L, R, D = map(int, input().split())
    rights[L-1].append((R-1, D))

for i in range(N):
    if not done[i]:
        position = [None] * N
        dfs(i, 0)

print('Yes')

Submission status: Time Limit Exceeded

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


def dfs(i, pos):
    if position[i] is None or position[i] == pos:
        position[i] = pos
        for r, d in rights[i]:
            dfs(r, pos+d)
    else:
        print('No')
        sys.exit()



rights = [[] for _ in range(N)]
indeg = [0]*N
for m in range(M):
    L, R, D = map(int, input().split())
    rights[L-1].append((R-1, D))
    indeg[R-1] += 1

for i in range(N):
    position = [None] * N
    dfs(i, 0)

print('Yes')

Submission status: Time Limit Exceeded

Solution code:
import sys,time
sys.setrecursionlimit(10**6)

def LI(): return [int(x) for x in sys.stdin.readline().split()]


def main():
    start = time.time()
    n,m = LI()
    a = [LI() for _ in range(m)]
    e = [[] for _ in range(n)]
    for l,r,d in a:
        e[l-1].append((r-1,d))
        e[r-1].append((l-1,-d))

    b = [False] * n
    def g(i,c):
        if time.time() - start > 0.9:
            return True
        if c == False:
            c = 0
        b[i] = c
        for r,d in e[i]:
            if b[r] != False:
                if b[r] != c+d:
                    return False
            else:
                if not g(r,c+d):
                    return False
        return True

    for i in range(n):
        if b[i] != False:
            continue
        if not g(i,False):
            return 'No'
    return 'Yes'


print(main())