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:
from collections import deque
import math
from functools import reduce

def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n = int(input())
ans = [-1] * n
ans[0] = 0

edges = [ [] for _ in range(n)]
for i in range(n-1):
    u,v,w = get_nums_l()
    edges[u-1].append([v-1,w%2==0])
    edges[v-1].append([u-1,w%2==0])

def aaa(x):
    # xを含むエッジ

    for edge in edges[x]:
        to = edge[0] # edgeのうちxじゃないほう
        if ans[to] != -1:
            continue
        same = edge[1]
        ans[to] = ans[x] ^ (not same)

        queue.append(x)

queue = deque()
queue.append(0)
while queue:
    aaa(queue.popleft())
aaa(0)
for annn in ans:
    print(annn)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)
nnn = int(input())

a = [-2 for i in range(nnn)]
a[0] = 0

def m():
	return map(int,input().split())


def oon(x,n,nn,k):
	global a
	for i in range(len(x[n])):
		if x[n][i][0] != nn and a[nn] != -2 and a[a[x[n][i][0]]] == -2:
			p = (k + x[n][i][1]) % 2
			if p == 0:
				a[x[n][i][0]] = 0
			else:
				a[x[n][i][0]] = 1
			oon(x,x[n][i][0],n,p)



b = [[] for i in range(nnn)]

for i in range(nnn-1):
	z,y,c = m();
	b[z-1].append([y-1,c])
	b[y-1].append([z-1,c])

oon(b,0,0,0)

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

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout

n = int(stdin.readline().rstrip())

d = dict()

for i in range(n - 1):
	x, y, w = [int(j) for j in input().split()]
	if (w % 2 == 0):
		if (x not in d.keys()):
			d[x] = 0
		if (y not in d.keys()):
			d[y] = 0
	else:
		if (x not in d.keys()):
			d[x] = 1
		if (y not in d.keys()):
			d[y] = 1

for v in d.values():
	stdout.write(str(v) + "\n")

Submission status: Wrong Answer

Solution code:
N = int(input())

T = [[0] * N 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 i in range(N):
        if T[n][i] > 0 and not i in used:
            if T[n][i] % 2 == 0:
                g0.add(i)
            opened.add(i)
            used.add(n)

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

Submission status: Wrong Answer

Solution code:
from collections import deque

N = int(input())
edges = [list(map(int, input().split())) for _ in range(N-1)]
for i in range(1, N+1):
    edges.append([0, i, 0])
vertices = [0]*(N+1)
visited = [0]*(N+1)

queue = deque([0])

while queue:
    s = queue.popleft()

    for i in edges:
        if i[0] == s:
            if visited[s] == 0:
                visited[s] = 1
                queue.append(i[1])
            if i[2] % 2 == 1:
                if vertices[i[0]] == 0:
                    vertices[i[1]] = 1
                else:
                    vertices[i[1]] = 0

for i in vertices[1:]:
    print(i)

Submission status: Wrong Answer

Solution code:
N = int(input())

dict = {}
for i in range(N-1):
    u, v, w = map(int, input().split())
    if w % 2 == 1:
        if u not in dict:
            dict[u] = [v]
        else:
            dict[u].append(v)

arr = [-1] * (N+1)
for i in range(1, N+1):
    if arr[i] == -1:
        arr[i] = 0
        if i in dict:
            v = dict[i]
            for j in v:
                if arr[j] == -1:
                    arr[j] = 1
    elif arr[i] == 0:
        if i in dict:
            v = dict[i]
            for j in v:
                if arr[j] == -1:
                    arr[j] = 1
    elif arr[i] == 1:
        if i in dict:
            v = dict[i]
            for j in v:
                if arr[j] == -1:
                    arr[j] = 0

for i in arr[1:]:
    print(i)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)
# n = int(input())
n = 10000
d = [set() for i in range(n)]
cost = {}
for i in range(n-1):
    # u,v,w = map(int,input().split())
    u,v,w = i,i+1,i
    d[u-1].add(v-1)
    d[v-1].add(u-1)
    cost[(u-1,v-1)] = w%2
    cost[(v-1,u-1)] = w%2

visited = [False for i in range(n)]
colors = [0 for i in range(n)]

stack = []
def dfs(v,c):
    visited[v] = True
    colors[v] = c%2
    for i in d[v]:
        if not visited[i]:
            dfs(i,c+cost[(v,i)])

dfs(0,0)

for i in range(n):
    print(colors[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):
        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)

Submission status: Wrong Answer

Solution code:
N = int(input())
u, v, w = list(), list(), list()

G = [[-1 for j in range(N)] for i in range(N)]
ans = [0 for j in range(N)]

me = 0

def dfs(_me):
    for i in range(N):
        if G[_me][i] != -1:
            if G[_me][i] % 2 == 0:
                ans[i] = ans[_me]
            else:
                ans[i] = 1 - ans[_me]

            dfs(i)

for i in range(N - 1):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    G[a][b] = c
    if i == 0:
        G[a][b] = 0
        me = a
        ans[me] = 0

dfs(me)

for element in ans:
    print(element)

Submission status: Wrong Answer

Solution code:
N = int(input())
UVW = [list(map(int, input().split())) for _ in range(N-1)]

# 奇数だったら塊の色を反転させる
class Bag():
    def __init__(self, node, color):
        self.bag = [node]
        self.color = color
        print(node, color)
    
    # あるノードを追加する
    def add(self, node):
        self.bag.append(node)

    # あるノードの色を変える:
    def change_color(self, color):
        self.color = color

    # 同じ色は統合する
    def union(self, Bag):
        self.bag += Bag.bag

    def find(self, num):
        if num in self.bag:
            return self.color
        else: return -1

    def __repr__(self):
        s = "["
        for bg in self.bag:
            s += str(bg) + ","
        s += "]"
        return s + "/" + str(self.color)


NODES = []
def find_all(node):
    for n in range(len(NODES)):
        i = NODES[n].find(node)
        if i != -1:
            return n
    else:
        return -1


color = 0
for uvw in UVW:
    u = uvw[0] - 1
    v = uvw[1] - 1
    w = uvw[2]
    #print(uvw, tree_color)
    i = find_all(u)
    j = find_all(v)
    if i == -1 and j == -1:
        bg = Bag(u, color)
        if w % 2 == 0:
            bg.add(v)
            NODES.append(bg)
        else:
            NODES.append(bg)
            bg2 = Bag(v, 1-color)
            NODES.append(bg2)
    elif i != -1 and j == -1:
        if w % 2 == 0:
            NODES[i].add(v)
        else:
            bg2 = Bag(v, 1-color)
            NODES.append(bg2)
    elif j != -1 and i == -1:
        if w % 2 == 0:
            NODES[j].add(v)
        else:
            bg2 = Bag(u, 1-color)
            NODES.append(bg2)
    else:
        if w % 2 == 0:
            NODES[i].union(NODES[j])
            del NODES[j]
        else:
            NODES[j].color = 1 - NODES[i].color
            
    #print(NODES)

#for tc in tree_color:
#    print(tc)
colors = [0 for _ in range(N)]
for n in NODES:
    color = n.color
    for nd in n.bag:
        colors[nd] = color

for cl in colors:
    print(cl)

Submission status: Wrong Answer

Solution code:
import sys
n = int(input())
edges = [list(map(int, input().split())) for _ in range(n - 1)]
even_edges = [e for e in edges if e[2] % 2 == 0]
odd_edges = [e for e in edges if e[2] % 2 == 1]

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]

uf = WeightedUnionFind(n)

for e in even_edges:
	uf.union(e[0], e[1], 0)

for e in odd_edges:
	uf.union(e[0], e[1], 1)

print(0)
for i in range(2, n + 1):
	if abs(uf.diff(1, i) % 2) == 0:
		print(0)
	else:
		print(1)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def solve(tree, u, v):

    colors = {}
    colors[u] = 0
    stack = deque([u])
    while stack:
        u = stack.pop()
        if u not in tree:
            continue
        for v in tree[u]:
            if v not in colors:
                stack.append(v)
            if w % 2 == 0:
                colors[v] = colors[u]
            else:
                colors[v] = 0 if colors[u] == 1 else 1

    sorted(colors)
    for c in colors:
        print colors[c]

if __name__ == '__main__':

    tree = {}
    n = sys.stdin.readline().strip()
    for _ in xrange(int(n)-1):
        u, v ,w = map(int, sys.stdin.readline().strip().split(" "))
        if u not in tree:
            tree[u] = {}
        if v not in tree:
            tree[v] = {}
        tree[u][v] = w
        tree[v][u] = w

    solve(tree, u, v)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self,n):
        self.parent=[i for i in range(n)]
        self.rank=[0 for _ in range(n)]
        # 親への重み
        self.weight=[0 for _ in range(n)]

    def find(self,x):
        if self.parent[x]==x:
            return x
        else:
            # 重みをrootまでに変える
            self.weight[x]+=self.weight[self.parent[x]]
            # rootにつなぎ替える
            y=self.find(self.parent[x])
            self.parent[x]=y
            return y

    def union(self,x,y,w):
        rootx=self.find(x)
        rooty=self.find(y)
        # yのrootにxのrootをつなぐ
        if self.rank[rootx] < self.rank[rooty]:
            self.parent[rootx]=rooty
            self.weight[rootx]=w-self.weight[x]+self.weight[y]
        else:
            self.parent[rooty]=rootx
            self.weight[rooty]=w-self.weight[y]+self.weight[x]
            if self.rank[rootx]==self.rank[rooty]:
                self.rank[rootx]+=1

n=int(input())
uvw=[list(map(int,input().split())) for _ in range(n-1)]
uf=UnionFind(n)
for u,v,w in uvw:
    u,v,w=u-1,v-1,w
    uf.union(u,v,w)

# print(uf.parent)
# print(uf.weight)
for w in uf.weight:
    print(w%2)

Submission status: Wrong Answer

Solution code:
# 未完成
import numpy as np
N = int(input())  # 頂点数
vertexcolor = np.zeros(N)+(-1)  # その要素の頂点に色が塗られたか否か（塗られてなければ-1）

edge = np.zeros((N-1, 3))  # N以降の入力を保存，辺に関する情報を保存している
for i in range(N-1):
    edge[i] = np.array([int(i) for i in input().split()])
    print(edge[i])

numofcoloredvertex = 2  # 色が塗られた頂点の数
# まずvertexcolor[edge[0][0] - 1]を白にする（黒でも問題はない）
vertexcolor[int(edge[0][0]) - 1] = 0
print(vertexcolor[int(edge[0][0]) - 1], 0)
if edge[0][2] % 2 == 0:  # 頂点（edge[0][0] - 1）との距離が偶数ならvertexcolor[edge[0][1] - 1] も白，奇数なら黒
    vertexcolor[int(edge[0][1]) - 1] = 0

else:
    vertexcolor[int(edge[0][1]) - 1] = 1


while (numofcoloredvertex < N):  # 色が塗られた頂点の数がNになるまで続ける
    for j in range(1, N-1):
        # どちらかの頂点に色が塗られていれば，距離の偶奇でもう１つの頂点の色が決まる
        if vertexcolor[int(edge[j][0]) - 1] >= 0 and vertexcolor[int(edge[j][1]) - 1] == -1:
            numofcoloredvertex += 1
            if edge[j][2] % 2 == 0:

                vertexcolor[int(edge[j][1]) -
                            1] = vertexcolor[int(edge[j][0]) - 1]
            else:

                vertexcolor[int(edge[j][1]) - 1] = 1 - \
                    vertexcolor[int(edge[j][0]) - 1]

        elif vertexcolor[int(edge[j][1]) - 1] >= 0 and vertexcolor[int(edge[j][0]) - 1] == -1:
            numofcoloredvertex += 1
            if edge[j][2] % 2 == 0:

                vertexcolor[int(edge[j][0]) -
                            1] = vertexcolor[int(edge[j][1]) - 1]
            else:

                vertexcolor[int(edge[j][0]) - 1] = 1 - \
                    vertexcolor[int(edge[j][1]) - 1]

for k in range(N):
    print("{}".format(int(vertexcolor[k])))

Submission status: Wrong Answer

Solution code:
#-*- coding:utf-8 -*-

import sys
sys.setrecursionlimit(10000)

def dfs(graph, used, color, v, c):
    color[v] = c    # 指定された色で塗る
    used[v] = True
    for e in graph[v]:
        if used[e[0]]:   # 訪問済みのノードは無視
            continue
        if e[1] % 2 == 1:   # 奇数。親と異色で塗る
            dfs(graph, used, color, e[0], 1-c)   # c=1or0なのでこれで逆に出来る
        else:   # 偶数。親と同色で塗る
            dfs(graph, used, color, e[0], c)


N = int(input())
graph = [[]]*N
used = [False]*N

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

color = [-1]*N

dfs(graph, used, color, 0, 0)    # 0を根と仮定する
for c in color:
    print(c)

Submission status: Wrong Answer

Solution code:
from collections import deque


def bfs(s):
    flag_list[s] = 1
    color_list[s] = 0
    q.append(s)
    while len(q)>0:
        u = q.popleft()
        for v in range(n):
            if m_list[u][v] > 0 and flag_list[v] == 0:
                flag_list[v] = 1
                if color_list[u] == 0:
                    color_list[v] = 1
                else:
                    color_list[v] = 0
                q.append(v)
        flag_list[u] = 2


if __name__ == "__main__":    
    n = int(input())
    m_list = [[0]*n for _ in range(n)]
    color_list = [0]*n
    flag_list = [0]*n
    q = deque([])
    for _ in range(n-1):
        u, v, w = map(int, input().split())
        m_list[u-1][v-1] = w
        m_list[v-1][u-1] = w
    bfs(0)
    for color in color_list:
        print(color)

Submission status: Wrong Answer

Solution code:
def root(i):
    for j in range(len(graph)):
        if not graph[i][j] == 0 and graph[i][j] % 2 == 0:
            color[i] = 1
            decide[i] = 1
            if decide[j] == 0:
                root(j)


N = int(input())
UVW = [list(map(int, input().split())) for _ in range(N - 1)]
graph = [[0 for i in range(N)] for j in range(N)]
for uvw in UVW:
    graph[uvw[0] - 1][uvw[1] - 1] = uvw[2]
    graph[uvw[1] - 1][uvw[0] - 1] = uvw[2]
color = [0 for _ in range(N)]
decide = [0 for _ in range(N)]
root(0)
# print(*graph, sep="\n")
[print(i) for i in color]

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
g = defaultdict(list)
visited = defaultdict(bool)
N = int(input())
ans = [0] * N

def dfs(v, d=0):
    if visited[v]:
        return
    visited[v] = True

    d += 1    
    if d % 2:
        ans[v-1] = 1
    for c in g[v]:
        dfs(v, d)

for j in range(N-1):
    u,v,w = map(int, input().split())
    g[u].append((v, w))
    g[v].append((u, w))

dfs(1)

for a in ans:
    print(a)

Submission status: Wrong Answer

Solution code:
#D問題
#Bellman-Ford法(最短距離)
def BellmanFord(edges,num_v,source):
    #グラフの初期化
    inf=float("inf")
    dist=[inf for i in range(num_v)]
    dist[source-1]=0
    #辺の緩和
    for i in range(num_v):
        for edge in edges:
            if edge[0] != inf and dist[edge[1]-1] > dist[edge[0]-1] + edge[2]:
                dist[edge[1]-1] = dist[edge[0]-1] + edge[2]
                if i==num_v-1: return -1
    return dist

N=int(input())
UVW=[list(map(int,input().split())) for i in range(N-1)]
distlist=BellmanFord(UVW,N,1)
for i in range(N):
    if distlist[i]%2 == 0:
        print(1)
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
N = int(input())

side = [ list(map(int, input().split())) for _ in range(N-1)]
side.sort()

ans = [0] * (N+1)
for u, v, w in side:
    if w % 2 == 0:
        ans[v] = ans[u]
    if w % 2 == 1:
        ans[v] = (ans[u]+1) % 2

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

Submission status: Wrong Answer

Solution code:
from collections import deque
import math
from functools import reduce

def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n = int(input())
ans = [-1] * n
ans[0] = 0

edges = [[]]*n
for i in range(n-1):
    u,v,w = get_nums_l()
    edges[u-1].append([v-1,w%2==0])
    edges[v-1].append([u-1,w%2==0])

def aaa(x):
    # xを含むエッジ

    for edge in edges[x]:
        to = edge[0] # edgeのうちxじゃないほう
        if ans[to] != -1:
            continue
        same = edge[1]
        ans[to] = ans[x] ^ (not same)

        queue.append(x)

queue = deque()
queue.append(0)
while queue:
    aaa(queue.popleft())
aaa(0)
for annn in ans:
    print(annn)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

N = int(input())
#print(N)
BOX = []
COLOR = [0 for i in range(N)]
COLOR[0] = 1
#print(COLOR)
for i in range(N-1):
    A = list(map(int,input().split()))
    BOX.append(A)

#print(BOX)

USEBOX = [0 for i in range(N)]
for i in range(N-1):
    if USEBOX[BOX[i][0]-1] == 0 and USEBOX[BOX[i][1]-1] == 0:
        USEBOX[BOX[i][0]-1] = 1
        USEBOX[BOX[i][1]-1] = 1
        
        if BOX[i][2] % 2 == 0:
            COLOR[BOX[i][1]-1] = COLOR[BOX[i][0]-1]
            
        elif BOX[i][2] % 2 == 1:
            COLOR[BOX[i][1]-1] = (COLOR[BOX[i][0]-1]+1)%2
            
    elif USEBOX[BOX[i][0]-1] == 1 and USEBOX[BOX[i][1]-1] == 0:
        USEBOX[BOX[i][1]-1] = 1
        
        if BOX[i][2] % 2 == 0:
            COLOR[BOX[i][1]-1] = COLOR[BOX[i][0]-1]
            
        elif BOX[i][2] % 2 == 1:
            COLOR[BOX[i][1]-1] = (COLOR[BOX[i][0]-1]+1)%2
 
    elif USEBOX[BOX[i][0]-1] == 0 and USEBOX[BOX[i][1]-1] == 1:
        USEBOX[BOX[i][0]-1] = 1
        
        if BOX[i][2] % 2 == 0:
            COLOR[BOX[i][0]-1] = COLOR[BOX[i][1]-1]
            
        elif BOX[i][2] % 2 == 1:
            COLOR[BOX[i][0]-1] = (COLOR[BOX[i][1]-1]+1)%2

print(COLOR)

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    uvw = []
    w = []
    result = [-1] * N
    for _ in range(N - 1):
        lst = [int(i) for i in input().split()]
        uvw.append([lst[0] if lst[0] <= lst[1] else lst[1],
                    lst[1] if lst[0] <= lst[1] else lst[0],
                    lst[2]])
    uvw.sort()
    # print(uvw)
    # 木の頂点を求める
    # -> 任意の場所で良い. 1 とする.
    # 頂点から順に塗っていく
    result[0] = False
    result = paint(uvw, 1, result)
    for i in result:
        print(int(i))


def paint(uvw, num, result):
    target_uvw = []
    for t in uvw:
        if t[0] == num or t[1] == num:
            target_uvw.append(t)
            uvw.remove(t)
    next_nums = []
    for t in target_uvw:
        target = t[0] if t[0] != num else t[1]
        result[target - 1] = result[num - 1] if t[2] % 2 == 0 else not(result[num - 1])
        next_nums.append(target)
    # print('探索中の番号:', num)
    # print('ヒットしたデータ', target_uvw)
    # print('現在の結果', result)
    for nn in next_nums:
        result = paint(uvw, nn, result)
    return result


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict, deque
from math import ceil, log2
stdin = sys.stdin
def ii(): return int(stdin.readline())
def li(): return map(int, stdin.readline().split())
N = ii()
seen = dict()
lr = defaultdict(list)
for i in range(N - 1):
    l, r, d= tuple(li())
    lr[l].append([r, d])
    lr[r].append([l, r])

# start from 1, color it black
queue = deque([[1, 0]])
seen[1] = 0
while queue:
    cur, d = queue.popleft()
    for nei, delta in lr[cur]:
        if nei in seen: continue
        else:
            new_color = 0 if (d & 1) == 0 else 1
            seen[nei] = new_color
            queue.append([nei, d + delta])
for i in range(1, N + 1):
    print(seen[i])

Submission status: Wrong Answer

Solution code:
def sol(inp=input):
    n=int(inp())
    pots=[None for _ in range(n)]
    edges=[list(map(int,inp().split())) for _ in range(n-1)]
    adj=[{} for _ in range(n)]
    for e in edges:
        adj[e[0]-1][e[1]-1]=e[2]
        adj[e[1]-1][e[0]-1]=e[2]
    
    def dfs(node,pot):
        pots[node]=pot
        for v in adj[node]:
            if pots[v] is None:
                dfs(v,pots[node]+adj[node][v])
    dfs(0,0)
    return [str(p%2) for p in pots]

Submission status: Wrong Answer

Solution code:
def searchLength(fr,to,signal):
    ans = 2
    for x in range(len(ary[fr])):
        if ary[fr][x] != 2:
            if x == to:
                return ary[fr][x]^signal
            ans = searchLength(x,to,ary[fr][x]^signal)
            break
    return ans



N = int(input())
ary = []
for i in range(N):
    ary.append([2]*N)
for r in range(N-1):
    u,v,w = map(int,input().split())
    w = w%2
    ary[u-1][v-1]= w
    # ary[v-1][u-1]= w
# for k in range(N):
for k in range(N):
    if k == 0:
        ary[0][k] == 0
        continue
    else:
        if ary[0][k]== 2:
            ary[0][k] = 0
        ary[0][k]=searchLength(0,k,ary[0][k])


for y in ary[0]:
    if y == 0 or y == 2:
        print(0)
    else:
        print(1)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
n = int(input())

tree= [[] for i in range(n+1)]
cost=[[0 for i in range(n+1)]for j in range(n+1)]
color=[0 for i in range(n+1)]
already=[False for i in range(n+1)]
que=[]
for i in range(n-1):
    u,v,w=map(int,input().split(' '))
    tree[u].append(v)
    tree[v].append(u)
    cost[u][v]=w
    cost[v][u]=w
    if(i==n-2):
        que.append(u)
        color[u]=0
        already[u]=True


while(len(que)!=0): 
    node = que.pop()
    for next_node in tree[node]:
        if already[next_node]==False:
            already[next_node]=True
            # print((color[node]+cost[node][next_node])%2)
            color[next_node]=(color[node]+cost[node][next_node])%2
            if len(tree[node])==1:
                continue
            que.append(next_node)
for i in range(1,len(color)):
    print(color[i])

Submission status: Wrong Answer

Solution code:
# 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


N = read_a_int()

from collections import defaultdict
node = defaultdict(lambda: set())  # キーで指定したノードが隣接するノードを記録しておく。
for _ in range(N-1):
    u, v, w = read_ints()
    if w % 2:
        # wが奇数だったらTrue
        w = True
    else:
        w = False
    node[v-1].add((u-1, w))
    node[u-1].add((v-1, w))


# 0番目から探索していく
import numpy as np
ans = np.full(N, -1, dtype='int16')
# -1は未探索、1は黒、0は白、奇数の重みに当たるたびに反転
visited = np.full(N, False, dtype=bool)
from collections import deque
# 幅優先探索で白黒を記録していく
que = deque([(0, 0)])  # (nodeidx, 現在の色)
ans[0] = 0
visited[0] = True
while que:
    n, c = que.popleft()
    ans[n] = c

    for nex in node[n]:
        nex_node, nex_w = nex
        if visited[nex_node]:
            continue
        # 重みが奇数なら色を反転して探索に追加
        if nex_w:
            c = 1-c

        que.append((nex_node, c))
        visited[nex_node] = True

print(*ans, sep='\n')

Submission status: Wrong Answer

Solution code:
import sys


def read():
    lines = sys.stdin.readlines()

    global N
    N = int(lines[0].strip())

    global UVW
    UVW = [
        list(map(int,
                 line.strip().split())) for line in lines[1:]
    ]
    UVW.sort(key=lambda uvw: uvw[0])


def reverse(vertex):
    if vertex == 0:
        return 1
    elif vertex == 1:
        return 0


if __name__ == '__main__':

    read()

    vertices = [None for n in range(N)]

    for n in range(N - 1):
        u, v, w = UVW[n]
        u -= 1
        v -= 1

        if ((not vertices[u]) and (not vertices[v])):
            vertices[u] = 0
            vertices[v] = vertices[u] if w % 2 == 0 else reverse(vertices[u])
        elif (not vertices[u]):
            vertices[u] = vertices[v] if w % 2 == 0 else reverse(vertices[v])
        elif (not vertices[v]):
            vertices[v] = vertices[u] if w % 2 == 0 else reverse(vertices[u])

    for vertex in vertices:
        print(vertex)

Submission status: Wrong Answer

Solution code:
n = int(input())
ev = [False for _ in range(n)]
od = [False for _ in range(n)]
for i in range(n-1):
    u, v, w = map(int,input().split())
    if w % 2 == 0:
        ev[u-1] = True
        ev[v-1] = True
    else:
        od[u-1] = True
        od[v-1] = True

t = False
pre = False
now = 0
for e, o in zip(ev, od):
    if e and o:
        t = True
    
    if pre and t:
        print(now)
        pre = False
    elif t:
        now = 1 - now
        print(now)
        pre = True
    elif e:
        print(now)
        pre = True
    elif o:
        now = 1 - now
        print(now)
        pre = False
    t = False

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())

    edges = []
    for _ in range(n - 1):
        u, v, w = list(map(int, input().split()))
        edges.append((u, v, w))

    # print(edges)
    edges = [(u, v) for u, v, w in edges if w % 2 != 0]
    # print(edges)

    has_odd = set(list(sum(edges, ())))
    # print(has_odd)

    if len(edges) < 1:
        for i in range(1, n + 1):
            print('0')
        return

    remain = edges
    b = []
    w = []
    u1, v1 = remain.pop(0)
    b.append(u1)
    w.append(v1)

    must_black = [u1]
    must_white = [v1]

    step = []
    while len(remain) > 0:
        u1, v1 = remain.pop(0)
        if u1 in must_black:
            b.append(u1)
            w.append(v1)
            if v1 not in must_white:
                must_white.append(v1)
        elif v1 in must_black:
            b.append(v1)
            w.append(u1)
            if u1 not in must_white:
                must_white.append(u1)
        elif u1 in must_white:
            b.append(v1)
            w.append(u1)
            if v1 not in must_black:
                must_black.append(v1)
        elif v1 in must_white:
            b.append(u1)
            w.append(v1)
            if u1 not in must_black:
                must_black.append(u1)
        else:
            step.append((u, v))

        if len(remain) < 1 and len(step) > 0:
            new_u1, new_v1 = step.pop(0)
            b.append(new_u1)
            w.append(new_v1)
            must_white.append(new_v1)
            must_black.append(new_u1)
            remain = step

    b = set(b)
    w = set(w)
    b = [{'c': 1, 'n': elem} for elem in b]
    w = [{'c': 0, 'n': elem} for elem in w]
    z = [{'c': 0, 'n': i} for i in range(1, n + 1) if i not in has_odd]
    result = sorted(b + w + z, key=lambda x: x['n'])
    # print(result)
    for e in result:
        print(e['c'])


main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

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

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

for u, v, w in edge:
    u -= 1; v -= 1
    ad[u].append((v,w))
    ad[v].append((u,w))

ans = [0]*N

def dfs(v=0,pv=-1,pw=0):
    if pw % 2 == 0:
        ans[v] = 1
    for nv,w in ad[v]:
        if nv != pv:
            dfs(nv,v,w)

dfs()

for a in ans:
    print(a)

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のグループをまとめる
        dxy += self.diff_p[x] - self.diff_p[y] #dxyをdiff(rx,ry)で置き換え
        x = self.root(x) #rxを新たにxと名づける
        y = self.root(y) #ryを新たにyと名づける
        if x == y:
            return False
        if self.parent[x] > self.parent[y]: #xの要素数がyの要素数より「小さい」とき入れ替える
            x,y=y,x
            dxy = -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)%2)