X(or)-mas Tree (Codeforces 1615D)
Tags: Others, dsu

'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are $$$n$$$ nodes in the tree, connected by $$$n-1$$$ edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation.  He has $$$m$$$ elves come over and admire his tree. Each elf is assigned two nodes, $$$a$$$ and $$$b$$$, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the bitwise XOR of the values of the lights on the edges in that path.However, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned $$$(a_i, b_i)$$$, as well as the parity of the number of set bits in his favorite number. In other words, he remembers whether the number of $$$1$$$'s when his favorite number is written in binary is odd or even.Help Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history!

Input: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow.The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq m \leq 2 \cdot 10^5$$$) — the size of tree and the number of elves respectively.The next $$$n-1$$$ lines of each test case each contains three integers, $$$x$$$, $$$y$$$, and $$$v$$$ ($$$1 \leq x, y \leq n$$$; $$$-1 \leq v < 2^{30}$$$) — meaning that there's an edge between nodes $$$x$$$ and $$$y$$$. If   $$$v = -1$$$: Santa doesn't remember what the set of lights were on for this edge.  $$$v \geq 0$$$: The set of lights on the edge is $$$v$$$. The next $$$m$$$ lines of each test case each contains three integers, $$$a$$$, $$$b$$$, and $$$p$$$ ($$$1 \leq a, b \leq n$$$; $$$a \neq b$$$; $$$0 \leq p \leq 1$$$) — the nodes that the elf was assigned to, and the parity of the number of set bits in the elf's favorite number.It is guaranteed that the sum of all $$$n$$$ and the sum of all $$$m$$$ don't exceed $$$2 \cdot 10^5$$$ each.It is guaranteed that the given edges form a tree.

Output: For each test case, first print either YES or NO (in any case), whether there's a tree consistent with Santa's memory or not. If the answer is YES, print $$$n-1$$$ lines each containing three integers: $$$x$$$, $$$y$$$, and $$$v$$$ ($$$1 \le x, y \le n$$$; $$$0 \le v < 2^{30}$$$) — the edge and the integer on that edge. The set of edges must be the same as in the input, and if the value of some edge was specified earlier, it can not change. You can print the edges in any order.If there are multiple answers, print any.

Note: The first test case is the image in the statement.One possible answer is assigning the value of the edge $$$(1, 2)$$$ to $$$5$$$, and the value of the edge $$$(2, 5)$$$ to $$$3$$$. This is correct because:   The first elf goes from node $$$2$$$ to node $$$3$$$. This elf's favorite number is $$$4$$$, so he remembers the value $$$1$$$ (as $$$4$$$ has an odd number of $$$1$$$ bits in its binary representation).  The second elf goes from node $$$2$$$ to node $$$5$$$. This elf's favorite number is $$$3$$$, so he remembers the value $$$0$$$ (as $$$3$$$ has an even number of $$$1$$$ bits in its binary representation).  The third elf goes from node $$$5$$$ to node $$$6$$$. This elf's favorite number is $$$7$$$, so he remembers the value $$$1$$$ (as $$$7$$$ has an odd number of $$$1$$$ bits in its binary representation).  The fourth elf goes from node $$$6$$$ to node $$$1$$$. This elf's favorite number is $$$1$$$, so he remembers the value $$$1$$$ (as $$$1$$$ has an odd number of $$$1$$$ bits in its binary representation).  The fifth elf goes from node $$$4$$$ to node $$$5$$$. This elf's favorite number is $$$4$$$, so he remembers the number $$$1$$$ (as $$$4$$$ has an odd number of $$$1$$$ bits in its binary representation). Note that there are other possible answers.

Sample Inputs:
4
6 5
1 2 -1
1 3 1
4 2 7
6 3 0
2 5 -1
2 3 1
2 5 0
5 6 1
6 1 1
4 5 1
5 3
1 2 -1
1 3 -1
1 4 1
4 5 -1
2 4 0
3 4 1
2 3 1
3 3
1 2 -1
1 3 -1
1 2 0
1 3 1
2 3 0
2 1
1 2 1
1 2 0

Sample Outputs:
YES
1 2 0
1 3 1
2 4 7
3 6 0
2 5 0
YES
1 2 1
1 3 0
1 4 1
4 5 1
NO
NO

Solution (Python):
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import collections

def solve():
    (n, m) = map(int, input().split())
    edges = []
    for _ in range(n - 1):
        edges.append(list(map(int, input().split())))
    parites = []
    for _ in range(m):
        parites.append(list(map(int, input().split())))
    adj_parites = collections.defaultdict(list)
    xord = [-1 for _ in range(n + 1)]
    xord[1] = 0
    for (x, y, c) in edges:
        if c != -1:
            sc = 0
            while c:
                if c & 1:
                    sc += 1
                c >>= 1
            c = sc & 1
        adj_parites[x].append((y, c))
        adj_parites[y].append((x, c))
    for (x, y, c) in parites:
        adj_parites[x].append((y, c))
        adj_parites[y].append((x, c))
    q = collections.deque()
    q.append(1)
    flag = 1
    while q and flag:
        cur = q.popleft()
        if xord[cur] == -1:
            xord[cur] = 0
        for (to, c) in adj_parites[cur]:
            if c != -1:
                if xord[to] == -1:
                    xord[to] = xord[cur] ^ c
                    q.appendleft(to)
                elif xord[to] == xord[cur] ^ c:
                    pass
                else:
                    flag = 0
                    break
            elif xord[to] == -1:
                q.append(to)
    if not flag:
        print('NO')
        return
    else:
        print('YES')
    for (x, y, c) in edges:
        if c != -1:
            print(str(x) + ' ' + str(y) + ' ' + str(c))
        elif not (xord[x] ^ xord[y]) & 1:
            print(str(x) + ' ' + str(y) + ' 0')
        else:
            print(str(x) + ' ' + str(y) + ' 1')
for _ in range(int(input())):
    solve()

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_root(s):
    v = []
    while not s == root[s]:
        v.append(s)
        s = root[s]
    for i in v:
        root[i] = s
    return s

def unite(s, t):
    (rs, rt) = (get_root(s), get_root(t))
    if not rs ^ rt:
        return
    if rank[s] == rank[t]:
        rank[rs] += 1
    if rank[s] >= rank[t]:
        root[rt] = rs
        size[rs] += size[rt]
    else:
        root[rs] = rt
        size[rt] += size[rs]
    return

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

def get_size(s):
    return size[get_root(s)]

def popcount(x):
    x = (x & 1431655765) + (x >> 1 & 1431655765)
    x = (x & 858993459) + (x >> 2 & 858993459)
    x = (x & 252645135) + (x >> 4 & 252645135)
    x = (x & 16711935) + (x >> 8 & 16711935)
    x = (x & 65535) + (x >> 16 & 65535)
    return x
t = int(input())
ans = []
for _ in range(t):
    (n, m) = map(int, input().split())
    root = [i for i in range(2 * n + 1)]
    rank = [1 for _ in range(2 * n + 1)]
    size = [1 for _ in range(2 * n + 1)]
    e = [tuple(map(int, input().split())) for _ in range(n - 1)]
    for (x, y, v) in e:
        if v == -1:
            continue
        if popcount(v) & 1:
            unite(x, y + n)
            unite(x + n, y)
        else:
            unite(x, y)
            unite(x + n, y + n)
    for _ in range(m):
        (a, b, p) = map(int, input().split())
        if p:
            unite(a, b + n)
            unite(a + n, b)
        else:
            unite(a, b)
            unite(a + n, b + n)
    ans0 = 'YES'
    for i in range(1, n + 1):
        if same(i, i + n):
            ans0 = 'NO'
            break
    ans.append(ans0)
    if ans0 == 'NO':
        continue
    u = [0] * (n + 1)
    for i in range(1, n + 1):
        u[i] = get_root(i) // (n + 1)
    ans0 = []
    for (x, y, v) in e:
        if v == -1:
            v = u[x] ^ u[y]
        ans0.append(' '.join(map(str, (x, y, v))))
    ans.append('\n'.join(ans0))
sys.stdout.write('\n'.join(ans))

Solution (Python):
import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import deque
LANS = []
t = int(input())
for tests in range(t):
    (n, m) = map(int, input().split())
    EDGE = [list(map(int, input().split())) for i in range(n - 1)]
    ELF = [list(map(int, input().split())) for i in range(m)]
    E = [[] for i in range(n + 1)]
    NODES = [-1] * (n + 1)
    NODES[1] = 0
    for (x, y, c) in EDGE:
        if c != -1:
            sc = 0
            while c != 0:
                if c % 2 == 1:
                    sc += 1
                c //= 2
            c = sc % 2
        E[x].append((y, c))
        E[y].append((x, c))
    for (x, y, c) in ELF:
        E[x].append((y, c))
        E[y].append((x, c))
    Q = deque([1])
    flag = 1
    while Q and flag == 1:
        x = Q.popleft()
        if NODES[x] == -1:
            NODES[x] = 1
        for (to, c) in E[x]:
            if c != -1:
                if NODES[to] == -1:
                    NODES[to] = NODES[x] ^ c
                    Q.appendleft(to)
                elif NODES[to] == NODES[x] ^ c:
                    True
                else:
                    flag = 0
                    break
            elif NODES[to] == -1:
                Q.append(to)
    if flag == 0:
        LANS.append('NO')
        continue
    LANS.append('YES')
    for (x, y, c) in EDGE:
        if c != -1:
            LANS.append(str(x) + ' ' + str(y) + ' ' + str(c))
        elif (NODES[x] ^ NODES[y]) % 2 == 0:
            LANS.append(str(x) + ' ' + str(y) + ' 0')
        else:
            LANS.append(str(x) + ' ' + str(y) + ' 1')
sys.stdout.write('\n'.join(LANS))