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: Accepted

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


ans = [-1] * N
q = [(0, 0, -1)]

while q:
    v, dist, parent = q.pop()

    if dist % 2 == 0:
        ans[v] = 0
    else:
        ans[v] = 1

    for u, w in nodes[v]:
        if u == parent:
            continue

        q.append((u, dist + w, v))

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

Submission status: Accepted

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


ans = [-1 for _ in range(N)]
q = [(0, 0, -1)]

while q:
    v, dist, parent = q.pop()

    if dist % 2 == 0:
        ans[v] = 0
    else:
        ans[v] = 1

    for u, w in nodes[v]:
        if u == parent:
            continue

        q.append((u, dist + w, v))

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
N = int(input())
a = [[] for _ in range(N)]
b = [[] for _ in range(N)]
for i in range(N-1):
    x, y, z = map(int, input().split())
    x, y, z = x-1, y-1, z % 2
    a[x].append([y, z])
    b[y].append([x, z])
dist = [0] * N
visited = [0] * N
print("")

def dfs(v, prev, dist, predist, visited):
    if visited[v]:
        return dist
    dist[v] = dist[prev] ^ predist
    visited[v] = 1
    for i in a[v]:
        dist = dfs(i[0], v, dist, i[1], visited)
    for i in b[v]:
        dist = dfs(i[0], v, dist, i[1], visited)
    return dist

dist = dfs(0, 0, dist, 0, visited)
for i in dist:
    print(i)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)

N = int(input())

C = [-1] * N  # Colors
E = [[] for _ in range(N)]  # Edges
swap = {0: 1, 1: 0}


def coloring(v, c):
    C[v] = c
    for e in E[v]:
        if C[e[0]] == -1:
            coloring(e[0], c if e[1] % 2 == 0 else swap[c])


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

coloring(0, 0)

for c in C:
    print(c)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
N = int(input())


sys.setrecursionlimit(1000000)

uvw = [[int(item) for item in input().split()] for _ in range(N-1)]

d = defaultdict(lambda: {})
for u, v, w in uvw:
    d[u][v] = w
    d[v][u] = w


dist = {1: 0}


def calc_dist(i, up):
    if not(i in dist):
        dist[i] = dist[up]+d[up][i]
        [calc_dist(k, i) for k in list(d[i].keys())]


[calc_dist(k, 1) for k in list(d[1].keys())]

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)


def resolve():
    N = [int(x) for x in sys.stdin.readline().split()][0]
    edge_list = [[] for _ in range(N)]

    for _ in range(N-1):
        u, v, w = [int(x) for x in sys.stdin.readline().split()]
        edge_list[u-1].append((v-1, w))
        edge_list[v-1].append((u-1, w))

    color_list = [0] * N
    visited_set = set()
    def dfs(i_rec, c_rec):
        visited_set.add(i_rec)
        color_list[i_rec] = c_rec
        for i_next, weight in edge_list[i_rec]:
            if i_next in visited_set:
                continue
            if weight % 2 == 0:
                dfs(i_next, c_rec)
            else:
                dfs(i_next, 1 - c_rec)

    dfs(0, 0)

    for c in color_list:
        print(c)


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3
1 2 2
2 3 1"""
        output = """0
0
1"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """5
2 5 2
2 3 10
1 3 8
3 4 2"""
        output = """1
0
1
0
1"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """1"""
        output = """0"""
        self.assertIO(input, output)

Submission status: Accepted

Solution code:
n = int(input())
ar = [[] for i in range(n)]
for i in range(n-1):
    ipt = list(map(int,input().split()))
    ar[ipt[0]-1].append((ipt[1]-1,ipt[2]))
    ar[ipt[1]-1].append((ipt[0]-1,ipt[2]))

ans = [-1 for i in range(n)]
u = 0
ans[u] = 0
queue = [u] #キュー
l = 1
while True:
    if l == 0:
        break
    u = queue.pop(0)
    l -= 1
    for v in ar[u]:
        if ans[v[0]] < 0:
            ans[v[0]] = ans[u] + v[1]
            queue.append(v[0])
            l+=1

for i in range(n):
    print(ans[i]%2)

Submission status: Accepted

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)
def input():
  return sys.stdin.readline()[:-1]

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

#################

N = I()
u,v,w = Line(N-1)

c = [[] for _ in range(N)]
for i in range(N-1):
  c[u[i]-1].append([v[i]-1, w[i]])
  c[v[i]-1].append([u[i]-1, w[i]])

d=[-1]*N
v=0
check_visited = [False]*N
check_visited[v] = True
S = [v]
d[v]=0
while S:
  v1 = S.pop()
  for i in c[v1]:
    if check_visited[i[0]] == False:
      check_visited[i[0]] = True
      d[i[0]] = d[v1] + i[1]
      S.append(i[0])

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

Submission status: Accepted

Solution code:
N = int(input())
S = [[] for i in range(N)]
for i in range(N-1):
  u, v, w = map(int, input().split())
  S[u-1].append((v-1, w))
  S[v-1].append((u-1, w))
#print(S)
C = [-1] * N
Q = [0]
C[0] = 0
while Q:
  p = Q.pop()
  Ns = S[p]
  #print(Ns)
  for v, w in Ns:
    if C[v] < 0:
      C[v] = (C[p]+w)%2
      Q.append(v)
for i in range(N):
  print(C[i])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, u: "List[int]", v: "List[int]", w: "List[int]"):
    A = [0] * N
    G = [[] for _ in range(N)]
    for i in range(N-1):
        G[u[i]-1].append((v[i]-1, w[i]))
        G[v[i]-1].append((u[i]-1, w[i]))
    stack = [0]
    visited = [0] * N
    while(len(stack) > 0):
        vv = stack.pop()
        visited[vv] = 1
        for k in G[vv]:
            if visited[k[0]] == 0:
                if k[1] % 2 == 0:
                    A[k[0]] = A[vv]
                else:
                    A[k[0]] = abs(A[vv] - 1)
                stack.append(k[0])
    for a in A:
        print(a)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    u = [int()] * (N-1)  # type: "List[int]" 
    v = [int()] * (N-1)  # type: "List[int]" 
    w = [int()] * (N-1)  # type: "List[int]" 
    for i in range(N-1):
        u[i] = int(next(tokens))
        v[i] = int(next(tokens))
        w[i] = int(next(tokens))
    solve(N, u, v, w)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000000)

N = int(input())

q = {}

for i in range(N):
    q[i] = []

for _ in range(N - 1):
    _u, _v, _w = map(int, input().split())

    q[_u - 1].append((_v - 1, _w))
    q[_v - 1].append((_u - 1, _w))

ans = [None] * N
ans[0] = 0


def search(x, parent_num):
    for s in q[x]:
        if ans[s[0]] is None:
            ans[s[0]] = (parent_num + s[1]) % 2
            search(s[0], ans[s[0]])


search(0, 0)

for i in range(N):
    print(ans[i])

Submission status: Accepted

Solution code:
import numpy as np
import sys
INF = float('inf')
sys.setrecursionlimit(10**5)
max = 10**5+5

def dk(start,node,edge):
  ans = [INF] * node
  ans[0] = 0
  q = [start]
  
  while(len(q) != 0):
    i = q.pop()
    for j, cost in edge[i]:
      if(ans[j] != INF):
        continue
      ans[j] = (ans[i] + cost)%2
      q.append(j)
  return ans

#入力
N = int(input())
#エッジ
E = [[] for _ in [0]*(max)]

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


ans = dk(0, N, E)

#出力
print(*ans, sep = "\n")

Submission status: Accepted

Solution code:

import sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 9)
import math

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

tree = [dict() for i in range(N)]
for i in range(N):
	tree[i]["edge"] = []
	tree[i]["color"] = -1
for i in range(N - 1):
	tree[uvw[i][0] - 1]["edge"].append([uvw[i][0], uvw[i][1], uvw[i][2]])
	tree[uvw[i][1] - 1]["edge"].append([uvw[i][1], uvw[i][0], uvw[i][2]])

tansaku = deque([1])
tree[0]["color"] = 0
while len(tansaku) > 0:
	node = tansaku.pop()

	if len(tree[node - 1]["edge"]) == 0:
		continue
	for edge in tree[node - 1]["edge"]:
		if edge[2] % 2 == 0:
			if tree[edge[1] - 1]["color"] == -1:
				tree[edge[1] - 1]["color"] = copy.deepcopy(tree[node - 1]["color"])
				tansaku.append(edge[1])
		else:
			if tree[edge[1] - 1]["color"] == -1:
				tree[edge[1] - 1]["color"] = tree[node - 1]["color"] ^ 1
				tansaku.append(edge[1])
for i in range(N):
	print(tree[i]["color"])

Submission status: Accepted

Solution code:
n = int(input())
links = [set() for _ in range(n)]

for _ in range(n - 1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    w %= 2
    links[v].add((u, w))
    links[u].add((v, w))

colors = [-1] * n
q = [(0, 0, -1)]

while q:
    v, c, p = q.pop()
    colors[v] = c
    for u, w in links[v]:
        if u == p:
            continue
        q.append((u, c ^ w, v))

print('\n'.join(map(str, colors)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)

def dfs(graph, node, dist):
    if graph[node-1][2] == 1:
        return
    else:
        graph[node-1][2] = 1
        graph[node-1][3] += dist
        if graph[node-1][3] % 2 == 0:
            graph[node-1][4] = 1
        else:
            pass
        ll = graph[node-1][0]
        for i in range(len(ll)):
            dfs(graph, ll[i], graph[node-1][3] + graph[node-1][1][i]);

def main():
    n = int(input())
    edge = []
    for i in range(n-1): edge.append(list(map(int,input().split())))

# graph[[node, node, ...], [dist, dist, ...], [reached or not], 
#       [dist from root], [color]]
    graph = [[[],[],0,0,0] for i in range(n)]
    for i in range(n-1):
        node1 = edge[i][0]
        node2 = edge[i][1]
        weight = edge[i][2]
        graph[node1-1][0].append(node2)
        graph[node2-1][0].append(node1)
        graph[node1-1][1].append(weight)
        graph[node2-1][1].append(weight)
    
    dfs(graph, 1, 0)
    for i in range(n):
        print(graph[i][4])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000)

N = int(input())
W = [list(map(int, input().split())) for _ in range(N-1)]
nodes = [[] for _ in range(N+1)]
for w in W:
    nodes[w[0]].append((w[1], w[2]))
    nodes[w[1]].append((w[0], w[2]))
ans = [-1] * (N+1)
ans[1] = 0
def search(num, root, dis):
    for node in nodes[num]:
        sum_d = dis
        if node[0] != root:
            idx = node[0]
            sum_d += node[1]%2
            if sum_d%2 != 0:
                ans[idx] = 1
            else:
                ans[idx] = 0
            search(idx, num, sum_d)

search(1, 0, 0)
for answer in ans[1:]:
    print(answer)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(2**31-1)#ループ回数

def paint(point, color):
    colors[point] = color

    # その点とつながる点で、まだ色が塗られていない点にルールに従い色を塗る
    for friend, w in reration[point]:
        if not colors[friend]:  # 塗られてない点
            # print(str(i)+"塗る")
            nextcolor = color*(-1)**w
            paint(friend, nextcolor)


N = int(input())
reration = [[] for i in range(N)]  # その点がつながる点
colors = ["" for i in range(N)]  # 色(作業中は簡単のため1,-1の2つに塗り分ける)
for i in range(N-1):
    U, V, W = map(int, input().split())
    reration[U-1].append((V-1, W % 2))
    reration[V-1].append((U-1, W % 2))

# print(hen)
# print(reration)
for i in range(N):
    if not colors[i]:
        paint(i, 1)
for co in colors:
    print((co+1)//2)

Submission status: Accepted

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(2**31-1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda : list(map(int,input().split()))
II = lambda : int(input())
dbg = lambda *something : print(*something) if DEBUG is True else 0
DEBUG = False

def main():

    N = II()
    t = [-1] * N


    E = [  [] for _ in range(N)]
 
    reached = [False] * N
    for _ in range(N-1):
        u,v,w = LMIIS()
        u -=1
        v -=1
        E[u].append((v,w))
        E[v].append((u,w))
    dbg(E)
    t[E[0][0][0]] = 0

     
    # def search(u):
    #     for v,w in E[u]:
    #         if t[v] == -1:
    #             t[v] = t[u] if w % 2 == 0 else t[u]^1
    #             search(v)
                

    # search(E[0][0][0])
    reached = [False] * N
    q = []
    q.append(E[0][0][0])
    while q:
        u = q.pop()
        reached[u] = True
        for v,w in E[u]:
            if reached[v] != True and  t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u]^1
                q.append(v)

                



    for i in t:
        write(i)
        write(' ')






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

Submission status: Accepted

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(2**31-1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda : list(map(int,input().split()))
II = lambda : int(input())
dbg = lambda *something : print(*something) if DEBUG is True else 0
DEBUG = False

def main():

    N = II()
    t = [-1] * N


    E = [  [] for _ in range(N)]
 
    reached = [False] * N
    for _ in range(N-1):
        u,v,w = LMIIS()
        u -=1
        v -=1
        E[u].append((v,w))
        E[v].append((u,w))
    dbg(E)
    t[E[0][0][0]] = 0

     
    # def search(u):
    #     for v,w in E[u]:
    #         if t[v] == -1:
    #             t[v] = t[u] if w % 2 == 0 else t[u]^1
    #             search(v)
                

    # search(E[0][0][0])
    reached = [False] * N
    q = deque()
    q.append(E[0][0][0])
    while q:
        u = q.pop()
        reached[u] = True
        for v,w in E[u]:
            if reached[v] != True and  t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u]^1
                q.append(v)

                



    for i in t:
        write(i)
        write(' ')






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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**31-1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda : list(map(int,input().split()))
II = lambda : int(input())
dbg = lambda *something : print(*something) if DEBUG is True else 0
DEBUG = False

def main():

    N = II()
    t = [-1] * N


    E = [  [] for _ in range(N)]
 
    reached = [False] * N
    for _ in range(N-1):
        u,v,w = LMIIS()
        u -=1
        v -=1
        E[u].append((v,w))
        E[v].append((u,w))
    dbg(E)
    t[E[0][0][0]] = 0

     
    # def search(u):
    #     for v,w in E[u]:
    #         if t[v] == -1:
    #             t[v] = t[u] if w % 2 == 0 else t[u]^1
    #             search(v)
                

    # search(E[0][0][0])
    reached = [False] * N
    q = [E[0][0][0]]
    while q:
        u = q.pop()
        reached[u] = True
        for v,w in E[u]:
            if reached[v] != True and  t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u]^1
                q.append(v)

                



    for i in t:
        write(i)
        write(' ')






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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2**31-1)
input = sys.stdin.readline
write = lambda x: sys.stdout.write(str(x))
LMIIS = lambda : list(map(int,input().split()))
II = lambda : int(input())
dbg = lambda *something : print(*something) if DEBUG is True else 0
DEBUG = False

def main():

    N = II()
    t = [-1] * N


    E = [  [] for _ in range(N)]
 
    reached = [False] * N
    for _ in range(N-1):
        u,v,w = LMIIS()
        u -=1
        v -=1
        E[u].append((v,w))
        E[v].append((u,w))
    dbg(E)
    t[E[0][0][0]] = 0

     
    def search(u):
        for v,w in E[u]:
            if t[v] == -1:
                t[v] = t[u] if w % 2 == 0 else t[u]^1
                search(v)
                

    search(E[0][0][0])

    for i in t:
        write(i)
        write(' ')






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

Submission status: Accepted

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

E = [{} for _ in [0]*N]
for u,v,c in UVW:
    E[u-1][v-1] = c
    E[v-1][u-1] = c

def dist_dfs_tree(N,E,start):
    d = [-1]*N
    d[start] = 0
    q = [start]
    while q:
        i = q.pop()
        ci = d[i]
        for j,cj in E[i].items():
            if d[j] !=-1:continue
            d[j] = ci+cj
            q.append(j)
    return d

d = dist_dfs_tree(N,E,0)
print(*[l%2 for l in d],sep="\n")

Submission status: Accepted

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

E = [{} for _ in [0]*N]
for u,v,c in UVW:
    E[u-1][v-1] = c
    E[v-1][u-1] = c

def Dijkstra(N,E,start):
    d = [-1]*N
    q = [(0,start)]
    while q:
        ci,i = heapq.heappop(q)
        if d[i]!= -1:continue
        d[i] = ci
        for j,cj in E[i].items():
            if d[j]!=-1:continue
            heapq.heappush(q,(ci+cj,j))
    return d

d = Dijkstra(N,E,0)
print(*[l%2 for l in d],sep="\n")

Submission status: Accepted

Solution code:
n = int(input())
graph = [[] for _ in range(n + 1)]

for i in range(n - 1):
    a, b, w = map(int, input().split())
    graph[a].append((b, w))
    graph[b].append((a, w))

que = [(1, 0)]

colors = [None] * (n + 1)
while que:
    now, color = que.pop(0)
    colors[now] = color

    for b, w in graph[now]:
        if colors[b] is not None:
            continue
        que.append((b, (color + (w & 1)) & 1))
print("\n".join(map(str, colors[1:])))

Submission status: Accepted

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


def genTree(N, E):
    E2 = [set() for _ in range(N+1)]
    for u, v, w in E:
        E2[u].add((v, w))
        E2[v].add((u, w))

    V = [None]*(N+1)
    Q = [1]

    while len(Q) > 0:
        q = Q.pop()
        s = list(filter(lambda x: V[x[0]] == None, E2[q]))

        V[q] = s
        Q.extend(map(lambda x: x[0], s))

    return V


def main():
    N = int(input())
    E = [tuple(map(int, input().split())) for _ in range(N-1)]

    V = genTree(N, E)
    X = [None]*(N+1)

    X[1] = 0
    Q = [1]
    
    while len(Q) > 0:
        q = Q.pop()
        x = X[q]

        for u, w in V[q]:
            X[u] = (x + w)%2

        Q.extend(map(lambda x: x[0], V[q]))

    for x in X[1:]:
        print(x)

        

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from Queue import Queue
n = int(raw_input())
adjList = [[] for _ in range(n+1)]
colors = [-1] * (n+1)
start = None
for i in range(n-1):
    u, v, w = map(int, raw_input().split())
    adjList[u].append((v, w))
    adjList[v].append((u, w))
    if start is None:
        start = u
def bfs(adjList, colors, start):
    colors[start] = 0
    q = Queue()
    q.put(start)
    while not q.empty():
        u = q.get()
        for adj, w in adjList[u]:
            if colors[adj] == -1:
                if w % 2 == 0:
                    colors[adj] = colors[u]
                else:
                    colors[adj] = colors[u]^1
                q.put(adj)
bfs(adjList, colors, start)
for i in range(1, n+1):
    if colors[i] != -1:
        print colors[i]

Submission status: Accepted

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

n = int(input())

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

#print(lw)

ans = [-1] * (n+1)
q = deque()
ans[1] = 0
q.append(1)
while q:
    r = q.popleft()
    prev = ans[r]
    
    for x in lw[r]:
        #print(x)
        y = x[0]
        if ans[y] >= 0:
            continue
        q.append(y)
        if x[1]%2==0:
            ans[y] = ans[r]
        else:
            ans[y] = 1 - ans[r]

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

Submission status: Accepted

Solution code:
n = int(input())
d = {}
for i in range(n-1):
    u,v,w = map(int,input().split())
    if u-1 not in d:
        d[u-1] = []
        d[u-1].append([v-1,w])
    else:
        d[u-1].append([v-1,w])
    if v-1 not in d:
        d[v-1] = []
        d[v-1].append([u-1,w])
    else:
        d[v-1].append([u-1,w])

ch = [False]*n
res = [-1]*n
q =[0]
res[0] = 0
ch[0] = True
while q != []:
     t = q.pop(0)
     for l in d[t]:
         if ch[l[0]] == True:
             continue
         else:
             ch[l[0]] = True
             res[l[0]] = res[t] + l[1]
             q.append(l[0])
for i in range(n):
    print(res[i]%2)

Submission status: Accepted

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

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

ans = [-1] * (n+1)
lw = [[] for i in range(n+1)]
for path in p:
    lw[path[0]].append((path[1],path[2]))
    lw[path[1]].append((path[0],path[2]))

from _collections import deque
q = deque()
ans[1] = 0
q.append(1)
while q:
    r = q.popleft()
    prev = ans[r]
    assert prev >= 0
    for xx in lw[r]:
        nx = xx[0]
        if ans[nx] >= 0:
            continue  # already
        q.append(nx)
        if xx[1] % 2 == 0:
            ans[xx[0]] = ans[r]
        else:
            ans[xx[0]] = 1 - ans[r]

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

Submission status: Accepted

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

graph = [[] for _ in range(N + 1)]
for u, v, w in edges:
    graph[u].append((v, w))
    graph[v].append((u, w))

edges.sort()
color = [-1] * (N + 1)
color[1] = 0
que = [1]

while que:
    u = que.pop()
    
    for v, w in graph[u]:
        if color[v] != -1:
            continue

        if w % 2 == 0:
            color[v] = color[u]
        else:
            color[v] = color[u] ^ 1
            
        que.append(v)
        
print(*color[1:], sep='\n')

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(100000)
input = sys.stdin.readline

N = int(input())
G = defaultdict(list)
for _ 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))
res = [None] * N


def dfs(v, c):
    res[v] = c
    for u, w in G[v]:
        if res[u] is not None:
            continue
        if w % 2 == 0:
            dfs(u, c)
        else:
            dfs(u, 1 - c)


dfs(0, 0)
for x in res:
    print(x)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())

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

s = 0
ans = [None] * n
ans[s] = 0

dq = deque()
dq.append(s)

while dq:
    v = dq.popleft()
    for nv, w in es[v]:
        if ans[nv] is None:
            ans[nv] = (ans[v] + w) % 2
            dq.append(nv)
print(*ans, sep='\n')

Submission status: Accepted

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

N = int(input())
adj = [[] for i in range(N)]
for _ 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))

color = [0]*N
visited = [0]*N
visited[0] = 1
q = deque()
q.append((0,0))

while q:
    v, l = q.pop()
    visited[v] = 1
    if l % 2 == 1:
        color[v] = 1
    for u, w in adj[v]:
        if not visited[u]:
            q.append((u, l+w))

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

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
adj = [[] for i in range(N)]
for _ 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))

color = [0]*N
visited = [0]*N
visited[0] = 1
q = deque()
q.append((0,0))

while q:
    v, l = q.pop()
    visited[v] = 1
    if l % 2 == 1:
        color[v] = 1
    for u, w in adj[v]:
        if not visited[u]:
            q.append((u, l+w))

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
MAX=10**5+5
tree=[[] for _ in range(MAX)]
ans = [-1]*(MAX)
def dfs(x,weight):
    if(ans[x]>=0):
        return
    ans[x]=weight&1
    for i,w in tree[x]:
        dfs(i,weight+w)

def resolve():
    n =int(input())
    for i in range(n-1):
        u,v,w = map(int,input().split())
        tree[u].append((v,w))
        tree[v].append((u,w))
    dfs(1,0)
    
    for i in range(1,n+1):
        print(ans[i])


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())
G=[[] for i in range(N)]
for i in range(N-1):
    u,v,w=map(int,input().split())
    u,v=u-1,v-1
    w%=2
    G[u].append([u,v,w])
    G[v].append([v,u,w])
color=[-1]*N
color[0]=0
stack=deque(G[0])
while(stack):
    u,v,w=stack.pop()
    if color[v]!=-1:
        continue
    if w==1:
        color[v]=1-color[u]
    else:
        color[v]=color[u]
    stack.extend(G[v])
[print(i) for i in color]

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)

n = int(input())
lis = [[] for i in range(n)]

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

li = [-1] * n

def calc(i,c):
    li[i] = c
    for j, w in lis[i]:
        if li[j] < 0:
            calc(j, li[i]^w)

calc(0,0)

for d in li:
    print(d)

Submission status: Accepted

Solution code:
N = int(input())
INF = float('inf')
dis = [INF]*N
dis[0] = 0
G = [[] for _ in range(N)]
for _ 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))

queue = [0]

while queue:
	u = queue.pop()
	for v, w in G[u]:
		if dis[v] > dis[u] + w:
			queue.append(v)
			dis[v] = dis[u] + w

for i in dis:
	print(i % 2)

Submission status: Accepted

Solution code:
import sys


sys.setrecursionlimit(100000)


def main():
    N = int(input())

    E = {i:{} for i in range(N)}
    for _ in range(N-1):
        u, v, w = map(int, input().split())
        E[u-1][v-1] = w % 2
        E[v-1][u-1] = w % 2
    
    ans = [-1] * N
    def dfs(x):
        for y in E[x]:
            del E[y][x]
            ans[y] = ans[x] if E[x][y] == 0 else 1 - ans[x]
            if len(E[y]) > 0:
                dfs(y)
    
    ans[0] = 0
    dfs(0)
    for a in ans:
        print(a)


main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**5)
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]:
        del t[y][x]
        ans[y] = ans[x] if t[x][y] % 2 == 0 else 1 - ans[x]
        if len(t[y]) > 0:
            dfs(y)
 
 
ans[0] = 0
dfs(0)
for i in range(n):
    print(ans[i])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**5)
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]:
        del t[y][x]
        ans[y] = ans[x] if t[x][y] % 2 == 0 else 1 - ans[x]
        if len(t[y]) > 0:
            dfs(y)


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