Problem:


Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1



Sample input:
3
1 2 2
2 3 1


Sample output:
0
0
1

Submission status: Wrong Answer

Solution code:
*D, = open(0)
n = int(D[0])

v = [[] for _ in range(n+1)]

dist = {}

for i in range(1, n):
    a, b, d = map(int, D[i].split())
    v[a].append(b)
    v[b].append(a)
    dist[(a,b)]=d
    dist[(b,a)]=d
    
color = [None for _ in range(n+1)]
color[1]=True

cnt = 1
next_vertex = [1]
while cnt < n:
    new_vertex = []
    for it in next_vertex:
        for node in v[it]:
            if color[node] != None:
                continue
            
        if dist[(it, node)]%2 == 0:
            color[node] = color[it]
        else:
            color[node] = not color[it]
        cnt += 1
        new_vertex.append(node)
        
    next_vertex = new_vertex



for i in range(1, n+1):
    if color[i]:
        print('0')
    else:
        print('1')

Submission status: Wrong Answer

Solution code:
N=int(input())
if N>=1e4:
  quit()
G=[[] for i in range(N)]
res=[-1]*N
def dfs(v,p,c):
  res[v]=c
  for nv,w in G[v]:
    if nv==p:
      continue
    if (w & 1):
      dfs(nv,v,1-c)
    else:
      dfs(nv,v,c)
 
for i in range(N-1):
  u,v,w=map(int,input().split())
  u-=1
  v-=1
  G[u].append((v,w))
  G[v].append((u,w))
dfs(0,-1,0)
for i in range(N):
  print(res[i])

Submission status: Wrong Answer

Solution code:
N=int(input())
if N>=1e4:
  quit()
G=[[] for i in range(N)]
res=[0]*N
def dfs(v,p,c):
  res[v]=c
  for nv,w in G[v]:
    if nv==p:
      continue
    if (w & 1):
      dfs(nv,v,1-c)
    else:
      dfs(nv,v,c)

for i in range(N-1):
  u,v,w=map(int,input().split())
  u-=1
  v-=1
  G[u].append((v,w))
  G[v].append((u,w))
dfs(0,-1,0)
for i in range(N):
  print(res[i])

Submission status: Wrong Answer

Solution code:
n = int(input())

dp = [-1] * (n + 1)
for _ in range(n-1):
    u, v, w = map(int, input().split())
    if dp[u] < 0 and dp[v] < 0:
        dp[u] = w%2
        dp[v] = dp[u]
    elif dp[u] < 0:
        if w % 2 == 0:
            dp[u] = dp[v]
        else:
            dp[u] = dp[v] ^ 1
    elif dp[v] < 0:
        if w % 2 == 0:
            dp[v] = dp[u]
        else:
            dp[v] = dp[u] ^ 1

for a in dp[1:]:
    print(a)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)

n = int(input())
path = [[] for _ in range(n + 1)]
for _ in range(n - 1):
  u, v, w = map(int, input().split())
  path[u].append((v, w))
  path[v].append((u, w))
d = [-1] * (n + 1)

def walk(i, c):
  if d[i] == -1:
    d[i] = c
    for x, w in path[i]:
      walk(x, c + w)

walk(1, 0)
print(*d[1:], sep="\n")

Submission status: Wrong Answer

Solution code:
n = int(input())
t = {i:{} for i in range(n)}
ans = [-1]*n
for _ in range(n-1):
    u, v, w = map(int, input().split())
    t[u-1][v-1] = w
    t[v-1][u-1] = w

def dfs(x):
    for y in t[x]:
        if ans[x] == -1:
            ans[y] = ans[x] if t[x][y] % 2 == 0 else 1-ans[x]
            dfs(y)

ans[0] = 0
dfs(0)
for i in range(n):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
'''input
1

'''

N = int(input())

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

for i in range(N-1):
	a, b, w = [int(x) for x in input().split()]
	a -= 1
	b -= 1
	edges[a].append((b, w))
	edges[b].append((a, w))

for _ in range(N):
	print(0)

Submission status: Wrong Answer

Solution code:
N = int(input())

node = [0 for _ in range(N)]
edge = [list(map(int, input().split())) for _ in range(N-1)]

for e in edge:
    if e[0] > e[1]:
        e[0], e[1] = e[1], e[0]

edge.sort()

for e in edge:
    if e[2]%2 == 1:
        node[e[1]-1] = node[e[0]-1] ^1

print("\n".join(map(str, node)))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
class PotUnionFind:
    def __init__(self, size):
        self.parent = [-1 for i in range(size)]#非負なら親ノード，負ならグループの要素数
        self.diff_p = [0 for i in range(size)]#親ノードを基準としたポテンシャル

    def root(self, x): #root(x): xの根ノードを返す
        if self.parent[x] < 0:
            return x
        else:
            rx = self.root(self.parent[x]) #xをxの根rxに直接つなぎたい
            self.diff_p[x] += self.diff_p[self.parent[x]] #そのために，diff(rx,x)を計算
            self.parent[x] = rx #xをrxに直接つなげる
            return rx

    def merge(self, x, y, dxy): #ポテンシャル差の条件p(y)-p(x)=dxyでxとyのグループをまとめる
        rx = self.root(x) #rxを新たにxと名づける
        ry = self.root(y) #ryを新たにyと名づける
        dxy += self.diff_p[x] - self.diff_p[y] #dxyをdiff(rx,ry)で置き換え
        x,y=rx,ry
        if x == y:
            return False
        if self.parent[x] > self.parent[y]: #xの要素数がyの要素数より「小さい」とき入れ替える
            x,y,dxy=y,x,-dxy
        self.parent[x] += self.parent[y] #xの要素数を更新
        self.parent[y] = x #yをxにつなぐ
        self.diff_p[y] = dxy #yの相対ポテンシャルを更新
        return True

    def issame(self, x, y): #issame(x,y): xとyが同じグループにあるならTrue
        return self.root(x) == self.root(y)
        
    def diff(self,x,y): #diff(x,y): xを基準としたyのポテンシャルを返す 
        if self.root(x) == self.root(y): #この時点でxの親はroot(x)
            return self.diff_p[y] - self.diff_p[x]
        else:
            return None

    def size(self,x): #size(x): xのいるグループの要素数を返す
        return -self.parent[self.root(x)]

n = int(input())

T=PotUnionFind(n)
for _ in [0]*(n-1):
    u,v,w = [int(i) for i in input().split()]
    T.merge(u-1,v-1,w)

for i in range(n):
    print(T.diff(0,i))

Submission status: Wrong Answer

Solution code:
from collections import deque

n = int(input())

node = [-1 for _ in range(n + 1)]
que = deque()
root = None
for _ in range(n - 1):
    v1, v2, w = map(int, input().split())
    if root is None:
        root = v1
        node[v1] = 0
    if node[v1] == -1 and node[v2] == -1:
        que.append((v1, v2, w))
    elif node[v1] == -1:
        v1, v2 = v2, v1
    if w % 2 == 0:
        node[v2] = node[v1]
    else:
        node[v2] = 0 if node[v1] == 1 else 1

while len(que) > 0:
    v1, v2, w = que.popleft()
    if node[v1] == -1:
        v1, v2 = v2, v1
    if w % 2 == 0:
        node[v2] = node[v1]
    else:
        node[v2] = 0 if node[v1] == 1 else 1

for i in range(1, n + 1):
    print(node[i])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# IMPORT ###############################################################################################################
import sys                                                      # システム
sys.setrecursionlimit(10**6)                                    # 再帰処理の上限変更
from collections import deque, Counter                          # キュー・個数カウント
from itertools   import accumulate, permutations, combinations  # 累積和・順列・組み合わせ
from operator    import itemgetter                              # ソート補助
from bisect      import bisect_left, bisect_right, bisect       # 二分探索
from heapq       import heappop, heappush                       # プライオリティキュー
from fractions   import gcd                                     # 最大公約数
from math        import ceil, floor, sqrt, cos, sin, tan, pi    # 数学処理
from copy        import deepcopy                                # オブジェクトコピー
import numpy         as np                                      # 数値計算

# MAIN #################################################################################################################
def main():
    # Init #############################################################################################################
    im = InputManager()
    # Input ############################################################################################################
    n = im.inputSingle()
    nodes = [Node(i+1) for i in range(n)]
    for i in range(n-1):
        u, v, w = im.inputMultiple()
        nodes[u-1].addConnection(nodes[v-1], w)
        nodes[v-1].addConnection(nodes[u-1], w)
    # Logic ############################################################################################################
    weights = [-1 for i in range(n)]
    for i in range(n):
        weights[i] = Node.rootFind(nodes[0], nodes[i], [nodes[i]], 0, weights)
    # Output ###########################################################################################################
    print(weights)
    for weight in weights:
        if weight % 2 == 0:
            print(0)
        else:
            print(1)
    # Return ###########################################################################################################
    return

class Node(object):
    def __init__(self, index):
        self._index = index
        self._connections = []
    
    @property
    def connections(self):
        return self._connections
    
    def addConnection(self, node, weight):
        self._connections.append({"node": node, "weight": weight})
    
    def __eq__(self, other):
        return self._index == other._index
    
    @staticmethod
    def rootFind(targetNode, baseNode, excludeNodes, weight, weightList):
        if baseNode == targetNode:
            # print("Founded: " + str(weight))
            return weight
        if weightList[baseNode._index - 1] > 0:
            return weightList[baseNode._index - 1] + weight
        for connection in baseNode.connections:
            if connection["node"] in excludeNodes:
                continue
            else:
                # print(str(baseNode._index) + " -> " + str(connection["node"]._index) + " : " + str([exclude._index for exclude in excludeNodes]))
                tmpExcludeNodes = deepcopy(excludeNodes)
                tmpExcludeNodes.append(connection["node"])
                calculatedWeight = Node.rootFind(targetNode, connection["node"], tmpExcludeNodes, weight + connection["weight"], weightList)
                if calculatedWeight > 0:
                    return calculatedWeight
        # print("Not Founded")
        return -1

# INPUT MANAGER ########################################################################################################
class InputManager(object):
    def __init__(self):
        pass

    @staticmethod
    def inputSingle(dtype=int):
        return dtype(input())
    
    @staticmethod
    def inputMultiple(dtype=int, aslist=False):
        if aslist:
            return list(map(dtype, input().split()))
        else:
            return map(dtype, input().split())

    @staticmethod
    def input2D(h, dtype=int):
        return [list(map(dtype, input().split())) for i in range(h)]

# CALL MAIN ############################################################################################################
main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# IMPORT ###############################################################################################################
import sys                                                      # システム
sys.setrecursionlimit(10**6)                                    # 再帰処理の上限変更
from collections import deque, Counter                          # キュー・個数カウント
from itertools   import accumulate, permutations, combinations  # 累積和・順列・組み合わせ
from operator    import itemgetter                              # ソート補助
from bisect      import bisect_left, bisect_right, bisect       # 二分探索
from heapq       import heappop, heappush                       # プライオリティキュー
from fractions   import gcd                                     # 最大公約数
from math        import ceil, floor, sqrt, cos, sin, tan, pi    # 数学処理
from copy        import deepcopy                                # オブジェクトコピー
import numpy         as np                                      # 数値計算

# MAIN #################################################################################################################
def main():
    # Init #############################################################################################################
    im = InputManager()
    # Input ############################################################################################################
    n = im.inputSingle()
    nodes = [Node(i+1) for i in range(n)]
    for i in range(n-1):
        u, v, w = im.inputMultiple()
        nodes[u-1].addConnection(nodes[v-1], w)
        nodes[v-1].addConnection(nodes[u-1], w)
    # Logic ############################################################################################################
    weights = [-1 for i in range(n)]
    for i in range(n):
        weights[i] = Node.rootFind(nodes[0], nodes[i], [nodes[i]], 0, weights)
    # Output ###########################################################################################################
    # print(weights)
    for weight in weights:
        if weight % 2 == 0:
            print(0)
        else:
            print(1)
    # Return ###########################################################################################################
    return

class Node(object):
    def __init__(self, index):
        self._index = index
        self._connections = []
    
    @property
    def connections(self):
        return self._connections
    
    def addConnection(self, node, weight):
        self._connections.append({"node": node, "weight": weight})
    
    def __eq__(self, other):
        return self._index == other._index
    
    @staticmethod
    def rootFind(targetNode, baseNode, excludeNodes, weight, weightList):
        if weightList[baseNode._index - 1] > 0:
            return weightList[baseNode._index - 1]
        if baseNode == targetNode:
            # print("Founded: " + str(weight))
            return weight
        for connection in baseNode.connections:
            if connection["node"] in excludeNodes:
                continue
            else:
                # print(str(baseNode._index) + " -> " + str(connection["node"]._index) + " : " + str([exclude._index for exclude in excludeNodes]))
                tmpExcludeNodes = deepcopy(excludeNodes)
                tmpExcludeNodes.append(connection["node"])
                calculatedWeight = Node.rootFind(targetNode, connection["node"], tmpExcludeNodes, weight + connection["weight"], weightList)
                if calculatedWeight > 0:
                    return calculatedWeight
        # print("Not Founded")
        return -1

# INPUT MANAGER ########################################################################################################
class InputManager(object):
    def __init__(self):
        pass

    @staticmethod
    def inputSingle(dtype=int):
        return dtype(input())
    
    @staticmethod
    def inputMultiple(dtype=int, aslist=False):
        if aslist:
            return list(map(dtype, input().split()))
        else:
            return map(dtype, input().split())

    @staticmethod
    def input2D(h, dtype=int):
        return [list(map(dtype, input().split())) for i in range(h)]

# CALL MAIN ############################################################################################################
main()

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def m():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))


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

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

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

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

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

n = int(input())

u = WeightedUnionFind(n)
a = [0 for i in range(n)]
for i in range(n-1):
	z,x,v = m()
	u.union(z-1,x-1,v%2)

for i in range(1,n):
	if u.diff(0,i) % 2 != 0:
		a[i] = 1

for i in range(n):
	print(a[i])

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def m():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))


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

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

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

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

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

n = int(input())

u = WeightedUnionFind(n)
a = [0 for i in range(n)]
for i in range(n-1):
	z,x,v = m()
	u.union(z-1,x-1,v)

for i in range(1,n):
	if u.diff(0,i) % 2 != 0:
		a[i] = 1

for i in range(n):
	print(a[i])

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.dist = [0] * n
 
    def root(self, i, d):
        if self.parent[i] == i:
            return i, d
        else:
            self.parent[i], d2 = self.root(self.parent[i], d + self.dist[i])
            return self.parent[i], d2
    
    def find(self, x, y):
        return self.root(x) == self.root(y)
 
    def union(self, i, j, d):
        i2, d1 = self.root(i, 0)
        j2, d2 = self.root(j, 0)
        if i2 < j2 and i2 == 0:
            self.parent[j2] = i2
            self.dist[j] = d1 + d
        elif j2 < i2 and j2 == 0:
            self.parent[i2] = j2
            self.dist[i] = d2 + d
        elif i2 < j2 and i2 >= 1:
            self.parent[i2] = j2
            self.dist[i] = d2 + d
        else:
            self.parent[j2] = i2
            self.dist[j] = d1 + d
            
N = int(input())
ps = [list(map(int, input().split())) for _ in range(N-1)]
ps.sort()
tree = UnionFind(N)
for i, j, d in ps:
    tree.union(i-1, j-1, d)

for i in range(N):
    while tree.parent[i] != 0:
        tree.dist[i] += tree.dist[tree.parent[i]]
        i = tree.parent[i]
for d in tree.dist:
    if d % 2 == 0:
        print(1)
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
N = int(input())
order = "0"*N

L = [list(map(int, input().split())) for i in range(N-1)]

for i in range(N):
	for j in range(N-1):
		if L[j][0] == i:
			if (L[j][2])%2 == 1:
				order = order[:L[j][1] - 1] + "1" + order[L[j][1]:]

for i in range(len(order)):
	print(order[i])

Submission status: Wrong Answer

Solution code:
N = int(input())
order = "0"*N

L = [list(map(int, input().split())) for i in range(N-1)]

for i in range(N):
	for j in range(N-1):
		if L[j][0] == i:
			if (L[j][2])%2 == 1:
				order = order[:L[j][1] - 1] + "1" + order[L[j][1]:]

print(order)

Submission status: Wrong Answer

Solution code:
N = int(input())

# 初期の木の根とランクを設定（初めはみんな根なのでpar[i]=i）
par = [0 for i in range(N)]
rank = [0 for i in range(N)]
for n in range(N):
    par[n] = n
NG_list =[]
unite_list = []

# 木の根を探索する関数
# 根が自身でない場合は再帰的にたどる
# x,yが同じ集合に属するかの判定はroot(par[x])==root(par[y])か否か
def root(x):
    if par[x] == x:
        return x
    else:
        par[x] = root(par[x])
        return par[x]

# 繋げる操作を指定された時に動かす関数
def unite(x,y):
    x = par[x]
    y = par[y]
    # rankが低い方に高い方を繋げる
    if rank[x] < rank[y]:
        par[x] = y
    else:
        par[y] = x
        # 同じだった場合xのランクが一つ増える扱いになる
        if rank[x] == rank[y]:
            rank[x] += 1

# 実際にクエリを受け取って動かす
for i in range(N-1):
    u,v,w = map(int,input().split())
    u = u-1
    v = v-1
    if w % 2 == 0:
        unite(u,v)
        unite_list.append([u,v])
    else:
        NG_list.append([u,v])

for i in range(N):
    for j in range(i,N):
        if [i,j] in NG_list or [i,j] in unite_list:
            pass
        else:
            unite(i,j)



r1 = root(par[0])
print(0)
for i in range(1,N):
    if root(par[i])==r1:
        print(0)
    else:
        print(1)

Submission status: Wrong Answer

Solution code:
N = int(input())

# 初期の木の根とランクを設定（初めはみんな根なのでpar[i]=i）
par = [0 for i in range(N)]
rank = [0 for i in range(N)]
for n in range(N):
    par[n] = n
NG_list =[]
unite_list = []

# 木の根を探索する関数
# 根が自身でない場合は再帰的にたどる
# x,yが同じ集合に属するかの判定はroot(par[x])==root(par[y])か否か
def root(x):
    if par[x] == x:
        return x
    else:
        par[x] = root(par[x])
        return par[x]

# 繋げる操作を指定された時に動かす関数
def unite(x,y):
    x = par[x]
    y = par[y]
    # rankが低い方に高い方を繋げる
    if rank[x] < rank[y]:
        par[x] = y
    else:
        par[y] = x
        # 同じだった場合xのランクが一つ増える扱いになる
        if rank[x] == rank[y]:
            rank[x] += 1

# 実際にクエリを受け取って動かす
for i in range(N-1):
    u,v,w = map(int,input().split())
    u = u-1
    v = v-1
    if w % 2 == 0:
        unite(u,v)
        unite_list.append([u,v])
    else:
        NG_list.append([u,v])

for i in range(N):
    for j in range(N):
        if [i,j] in NG_list or [i,j] in unite_list:
            pass
        else:
            unite(i,j)



r1 = root(par[0])
print(0)
for i in range(1,N):
    if root(par[i])==r1:
        print(0)
    else:
        print(1)

Submission status: Wrong Answer

Solution code:
import numpy as np


def read():
    N = int(input().strip())  # N <= 10**5
    edges = dict()
    for i in range(N-1):
        # u[i] < v[i] は保証されている
        u, v, w = list(map(int, input().strip().split()))
        if u - 1 in edges.keys():
            edges[u - 1].update({v - 1: w % 2})
        else:
            edges.update({u - 1: {v - 1: w % 2}})
        if v - 1 in edges.keys():
            edges[v - 1].update({u - 1: w % 2})
        else:
            edges.update({v - 1: {u - 1: w % 2}})
    return N, edges


def solve(N, edges):
    c = [-1] * N  # -1: unvisited, 0: white, 1: black
    stack = list()
    c[0] = 0
    stack.append(0)
    while len(stack) > 0:
        s = stack.pop()
        for t in edges[s].keys():
            if c[t] == -1:
                print('visited')
                if edges[s][t]:
                    c[t] = 1 - c[s]
                else:
                    c[t] = c[s]
                stack.append(t)
    return c


if __name__ == '__main__':
    inputs = read()
    colors = solve(*inputs)
    for col in colors:
        print("%d" % col)

Submission status: Wrong Answer

Solution code:
import numpy as np


def read():
    N = int(input().strip())  # N <= 10**5
    to = [[]] * N
    cost = [[]] * N
    for i in range(N-1):
        # u[i] < v[i] は保証されている
        u, v, w = list(map(int, input().strip().split()))
        to[u-1].append(v-1)
        to[v-1].append(u-1)
        cost[u-1].append(w%2)
        cost[v-1].append(w%2)
    return N, to, cost


def solve(N, to, cost):
    c = np.ones((N, ), dtype=np.uint8) * -1  # -1: unvisited, 0: white, 1: black
    q = list()
    c[0] = 0
    q.append(0)
    while len(q) > 0:
        s = q.pop()
        for t in to[s]:
            if c[t] == -1:
                if cost[s][t]:
                    c[t] = 1 - c[s]
                else:
                    c[t] = c[s]
                q.append(t)
    return c


if __name__ == '__main__':
    inputs = read()
    colors = solve(*inputs)
    for col in colors:
        print("%d" % col)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.dist = [0] * n
 
    def root(self, i, d):
        if self.parent[i] == i:
            return i, d
        else:
            self.parent[i], d2 = self.root(self.parent[i], d + self.dist[i])
            return self.parent[i], d2
    
    def find(self, x, y):
        return self.root(x) == self.root(y)
 
    def union(self, i, j, d):
        i2, d1 = self.root(i, 0)
        j2, d2 = self.root(j, 0)
        if i2 < j2:
            self.parent[j2] = i2
            self.dist[j] = d1 + d
        else:
            self.parent[i2] = j2
            self.dist[i] = d2 + d
N = int(input())
ps = [list(map(int, input().split())) for _ in range(N-1)]
ps.sort()
tree = UnionFind(N)
for i, j, d in ps:
    tree.union(i-1, j-1, d)
    
for d in tree.dist:
    if d % 2 == 0:
        print(1)
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.dist = [0] * n
 
    def root(self, i, d):
        if self.parent[i] == i:
            return i, d
        else:
            self.parent[i], d2 = self.root(self.parent[i], d + self.dist[i])
            return self.parent[i], d2
    
    def find(self, x, y):
        return self.root(x) == self.root(y)
 
    def union(self, i, j, d):
        i2, d1 = self.root(i, 0)
        j2, d2 = self.root(j, 0)
        if i < j:
            self.parent[j2] = i2
            self.dist[j] = d1 + d
        else:
            self.parent[i2] = j2
            self.dist[i] = d2 + d
N = int(input())
ps = [list(map(int, input().split())) for _ in range(N-1)]
ps.sort()
tree = UnionFind(N)
for i, j, d in ps:
    tree.union(i-1, j-1, d)
    
for d in tree.dist:
    if d % 2 == 0:
        print(1)
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def hantei(i, oya=-1):
    if ans[i] != -1:
        return ans[i]
    for u, w in pea[i]:
        if u == oya: continue
        h = hantei(u, i)
        if h:
            re = ans[i] = (h + w) % 2
            return re

n = int(input())
pea = [[] for _ in range(n + 1)]
for _ in range(n - 1):
    u, v, w = map(int, input().split())
    w %= 2
    pea[u].append([v, w])
    pea[v].append([u, w])
ans = [-1] * (n + 1)
ans[1] = 1
for i in range(1, n + 1):
    print(hantei(i))

Submission status: Wrong Answer

Solution code:
# from collections import defaultdict
# dd = defaultdict(lambda: 0)

N = int(input())
T = [dict() for _ in range(N)]

for i in range(N-1):
    u, v, w = [int(x) for x in input().split()]
    u -= 1
    v -= 1
    T[u][v] = w
    T[v][u] = w

opened = {0}
g0 = {0}
used = {0}

while len(opened) != 0:
    n = opened.pop()
    for n2 in T[n]:
        if n2 in used:
            continue
        if T[n][n2] % 2 == 0:
            g0.add(n2)
        opened.add(n2)
        used.add(n2)

for i in range(N):
    print(0 if i in g0 else 1)

Submission status: Wrong Answer

Solution code:
N = int(input())
u = [0]*N
v = [0]*N
w = [0]*N
for n in range(N-1):
    u[n], v[n], w[n] = map(int, input().split())
    u[n] -= 1
    v[n] -= 1
color = [0]*N
color[0] = 1
x = 0
next_x = []
position = [0]*N
position[0] = 1
while position != [1]*N:
    for n in range(N):
        if u[n] == x and position[v[n]] == 0:
            if color[x] == 1 and w[n]%2 == 0:
                color[v[n]] = 1
            next_x.append(v[n])
        if v[n] == x and position[u[n]] == 0:
            if color[x] == 1 and w[n]%2 == 0:
                color[u[n]] = 1
            next_x.append(u[n])
    x = next_x.pop(-1)
    position[x] = 1
    continue
    
for n in range(N):
        if u[n] == x and position[v[n]] == 0:
            if w[n]%2 == 0:
                color[v[n]] = color[x]
        if v[n] == x and position[u[n]] == 0:
            if w[n]%2 == 0:
                color[u[n]] = color[x]

for n in range(N):
    print(color[n])

Submission status: Wrong Answer

Solution code:
#https://atcoder.jp/contests/abc126
# -*- coding: utf-8 -*-

n = int(input())
v = []
for i in range(n-1):
        v.append( list(map(int,input().split())))
done = [0] * (n+1)
def tree(v_id,kyori):
        done[v_id] = kyori%2 +1
        # print(v_id,kyori,done[v_id])
        for i,vv in enumerate(v):
                if vv[0] is v_id and done[vv[1]] is 0:
                        tree(vv[1],kyori+vv[2])
                elif vv[1] is v_id and done[vv[0]] is 0:
                        tree(vv[0],kyori+vv[2])
        return

for i in v:
        if i[0] is 1:
                tree(1,0)
                break

for i in done:
        if i is not 0:
                print(i-1)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.dist = [0] * n
 
    def root(self, i, d):
        if self.parent[i] == i:
            return i, d
        else:
            self.parent[i], self.dist[i] = self.root(self.parent[i], d + self.dist[i])
            return self.parent[i], self.dist[i]
    
    def find(self, x, y):
        return self.root(x) == self.root(y)
 
    def union(self, i, j, d):
        i, d1 = self.root(i, 0)
        j, d2 = self.root(j, 0)
        if i < j:
            self.parent[j] = i
            self.dist[j] = d1 + d
        else:
            self.parent[i] = j
            self.dist[i] = d2 + d
N = int(input())
ps = [list(map(int, input().split())) for _ in range(N-1)]
ps.sort()
tree = UnionFind(N)
for i, j, d in ps:
    tree.union(i-1, j-1, d)
    
for d in tree.dist:
    if d % 2 == 0:
        print(1)
    else:
        print(0)