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: Runtime Error

Solution code:
#coding: utf-8
from collections import defaultdict

N = int(input())
G = {}
for i in range(1, N+1):
    G[i] = []

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

ret = [-1] * (N+1)

def dfs(node, d):
    if ret[node] != -1:
        return

    if d % 2 == 0:
        ret[node] = 0
    else:
        ret[node] = 1 

    for next_node in G[node]:
        dfs(next_node[0], d + next_node[1])

dfs(1, 0)
for i in range(N):
    print(ret[i+1])

Submission status: Runtime Error

Solution code:
# code like professional " write main function"
import os
import sys
from collections import defaultdict
adj = defaultdict(list)
col = defaultdict(int)
sys.setrecursionlimit(1000000)
mx=0
edges = {}
# finding maximum color we need it would be maximum neighbouring nodes of out of all the nodes
def find_color(u , p):
	global mx , now
	cnt =0
	for i in adj[u]:
		cnt = cnt+1
		if i==p:
			continue
		find_color(i , u)
	mx = max(mx, cnt)
now =0
# now color the edges 
def dfs(u , p, prev):
	global mx, now
	for i in adj[u]:
		if i==p:
			continue
		# if current color is equivalent to previous edge color use next color
		if now == prev:
			now = (now+1)%mx
		col[edges[i,u]]=now
		now =(now+1)%mx
	for i in adj[u]:
		if i==p:
			continue
		dfs(i , u, col[edges[i, u]])

def main():
	n = int(input())
	for i in range(n-1):
		x, y = map(int , input().split())
		adj[x].append((y))
		adj[y].append((x))
		edges[x,y]=i
		edges[y,x]=i
	find_color(1, 0)
	dfs(1, 0,-1)
	print(mx)
	for i in range(n-1):
		print(col[i]+1)


if __name__ == "__main__":
	main()

Submission status: Runtime Error

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

# 二分グラフ

N = int(input())
graph = [[] for _ in range(N)]
color = [-1]*N

# 隣接リストの作成
for i in range(N-1):
    a, b, w = map(int, input().split())
    a -= 1
    b -= 1
    w %= 2
    graph[a].append((b,w))
    graph[b].append((a,w))

# 深さ優先探索
def dfs(g,v,c):
    if color[v] == -1:
        color[v] = c
        for nv, w in g[v]:
            if color[nv]!=-1:
                continue
            dfs(g,nv,(w+c)%2)

def main():
    dfs(graph, 0, 1)
    for i in color:
        print(i)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

# 二分グラフ

N = int(input())
graph = [[] for _ in range(N)]
color = [-1]*N

# 隣接リストの作成
for i in range(N-1):
    a, b, w = map(int, input().split())
    a -= 1
    b -= 1
    w %= 2
    graph[a].append((b,w))
    graph[b].append((a,w))

# 深さ優先探索
def dfs(g,v,c):
    if color[v] == -1:
        color[v] = c
        for nv, w in g[v]:
            if color[nv]==1:
                continue
            nc = c
            if w != 0:
                nc = 1-c
            dfs(g,nv,nc)

def main():
    dfs(graph, 0, 1)
    for i in color:
        print(i)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
g = {}
a = int(input())
vertices = [i for i in range(1, a + 1)]
for i in range(a):
    c = [int(s) for s in input().split()] 
    print(0)

Submission status: Runtime Error

Solution code:
n = int(input())
uvw = [list(map(int, input().split())) for i in range(n - 1)]
d = [-1 for i in range(n)]
edge = [[] for i in range(n)]
for u, v, w in uvw:
    edge[u - 1].append((v - 1, w))
    edge[v - 1].append((u - 1, w))
def dfs(now, D):
    d[now] = D
    for i, j in edge[now]:
        if d[i] == -1:
            dfs(i, D + j)
dfs(0, 0)
for i in d:
    print(i % 2)

Submission status: Runtime Error

Solution code:

from copy import copy
N=int(input())
G=[[] for _ in range(N)]
di=[-1]*N
for i in range(N-1):
    u,v,w=map(int,input().split())
    G[u-1].append([v-1,w])
    G[v-1].append([u-1,w])

def dfs(a,b):
    seen[a]=1
    #distance of a to b
    for g,d in G[a]:
        if seen[g]==1:continue
        if g==b:
            return d
        seen[g]=1
        dis=dfs(g,b)
        if dis !=0:
            return d+dis
        seen[g]=0
    return 0

di[0]=0
for i in range(N):
    if di[i]!=-1:continue
    seen=[0]*N
    di[i]=dfs(0,i)

for i in range(N):
    if di[i]%2==0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    def dfs(node):
        for adjnode in edges[node]:
            if colors[adjnode[0]] == -1:
                if adjnode[1] % 2 == 0:
                    colors[adjnode[0]] = colors[node]
                else:
                    colors[adjnode[0]] = colors[node] ^ 1
                dfs(adjnode[0])
    # input
    n = int(input())
    edges = {e: [] for e in range(n)}
    for _ in range(n - 1):
        u, v, w = map(int, input().split())
        u -= 1
        v -= 1
        edges[u].append((v, w))
        edges[v].append((u, w))
    # process
    colors = [-1] * n
    colors[0] = 0
    dfs(0)
    # output
    print(*colors, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N=int(input())
G=[[] for _ in range(N)]
ans=[-1]*N

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

def dfs(x):
    if ans[x]!=-1:
        return ans[x]
    for y,w in G[x]:
        if seen[y]:continue
        seen[y]=True
        if ans[y]!=-1:
            seen[y]=False
            return (ans[y]+1)%2
        temp=dfs(y)
        if temp==None:
            seen[y]=False
        else:
            seen[y]=False
            return (temp+w)%2

ans[0]=0
seen=[False]*N
for g,e in G[0]:
    ans[g]=e%2


for i in range(N):
    ans[i]=dfs(i)

for a in ans:
    print(a)

Submission status: Runtime Error

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

for edge in edges:
    A[edge[0]].append([edge[1],edge[2]])
    A[edge[1]].append([edge[0],edge[2]])

depth = [-1]*(N+1)
depth[1] = 0

def dfs(A,s):
    for v in A[s]:
        if depth[v[0]] == -1:
            depth[v[0]] = depth[s] + v[1]
            dfs(A, v[0])

dfs(A, 1)
for d in depth[1:]:
    if d % 2 == 0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
N=int(input())
edge={i:[] for i in range(N)}
for i in range(N-1):
    u,v,w=list(map(int,input().split()))
    u,v=u-1,v-1
    edge[u].append([v,w])
    edge[v].append([u,w])
tyouten=[0 for _ in range(N)]
tyouten[0]=1
def kaiki(edge,i):
    for e in edge[i]:
        if tyouten[e[0]]!=0:
            continue
        if e[1]%2==0:
            tyouten[e[0]]=tyouten[i]
        else:
            tyouten[e[0]]=-tyouten[i]
        kaiki(edge,e[0])
kaiki(edge,0)
for t in tyouten:
    if t==1:
        print(1)
    else:
        print(0)

Submission status: Runtime Error

Solution code:
def dfs(i):
  if reached[i] == 1:
    return
  reached[i] = 1
  for dic in uv[i]:
    to = dic["to"]
    w = dic["weight"]
    if w % 2 == 0:
      color[to] = color[i]
    else:
      color[to] = int(not color[i])
    dfs(to)

n = int(input())
color = [0]*(n+1)
reached = [0]*(n+1)
uv = [[] * (n+1) for i in range(n+1)]
for i in range(n-1):
  u,v,w = map(int,input().split())
  uv[u].append({"to":v, "weight":w})
  uv[v].append({"to":u, "weight":w})
dfs(1)
for i in color[1:]:
  print(i)

Submission status: Runtime Error

Solution code:
from sys import stdin
input = stdin.readline


def main():
  N = int(input())
  G = [[] for _ in range(N+1)]
  for i in range(N-1):
    u, v, w = map(int, input().split())
    G[u].append((v, w))
    G[v].append((u, w))

  color = [-1]*(N+1)
  color[1] = 0
  # S = [1]
  # while len(S):
  #   now = S[-1]
  #   for next_, w in G[now]:
  #     if color[next_] != -1:
  #       continue
  #     S.append(next_)
  #     color[next_] = (w % 2) ^ color[now]
  #     break
  #   else:
  #     S.pop()

  def dfs(now):
    for next_, w in G[now]:
      if color[next_] == -1:
        color[next_] = (w % 2) ^ color[now]
        dfs(next_)
  dfs(1)

  for i in range(1, N+1):
    print(color[i])


if(__name__ == '__main__'):
  main()

Submission status: Runtime Error

Solution code:
n = int(input())
col = [0]*n
next = [[] for i in range(n)]
d = [float('INF')]*n
d[0]=0

def dfs(now):
    for next1,w1 in next[now]:
        if d[next1]>d[now]+w1:
            d[next1]=d[now]+w1
            dfs(next1)

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

dfs(0)

for i in range(n):
    if d[i]%2==0:
        print('0')
    else:
        print('1')

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

# 入力
N = int(input())
adj = [[] for _ in range(N)]
ans = [None] * N

# グラフ探索で解いてみる
# c: 頂点vの色(0or1)
def dfs(v,parent,c):
    ans[v] = c
    for u,w in adj[v]:
        if u == parent:
            continue
        dfs(u,v,1-c) if w & 1 else dfs(u,v,c)

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

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n=int(input())
edge=[[] for _ in range(n)]
dist=[-1]*n
for i in range(n-1):
    x,y,z=map(int,input().split())
    edge[x-1].append([y-1,z])
    edge[y-1].append([x-1,z])
def dfs(node,d):
    dist[node]=d
    for i in edge[node]:
        if dist[i[0]]==-1:
            dfs(i[0],d+i[1])
dfs(0,0)
print(*[i%2 for i in dist],sep='\n')

Submission status: Runtime Error

Solution code:
import sys
INFTY=sys.maxsize

def readinput():
    n=int(input())
    nList=[]
    for _ in range(n+1):
        nList.append([])
    for _ in range(1,n):
        u,v,w=map(int,input().split())
        nList[u].append((v,w))
        nList[v].append((u,w))

    return n,nList

WHITE=0
GRAY=1
BLACK=2
status=[]
color=[]

def dfs(s,nList):
    for u,w in nList[s]:
        if status[u]==WHITE:
            if w%2==0:
                color[u]=color[s]
            else:
                color[u]=(color[s]+1)%2
            status[u]=GRAY
            dfs(u,nList)
    status[s]=BLACK

def main(n,nList):
    global status
    global color

    status=[WHITE]*(n+1)
    color=[WHITE]*(n+1)
    dfs(1,nList)

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

if __name__=='__main__':
    n,nList=readinput()
    main(n,nList)
    #print(ans)

Submission status: Runtime Error

Solution code:
import sys
INFTY=sys.maxsize

def readinput():
    n=int(input())
    nList=[]
    for _ in range(n+1):
        nList.append([])
    for _ in range(1,n):
        u,v,w=map(int,input().split())
        nList[u].append((v,w))
        nList[v].append((u,w))

    return n,nList

WHITE=0
GRAY=1
BLACK=2
status=[]
color=[]

def dfs(s,nList):
    for u,w in nList[s]:
        if status[u]==WHITE:
            if w%2==0:
                color[u]=color[s]
            else:
                color[u]=(color[s]+1)%2
            status[u]=GRAY
            dfs(u,nList)
    status[u]=BLACK

def main(n,nList):
    global status
    global color

    status=[WHITE]*(n+1)
    color=[WHITE]*(n+1)
    dfs(1,nList)

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

if __name__=='__main__':
    n,nList=readinput()
    main(n,nList)
    #print(ans)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(1000000)

num_node = int(input())
relation = [[[], []] for i in range(num_node + 1)]
for i in range(num_node - 1):
    u, v, w = map(int, input().split())
    if w % 2 == 0:
        relation[u][0].append(v)
        relation[v][0].append(u)
    else:
        relation[u][1].append(v)
        relation[v][1].append(u)
colors = [None] * (num_node + 1)


def dfs(n: int):
    if n == 1:
        colors[n] = 0
    print(colors)
    # 偶数
    for even_idx in relation[n][0]:
        if colors[even_idx] is not None:
            continue
        else:
            colors[even_idx] = colors[n]
            dfs(even_idx)
    # 奇数
    for odd_idx in relation[n][1]:
        if colors[odd_idx] is not None:
            continue
        else:
            colors[odd_idx] = not colors[n]
            dfs(odd_idx)


if __name__ == '__main__':
    dfs(1)
    for ans in list(map(int, colors[1:])):
        print(ans)

Submission status: Runtime Error

Solution code:
num_node = int(input())
relation = [[[], []] for i in range(num_node + 1)]
for i in range(num_node - 1):
    u, v, w = map(int, input().split())
    if w % 2 == 0:
        relation[u][0].append(v)
        relation[v][0].append(u)
    else:
        relation[u][1].append(v)
        relation[v][1].append(u)
colors = [None] * (num_node + 1)


def dfs(n: int):
    if n == 1:
        colors[n] = 0
    print(colors)
    # 偶数
    for even_idx in relation[n][0]:
        if colors[even_idx] is not None:
            continue
        else:
            colors[even_idx] = colors[n]
            dfs(even_idx)
    # 奇数
    for odd_idx in relation[n][1]:
        if colors[odd_idx] is not None:
            continue
        else:
            colors[odd_idx] = not colors[n]
            dfs(odd_idx)


if __name__ == '__main__':
    dfs(1)
    for ans in list(map(int, colors[1:])):
        print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
edge = [[] for _ in range(N)]

for i in range(N - 1):
    u, v, w = [int(_) for _ in input().split()]
    w = w % 2
    u -= 1
    v -= 1
    edge[u].append((v, w))
    edge[v].append((u, w))

ans = [0] * N


def dfs(v, pv, pw):
    childs = filter(lambda cv: cv[0] != pv, edge[v])
    for cv, cw in childs:
        if cw == 0 and pw == 1:
            None
        if cw == 1:
            ans[cv] = 1
            dfs(cv, v, cw)
        else:
            dfs(cv, v, cw)


dfs(0, -1, -1)
print(*ans)

Submission status: Runtime Error

Solution code:
N = int(input())
paths = {}
for i in range(N-1):
    u, v, w = map(int,input().split())
    paths.setdefault(u, {})
    paths[u][v] = w
    paths.setdefault(v, {})
    paths[v][u] = w

node_colors = [-1] * (N+1)

def route(last, now, dist):
    for next_node, next_distance in zip(paths[now].keys(), paths[now].values()):
        node_colors[next_node] = (dist + next_distance) % 2
        if next_node != last:
            route(now, next_node, dist + next_distance)

node_colors[1] = 0

route(0, 1, 0)

for i in range(N):
    print(node_colors[i+1])

Submission status: Runtime Error

Solution code:
def p_color(here, previous):
    color_here = colors[here]
    next_candidates = []
    for u, v, w in paths:
        if here == u and v != previous:
            next_candidates.append(v)
            if color_here == 0:
                if w % 2 == 0:
                    colors[v] = 0
                else:
                    colors[v] = 1
            else:
                if w % 2 == 0:
                    colors[v] = 1
                else:
                    colors[v] = 0
        elif here == v and u != previous:
            next_candidates.append(u)
            if color_here == 0:
                if w % 2 == 0:
                    colors[u] = 0
                else:
                    colors[u] = 1
            else:
                if w % 2 == 0:
                    colors[u] = 1
                else:
                    colors[u] = 0
    if len(next_candidates) == 0:
        return
    else:
        for p in next_candidates:
            p_color(p, here)

n = int(input())
colors = [0,] * n

paths = []
while True:
    try:
        u, v, w = map(int, input().split())
        paths.append([u - 1, v - 1, w])
    except:
        break

p_color(0, -1)

for c in colors:
    print(c)

Submission status: Runtime Error

Solution code:
(n,),*t=[map(int,t.split())for t in open(0)]
n+=1
*e,=eval('[],'*n)
q=[n]
f=[-1]*n
for v,w,c in t:e[v]+=w*n+c,;e[w]+=v*n+c,
for v in q:
 f[v//n]=v%n&1
 for w in e[v//n]:q+=[w+v%n]*(f[w//n]<0)
print(*f[1:])

Submission status: Runtime Error

Solution code:
(n,),*t=[map(int,t,split())for t in open(0)]
*e,=eval('[],'*-~n)
q=[(1,0)]
f=[-1]*n
for v,w,c in t=:e[v]+=(w,c),;e[w]+=(v,c),
for v,c in q:
 f[v-1]=c%2
 for w,d in e[v]:q+=[(w,c+d)]*(f[w-1]<0)
print(*f)

Submission status: Runtime Error

Solution code:
import numpy as np
n=int(input())
a=[list(map(int,input().split())) for i in range(n-1)]

t=np.array(a).T
#木の根
root=1
tree={1:[1,0]}
#p:親,d:距離
p=0
d=1

t0=t[0].tolist()
stack=[root]
while stack:
  now=stack.pop(-1)
  now_d=t0.index(tree[now][p])
  
  right=list(zip(*np.where(t[1]==now)))
  r=[i for i in zip(*np.where(t[1]==now)) if a[i[0]][0]!=tree[now][p]]
  l=[i for i in zip(*np.where(t[0]==now)) if a[i[0]][1]!=tree[now][p]]
  #print(r,tree[now][p])
  #print(right)
  #left=list(zip(*np.where(t[0]==now)))
  #print(r,l)
  for i in r:
    ii=i[0]
    stack.append(a[ii][0])
    tree[a[ii][0]]=[now, a[ii][2]+tree[now][d]]
     #print(a[ii][2]+tree[now][d])
      
  for i in l:
    ii=i[0]
    stack.append(a[ii][1])
    tree[a[ii][1]]=[now, a[ii][2]+tree[now][d]]
    #print(a[ii][2]+tree[now][d])
    
#print(tree)
for i in range(1,n+1):
  if tree[i][d]%2==0:
    print(1)
  else:
    print(0)

Submission status: Runtime Error

Solution code:
N = int(input())
graph = [[] for  _ in range(N)]
now = 0
for _ in range(N-1):
    x,y,w = map(int,input().split())
    x -= 1
    y -= 1
    graph[x].append((y,w))
    graph[y].append((x,w))
    now = x
    
vis = [0 for _ in range(N)]

even = set()
odd = set()

def dfs(now):
 #   print(now)
    for nv in graph[now]:
        if vis[nv[0]]: continue
        if nv[1] % 2 == 0:
            if now in even:
                even.add(nv[0])
            else:
                odd.add(nv[0])
        else:
            if now in even:
                odd.add(nv[0])
            else:
                even.add(nv[0])
        vis[nv[0]] = 1
        dfs(nv[0])
vis[x] = 1
even.add(x)
dfs(x)

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

Submission status: Runtime Error

Solution code:
N = int(input())
graph = [[] for  _ in range(N)]
now = 0
for _ in range(N-1):
    x,y,w = map(int,input().split())
    x -= 1
    y -= 1
    graph[x].append((y,w))
    graph[y].append((x,w))
    now = x
    
vis = [0 for _ in range(N)]

even = set()
odd = set()

def dfs(now):
    #print(now)
    for nv in graph[now]:
        if vis[nv[0]]: continue
        if nv[1] % 2 == 0:
            if now in even:
                even.add(nv[1])
            else:
                odd.add(nv[1])
        else:
            if now in even:
                odd.add(nv[1])
            else:
                even.add(nv[1])
        vis[nv[0]] = 1
        dfs(nv[0])
vis[x] = 1
even.add(x)
dfs(x)

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

Submission status: Runtime Error

Solution code:
N = int(input())
graph = [[] for  _ in range(N)]
now = 0
for _ in range(N-1):
    x,y,w = map(int,input().split())
    x -= 1
    y -= 1
    graph[x].append((y,w))
    graph[y].append((x,w))
    now = x
    
vis = [0 for _ in range(N)]

even = set()
odd = set()

def dfs(now):
    for nv in graph[now]:
        if vis[nv[0]]: continue
        if nv[1] % 2 == 0:
            if nv in even:
                even.add(nv[1])
            else:
                odd.add(nv[1])
        else:
            if nv in even:
                odd.add(nv[1])
            else:
                even.add(nv[1])
        vis[nv[0]] = 1
        dfs(nv[0])
vis[x] = 1
even.add(x)
dfs(x)
for i in range(N):
    if i in even:
        print(1)
    else:
        print(0)

Submission status: Runtime Error

Solution code:
N = int(input())
graph = [[] for  _ in range(N)]
for _ in range(N-1):
    x,y,w = map(int,input().split())
    x -= 1
    y -= 1
    graph[x].append((y,w))
    graph[y].append((x,w))
    


vis = [0 for _ in range(N)]

even = set()
odd = set()

def dfs(now):
    for nv in graph[now]:
        if vis[nv[0]]: continue
        if nv[1] % 2 == 0:
            if nv in even:
                even.add(nv[1])
            else:
                odd.add(nv[1])
        else:
            if nv in even:
                odd.add(nv[1])
            else:
                even.add(nv[1])
        vis[nv[0]] = 1
        dfs(nv[0])
vis[0] = 1
even.add(0)
dfs(0)
for i in range(N):
    if i in even:
        print(1)
    else:
        print(0)

Submission status: Runtime Error

Solution code:
N = int(input())
adj = [ [] for _ in range(N) ]
for _ in range(N-1):
  u,v,w = map(int,input().split())
  u -= 1
  v -= 1
  adj[u].append((v,w))
  adj[v].append((u,w))

def dfs(node, w, color):
  colors[node] = color

  for nei,nw in adj[node]:
    if colors[nei] != -1: continue
    nc = 1 if (w+nw)%2==0 else 0
    dfs(nei, nw, nc)

  return True

colors = [-1] * N
for i in range(N):
  if colors[i] == -1:
    dfs(i, 0, 1)

for c in colors: print(c)

Submission status: Runtime Error

Solution code:
n = int(input())
to = [[] for _ in range(n)]
for _ in range(n - 1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    to[u].append((v, w))
    to[v].append((u, w))
ans = [-1] * n
def dfs(u=0, c=0, parent=-1):
    ans[u] = c
    for v, w in to[u]:
        if v == parent:
            continue
        dfs(v, (c + w) & 1, u)

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

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest
import os

sys.setrecursionlimit(9999999999)


def dfs(now, edge, colors):
    # 枝を全て調査
    for i in edge[now]:
        # 色を設定済みなら何もしない
        if not colors[i[0]] == -1:
            continue

        # 色の設定
        # 親子の距離%2(偶数0:奇数:1) + 親(偶数0:奇数:1) の余りを子に設定(偶数なら0 奇数なら1を設定できるロジック)
        colors[i[0]] = (i[1] % 2 + colors[now]) % 2

        # 再帰処理
        dfs(i[0], edge, colors)


# 実装を行う関数
def resolve():
    n = int(input())
    uvw = [list(map(int, input().split())) for i in range(n - 1)]

    edge = [[] for i in range(n + 1)]

    # 例：edge[0] = [[1, 100][2, 300]]
    # 点0は点1と距離100、点2と距離300でつながっている。
    for i in uvw:
        edge[i[0]].append([i[1], i[2]])
        edge[i[1]].append([i[0], i[2]])

    # -1は「未設定」の意味
    colors = [-1 for i in range(n + 1)]

    # 初期(適当な点を黒に塗る)
    colors[1] = 1

    dfs(1, edge, colors)

    for i in range(1, len(colors)):
        print(colors[i])


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3
1 2 2
2 3 1"""
        output = """0
0
1"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """5
2 5 2
2 3 10
1 3 8
3 4 2"""
        output = """1
0
1
0
1"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest
import os

sys.setrecursionlimit(99999999999)


def dfs(now, edge, colors):
    # 枝を全て調査
    for i in edge[now]:
        # 色を設定済みなら何もしない
        if not colors[i[0]] == -1:
            continue

        # 色の設定
        # 親子の距離%2(偶数0:奇数:1) + 親(偶数0:奇数:1) の余りを子に設定(偶数なら0 奇数なら1を設定できるロジック)
        colors[i[0]] = (i[1] % 2 + colors[now]) % 2

        # 再帰処理
        dfs(i[0], edge, colors)


# 実装を行う関数
def resolve():
    n = int(input())
    uvw = [list(map(int, input().split())) for i in range(n - 1)]

    edge = [[] for i in range(n + 1)]

    # 例：edge[0] = [[1, 100][2, 300]]
    # 点0は点1と距離100、点2と距離300でつながっている。
    for i in uvw:
        edge[i[0]].append([i[1], i[2]])
        edge[i[1]].append([i[0], i[2]])

    # -1は「未設定」の意味
    colors = [-1 for i in range(n + 1)]

    # 初期(適当な点を黒に塗る)
    colors[1] = 1

    dfs(1, edge, colors)

    for i in range(1, len(colors)):
        print(colors[i])


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3
1 2 2
2 3 1"""
        output = """0
0
1"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """5
2 5 2
2 3 10
1 3 8
3 4 2"""
        output = """1
0
1
0
1"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest
import os


def dfs(now, edge, colors):
    # 枝を全て調査
    for i in edge[now]:
        # 色を設定済みなら何もしない
        if not colors[i[0]] == -1:
            continue

        # 色の設定
        # 親子の距離%2(偶数0:奇数:1) + 親(偶数0:奇数:1) の余りを子に設定(偶数なら0 奇数なら1を設定できるロジック)
        colors[i[0]] = (i[1] % 2 + colors[now]) % 2

        # 再帰処理
        dfs(i[0], edge, colors)


# 実装を行う関数
def resolve():
    n = int(input())
    uvw = [list(map(int, input().split())) for i in range(n - 1)]

    edge = [[] for i in range(n + 1)]

    # 例：edge[0] = [[1, 100][2, 300]]
    # 点0は点1と距離100、点2と距離300でつながっている。
    for i in uvw:
        edge[i[0]].append([i[1], i[2]])
        edge[i[1]].append([i[0], i[2]])

    # -1は「未設定」の意味
    colors = [-1 for i in range(n + 1)]

    # 初期(適当な点を黒に塗る)
    colors[1] = 1

    dfs(1, edge, colors)

    for i in range(1, len(colors)):
        print(colors[i])


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3
1 2 2
2 3 1"""
        output = """0
0
1"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """5
2 5 2
2 3 11
1 3 8
3 4 2"""
        output = """1
0
1
0
1"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest
import os


def dfs(now, parent, edge, colors):
    # 枝を全て調査
    for i in edge[now]:
        # 色を設定済みなら何もしない
        if not colors[i[0]] == -1:
            continue

        # 色の設定
        # 親子の距離%2(偶数0:奇数:1) + 親(偶数0:奇数:1) の余りを子に設定(偶数なら0 奇数なら1を設定できるロジック)
        colors[i[0]] = (i[1] % 2 + colors[now]) % 2

        # 再帰処理
        dfs(i[0], now, edge, colors)


# 実装を行う関数
def resolve():
    n = int(input())
    uvw = [list(map(int, input().split())) for i in range(n - 1)]

    edge = [[] for i in range(n + 1)]

    # 例：edge[0] = [[1, 100][2, 300]]
    # 点0は点1と距離100、点2と距離300でつながっている。
    for i in uvw:
        edge[i[0]].append([i[1], i[2]])
        edge[i[1]].append([i[0], i[2]])

    # -1は「未設定」の意味
    colors = [-1 for i in range(n + 1)]

    # 初期(適当な点を黒に塗る)
    colors[1] = 1

    dfs(1, 1, edge, colors)

    for i in range(1, len(colors)):
        print(colors[i])


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3
1 2 2
2 3 1"""
        output = """0
0
1"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """5
2 5 2
2 3 11
1 3 8
3 4 2"""
        output = """1
0
1
0
1"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()