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: Wrong Answer

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()
  elif (l,r) in ds:
    if ds[(l,r)]!=d:
      print('No')
      exit()
  else:
    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: Wrong Answer

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の集合
for l,r,d in lrd:
  if (r,l) in ds:
    print('No')
    exit()
  if (l,r) in ds and ds[(l,r)]!=d:
    print('No')
    #print(ds)
    exit()
  else:
    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]:
        if (i,r) in ds and ds[(i,r)]!=ds[(i,l)]+ds[(l,r)]:
          print('No')
          exit()
        else:
          ds[(i,r)]=ds[(i,l)]+ds[(l,r)]
          dr[r].add(i)
print('Yes')
#print(ds)

Submission status: Wrong Answer

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の集合
for l,r,d in lrd:
  if (r,l) in ds:
    print('No')
    exit()
  if (l,r) in ds and ds[(l,r)]!=d:
    print('No')
    #print(ds)
    exit()
  else:
    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]:
        if (i,r) in ds and ds[(i,r)]!=ds[(i,l)]+ds[(l,r)]:
          print('No')
          exit()
        else:
          ds[(i,r)]=ds[(i,l)]+ds[(l,r)]
print('Yes')
#print(ds)

Submission status: Wrong Answer

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, r, i, -d))
    graph[l].append((r, l, i, d))

max_int = 10 ** 10
point = [None for _ in range(n)]

for v in range(n):
    Q = deque()
    if point[v] is not None:
        continue
    Q.extend(graph[v])
    while Q:
        next_v, v, e, d = Q.popleft()
        if point[next_v] is not None:
            if point[next_v] != point[v] + d:
                print('No')
                exit()
            point[next_v] = point[v] + d
            Q.extend(graph[next_v])
print('Yes')

Submission status: Wrong Answer

Solution code:
from collections import deque

n, m = map(int, input().split())
graph = [[] for _ in range(n)]
edge = []
for i in range(m):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    graph[r].append((l, i))
    graph[l].append((r, i))
    edge.append(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 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] + edge[e]
                else:
                    if point[next_v] != point[v] + edge[e]:
                        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: Wrong Answer

Solution code:
n, m = map(int, input().split())
query = []
for _ in range(m):
    l, r, d = map(int, input().split())
    l -= 1
    r -= 1
    if l > r:
        l, r = r, l
        d *= -1
    query.append((l, r, d))
query.sort()
max_x = 10 ** 10
position = [max_x for _ in range(n)]
for l, r, d in query:
    if (position[l] == max_x) & (position[r] == max_x):
        position[l] = 0
        position[r] = position[l] + d
    elif (position[l] == max_x) & (position[r] != max_x):
        position[l] = position[r] - d
    elif (position[l] != max_x) & (position[r] == max_x):
        position[r] = position[l] + d
    else:
        if position[r] - position[l] == d:
            continue
        else:
            print('No')
            exit()
print('Yes')

Submission status: Wrong Answer

Solution code:
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)]
    for lrd in LRD:
        l, r, d = lrd
        adj_list[l-1].append((l-1, r-1, d))
        adj_list[r-1].append((r-1, l-1, -d))
    
    X = [None]*N
    import collections

    for i in range(N):
        if X[i] is not None:
            continue
        q = collections.deque(adj_list[i])
        X[i] = 0
        while q:
            src, nxt, d = q.pop()
            if X[nxt] is not None:
                if X[nxt] != X[src] + d:
                    return
            else:
                X[nxt] = X[src] + d
                q.extend(adj_list[nxt])
    print("Yes")

    


if '__main__' == __name__:
    resolve()

Submission status: Wrong Answer

Solution code:
import sys
from typing import List

sys.setrecursionlimit(1000000)

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

g = [[] for _ in range(N)]

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


def ok(cur: int, ds: int, dists: List[int]):
    dists[cur] = ds

    flag = True
    for nx, d in g[cur]:
        if dists[nx] >= 0:
            flag &= abs(dists[nx] - dists[cur]) == d
        elif flag:
            flag &= ok(nx, ds + d, dists)


    return flag


dists = [-1] * N
ans = True
for i in range(N):
    if ans and dists[i] < 0:
        ans &= ok(i, 0, dists)

print("Yes" if ans else "No")

Submission status: Wrong Answer

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

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

from collections import defaultdict
V = defaultdict(list)
 
for _ in range(m):
    a, b,c = map(int, input().split())
    V[a].append([b,c])

inf  = float("inf") 

def dfs(source):
    dist = [inf]*(n+1)
    dist[source] = 0
    q = [source]
    while q:
        a = q.pop()
        for b in V[a]:
            if dist[b[0]]!=inf:
                if dist[b[0]] != dist[a] +b[1]:
                    print("No")
                    exit()
            else:
                dist[b[0]] = dist[a] + b[1]
                q.append(b[0])

    print("Yes")

dfs(min(V))

Submission status: Wrong Answer

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

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

from collections import defaultdict
V = defaultdict(list)
 
for _ in range(m):
    a, b,c = map(int, input().split())
    V[a].append([b,c])
    V[b].append([a,-c])

inf  = float("inf") 

def dfs(source):
    dist = [inf]*(n+1)
    dist[source] = 0
    q = [source]
    while q:
        a = q.pop()
        for b in V[a]:
            if dist[b[0]]!=inf:
                if dist[b[0]] != dist[a] +b[1]:
                    print("No")
                    exit()
            else:
                dist[b[0]] = dist[a] + b[1]
                q.append(b[0])

    print("Yes")

dfs(min(V))

Submission status: Wrong Answer

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

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

from collections import defaultdict
V = defaultdict(list)
 
for _ in range(m):
    a, b,c = map(int, input().split())
    V[a].append([b,c])
    V[b].append([a,-c])

inf  = float("inf") 

def dfs(source):
    dist = [inf]*(n+1)
    dist[source] = 0
    q = [source]
    while q:
        a = q.pop()
        for b in V[a]:
            if dist[b[0]]!=inf:
                if dist[b[0]] != dist[a] +b[1]:
                    print("No")
                    exit()
            else:
                dist[b[0]] = dist[a] + b[1]
                q.append(b[0])
    return dist

dfs(min(V))

print("Yes")

Submission status: Wrong Answer

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
        while edge[u]:
            v, w = edge[u].pop()
            if (v in costs) 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]:
            costs[u] = 0
            dfs(u, 0)
    print("Yes")


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
class uf():
    def __init__(self,n):
        self.n=n
        self.pa=[-1]*n
    def find(self,x):
        if self.pa[x]<0:
            return x
        else:
            self.pa[x]=self.find(self.pa[x])
            return self.pa[x]
    def unite(self,x,y):
        x=self.find(x)
        y=self.find(y)
        if x==y:
        	return True
        else:
            if self.pa[x]>self.pa[y]:
                x,y=y,x
            self.pa[x]+=self.pa[y]
            self.pa[y]=x
            return True
    def same(self,x,y):
        return self.find[x]==find.pa[y]
    def size(self,x):
        return -self.pa[self.find(x)] 
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
uf=uf(n)
d={}
for i in range(n):
    d[i]=[]
for i in range(m):
    a,b,c=map(int,input().split())
    uf.unite(a-1,b-1)
    d[a-1].append([b-1,c])
    d[b-1].append([a-1,c])
l=[-1]*n
for i in range(n):
    if uf.pa[i]<0:
        l[i]=0
        for x in d[i]:
            a,b=x
            l[a]=b
    else:
        for x in d[i]:
            a,b=x
            if l[a]==l[i]==-1:
              l[a]=0
              l[i]=b
            elif l[a]==-1:
                l[a]=l[i]+b
            elif l[i]==-1:
                l[i]=l[a]+b
            elif abs(l[i]-l[a])!=b:
                print('No')
                quit()

print('Yes')

Submission status: Wrong Answer

Solution code:
class uf():
    def __init__(self,n):
        self.n=n
        self.pa=[-1]*n
    def find(self,x):
        if self.pa[x]<0:
            return x
        else:
            self.pa[x]=self.find(self.pa[x])
            return self.pa[x]
    def unite(self,x,y):
        x=self.find(x)
        y=self.find(y)
        if x==y:
        	return True
        else:
            if self.pa[x]>self.pa[y]:
                x,y=y,x
            self.pa[x]+=self.pa[y]
            self.pa[y]=x
            return True
    def same(self,x,y):
        return self.find[x]==find.pa[y]
    def size(self,x):
        return -self.pa[self.find(x)] 
import sys
input=sys.stdin.readline
n,m=map(int,input().split())
uf=uf(n)
d={}
for i in range(n):
    d[i]=[]
for i in range(m):
    a,b,c=map(int,input().split())
    uf.unite(a-1,b-1)
    d[a-1].append([b-1,c])
    d[b-1].append([a-1,c])
l=[-1]*n
for i in range(n):
    if uf.pa[i]<0:
        l[i]=0
        for x in d[i]:
            a,b=x
            l[a]=b
    else:
        for x in d[i]:
            a,b=x
            if l[a]==-1:
                l[a]=l[i]+b
            elif l[i]==-1:
                l[i]=l[a]+b
            elif abs(l[i]-l[a])!=b:
                print('No')
                quit()

print('Yes')

Submission status: Wrong Answer

Solution code:
N,M=map(int, input().split())
if M==0:
    print("Yes")
    exit()
L=[]
for i in range(M):
    l,r,d=map(int, input().split())
    L.append((l-1,r-1,d))

L=sorted(L)
done=[float("INF")]*N
for i in range(M):
    t=L[i]
    l,r,d=t
    
    nowl=done[l]
    nowr=done[r]
    if nowl==float("INF") and nowr==float("INF"):
        done[l]=0
        done[r]=d
    elif nowl==float("INF"):
        done[l]=nowr-d
    elif nowr==float("INF"):
        done[r]=nowl+d
    else:
        if nowr-nowl!=d:
            print("No")

            exit()
#print(done)
print("Yes")

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
info = []
for _ in range(m):
    l,r,d = map(int,input().split())
    l -= 1
    r -= 1
    if l > r:
        l,r = r,l
        d = -d
    info.append((l,r,d))
info.sort(key=lambda x: x[0])
# print(info)
INF = float("INF")
pos = [INF]*n

ans = "Yes"
for i in range(m):
    l,r,d = info[i]
    if pos[l] == INF:
        pos[l] = 0
        pos[r] = d
    elif pos[r] == INF:
        pos[r] = pos[l]+d
    elif pos[l]+d != pos[r]:
        ans = "No"
        break
print(ans)

Submission status: Wrong Answer

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

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

L=sorted(L)
done=[float("INF")]*N
for i in range(M):
    t=L[i]
    l,r,d=t
    nowl=done[l]
    nowr=done[r]
    if nowl==float("INF") and nowr==float("INF"):
        done[l]=0
        done[r]=d
    elif nowl==float("INF"):
        done[l]=nowr-d
    elif nowr==float("INF"):
        done[r]=nowl+d
    else:
        if nowr-nowl!=d:
            print("No")
            exit()

print("Yes")

Submission status: Wrong Answer

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))
    v = -1
    for i in range(N):
        if len(G[i]) > 0:
            v = i
    val = [inf] * N
    def bfs(ini):
        flag = True
        q = deque([ini])
        visited = set()
        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

    val[v] = 0
    if bfs(v):
        print("Yes")
    else:
        print("No")
    return




main()

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
edges = [[] for i in range(n)]
for i in range(m):
    li, ri, di = map(int, input().split())
    li, ri = li-1, ri-1
    edges[li].append((ri, di))
    edges[ri].append((li, -di))

coordinate = [None for i in range(n)]
for i in range(n):
    edge = edges[i]
    if coordinate[i] == None:
        coordinate[i] = 0
        start = 0
    else:
        start = coordinate[i]
    for end, dist in edge:
        if coordinate[end] == None:
            coordinate[end] = start + dist
        else:
            if coordinate[end] != start + dist:
                print('No')
                exit()
print('Yes')

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
nodeinfo = []
for i in range(m):
    li, ri, di = map(int, input().split())
    li, ri = li-1, ri-1
    nodeinfo.append([li, ri, di])

ans = 'Yes'
human = [None for i in range(n)]
for i in range(m):
    li, ri, di = nodeinfo[i]
    if human[li] == None and human[ri] == None:
        human[li] = 0
        human[ri] = di
    elif human[li] == None:
        human[li] = human[ri] - di
    elif human[ri] == None:
        human[ri] = human[li] + di
    else:
        if di != human[ri] - human[li]:
            ans = 'No'

print(ans)

Submission status: Wrong Answer

Solution code:
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())

n, m = map(int, input().split())
nodeinfo = []
for i in range(m):
    li, ri, di = map(int, input().split())
    li, ri = li-1, ri-1
    nodeinfo.append([li, ri, di])

ans = 'Yes'
human = [None for i in range(n)]
uf = UnionFind(n)
for i in range(m):
    li, ri, di = nodeinfo[i]
    uf.union(li, ri)
    if human[li] == None and human[ri] == None:
        human[li] = 0
        human[ri] = di
    elif human[li] == None:
        human[li] = human[ri] - di
    elif human[ri] == None:
        human[ri] = human[li] + di
    else:
        if di != human[ri] - human[li]:
            ans = 'No'

dic = uf.all_group_members()
for lst in dic.values():
    group = []
    for i in lst:
        group.append(human[i])
    if None in group: continue
    if max(group) - min(group) > 10**9:
        ans = 'No'

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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))

top=[False]*n

for i in range(n):
    memo=[False]*n
    if top[i]:
        l=deque([(i,top[i])])
        memo[i]=top[i]
    else:
        l=deque([(i,0)])
        memo[i]=0
    while l:
        now=l.popleft()
        for to in edge[now[0]]:
            if top[to[0]]:
                if top[to[0]]==to[1]+memo[now[0]]:
                    memo[to[0]]=top[to[0]]
                    continue
                else:
                    print("No")
                    exit()
            else:
                top[to[0]]=to[1]+memo[now[0]]
                memo[to[0]]=top[to[0]]

print("Yes")

Submission status: Wrong Answer

Solution code:
from collections import deque

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))

top=[False]*n

for i in range(n):
    memo=[False]*n
    if top[i]:
        l=deque([(i,top[i])])
        memo[i]=top[i]
    else:
        l=deque([(i,0)])
        memo[i]=0
    while l:
        now=l.popleft()
        for to in edge[now[0]]:
            if top[to[0]]:
                if top[to[0]]==to[1]+memo[now[0]]:
                    continue
                else:
                    print("No")
                    exit()
            else:
                top[to[0]]=to[1]+memo[now[0]]

print("Yes")

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
G = [[] for _ in range(n)]
indeg = [0] * n

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

from collections import deque
ng = False
visited_cost = [0] * n
for start, deg in enumerate(indeg):
    if deg > 1 or visited_cost[start] > 0:
        continue
    st = deque([[start, 0]])
    while st:
        i, cost = st.pop()
        for ni, nd in G[i]:
            if visited_cost[ni] == 0:
                visited_cost[ni] = cost + nd
                st.append([ni, cost + nd])
            elif visited_cost[ni] == cost + nd:
                continue
            else:
                # 既に記録されていて、矛盾している場合
                # 終了
                ng = True
                break
        if ng:
            break
    if ng:
        break

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

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int, input().split())
A=[[]for _ in range(N)]
V=[False]*N
X=[0]*N
x=0
for i in range(M):
  L,R,D=map(int, input().split())
  A[L-1].append((R-1,D))
  A[R-1].append((L-1,-D))
  
for i in range(N):
  if V[i]==False:
    stack=deque([(i,x)])
    V[i]=True
    while stack:
      now,dx=stack.popleft()
      for new,di in A[now]:
        if V[new]:
          if X[new]!=dx+di:
            print('No')
            exit()
        else:
          X[new]=dx+di
          V[new]=True
          stack.append((new,x+di))

if max(X)-min(X)>10**9:
  print('No')
else:
  print('Yes')

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int, input().split())
A=[[]for _ in range(N)]
V=[False]*N
X=[0]*N
x=0
for i in range(M):
  L,R,D=map(int, input().split())
  A[L-1].append((R-1,D))
  A[R-1].append((L-1,-D))
  
for i in range(N):
  if V[i]==False:
    stack=deque([(i,x)])
    V[i]=True
    while stack:
      now,x=stack.popleft()
      for new,di in A[now]:
        if V[new]:
          if X[new]!=x+di:
            print('No')
            exit()
        else:
          X[new]=x+di
          V[new]=True
          stack.append((new,x+di))

if max(X)-min(X)>10**9:
  print('No')
else:
  print('Yes')

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int, input().split())
A=[[]for _ in range(N)]
V=[False]*N
X=[0]*N
x=0
for i in range(M):
  L,R,D=map(int, input().split())
  A[L-1].append((R-1,D))
  A[R-1].append((L-1,D))
for i in range(N):
  if V[i]==False:
    stack=deque([(i,x)])
    V[i]=True
    while stack:
      now,x=stack.popleft()
      for new,di in A[now]:
        if V[new]:
          if X[new]!=x+di:
            print('No')
            exit()
        else:
          X[new]=x+di
          V[new]=True
          stack.append((new,x+di))
print('Yes')

Submission status: Wrong Answer

Solution code:
from collections import deque
N,M=map(int, input().split())
A=[[]for _ in range(N)]
V=[False]*N
X=[0]*N
x=0
for i in range(M):
  L,R,D=map(int, input().split())
  A[L-1].append((R-1,D))
  A[R-1].append((L-1,D))
for i in range(N):
  if V[i]==False:
    stack=deque([(i,x)])
    V[i]=True
    while stack:
      now,x=stack.popleft()
    for new,di in A[now]:
      if V[new]:
        if X[new]!=x+di:
          print('No')
          exit()
      else:
        X[new]=x+di
        V[new]=True
        stack.append((new,x+di))
print('Yes')

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(s):
    global dist, visit
    q = deque()
    q.append(s)
    dist[s] = 0
    visit[s] = s
    x = 0
    y = deque()
    while q:
        p = q.popleft()
        for g in G[p]:
            if dist[g[0]] == a:
                dist[g[0]] = dist[p] + g[1] + x
                y.append(g[0])
                visit[g[0]] = s
                q.append(g[0])
            else:
                if not dist[g[0]] == dist[p] + g[1] + x:
                    if visit[g[0]] == s:
                        print("No")
                        exit()
                    else:
                        if x == 0:
                            x = dist[g[0]] - (dist[p] + g[1])
                            while y:
                                z = y.popleft()
                                dist[z] += x
                        else:
                            print("No")
                            exit()
                    

n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
for _ in range(m):
    l, r, d = map(int, input().split())
    G[l].append([r, d])
a = -pow(10, 9)
dist = [a] * (n + 1)
visit = [0] * (n + 1)
for i in range(1, n + 1):
    if dist[i] == a:
        bfs(i)
print("Yes")

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs(s):
    global dist, visit
    q = deque()
    q.append(s)
    dist[s] = 0
    visit[s] = s
    x = 0
    y = deque()
    while q:
        p = q.popleft()
        y.append(p)
        for g in G[p]:
            if dist[g[0]] == a:
                dist[g[0]] = dist[p] + g[1] + x
                visit[g[0]] = s
                q.append(g[0])
            else:
                if not dist[g[0]] == dist[p] + g[1] + x:
                    if visit[g[0]] == s:
                        print("No")
                        exit()
                    else:
                        if x == 0:
                            x = dist[g[0]] - (dist[p] + g[1])
                            while y:
                                z = y.popleft()
                                dist[z] += x
                        else:
                            print("No")
                            exit()
                    

n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
for _ in range(m):
    l, r, d = map(int, input().split())
    G[l].append([r, d])
a = -pow(10, 9)
dist = [a] * (n + 1)
visit = [0] * (n + 1)
for i in range(1, n + 1):
    if dist[i] == a:
        bfs(i)
print("Yes")

Submission status: Wrong Answer

Solution code:
def get_root(s):
    if s != root[s]:
        root[s] = get_root(root[s])
        return root[s]
    return s

def unite(s, t):
    root_s = get_root(s)
    root_t = get_root(t)
    if not root_s == root_t:
        if rank[s] == rank[t]:
            root[root_t] = root_s
            rank[root_s] += 1
        elif rank[s] > rank[t]:
            root[root_t] = root_s
        else:
            root[root_s] = root_t

def same(s, t):
    if get_root(s) == get_root(t):
        return True
    else:
        return False

n, m = map(int, input().split())
root = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
G = [[] for _ in range(2 * m)]
for i in range(m):
    l, r, d = map(int, input().split())
    G[2 * i] = [l, r, d]
    G[2 * i + 1] = [r, l, -d]
G.sort()
a = -10000000
x = [a] * (n + 1)
for g in G:
    if not same(g[0], g[1]):
        unite(g[0], g[1])
        if x[g[0]] == a and x[g[1]] == a:
            x[g[0]], x[g[1]] = 10000000, 10000000 + g[2]
        elif x[g[0]] == a:
            x[g[0]] = x[g[1]] - g[2]
        elif x[g[1]] == a:
            x[g[1]] = x[g[0]] + g[2]
        else:
            if not x[g[0]] == x[g[1]] - g[2]:
                print("No")
                exit()
    else:
        if not x[g[0]] == x[g[1]] - g[2]:
            print("No")
            exit()
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

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

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w

    def weig(self, x):
        self.find(x)
        return self.weight[x]

    def diff(self, x, y):
        return self.weig(y) - self.weig(x)

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

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


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

for i in range(m):
    l, r, d = map(int, input().split())
    l -= 1;r -= 1
    if UF.same(l, r):
        if d != abs(UF.diff(l, r)):
            exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
class WeightedUnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.weight = [0] * n

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

    def union(self, x, y, w):
        w += self.weight[x] - self.weight[y]
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
            w = -w
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        self.weight[y] = w

    def weig(self, x):
        self.find(x)
        return self.weight[x]

    def diff(self, x, y):
        return self.weig(y) - self.weig(x)

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

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


n, m = map(int, input().split())
UF = WeightedUnionFind(n + 1)

for i in range(m):
    l, r, d = map(int, input().split())
    if UF.same(l, r):
        if d != abs(UF.diff(l, r)):
            exit(print("No"))
    else:
        UF.union(l, r, d)
print("Yes")