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:
n=int(input())
mat=[[] for i in range(n)]
group=[0]*n
group[0]=1
for i in range(n-1):
    u, v, w = map(int, input().split())
    mat[u-1].append((v-1, w))
    mat[v-1].append((u-1, w))
def C(kw, p, l):
    global group
    k, w = kw
    if w%2==1:
        p*=-1
    group[k]=p
    for kwi in mat[k]:
        if kwi[0]!=l:
            C(kwi, p, k)
for kwi in mat[0]:
    C(kwi, 1, 0)
for gi in group:
    if gi>0:
        print(1)
    else:
        print(0)

Submission status: Runtime Error

Solution code:
n = int(input())
U = [[int(a) for a in input().split()] for _ in range(n-1)]


arr = [-1] * n
dic = {}
for u, v, w in U:
    if u in dic:
        dic[u].add((v, w))
    else:
        dic[u] = set([(v, w)])

    if v in dic:
        dic[v].add((u, w))
    else:
        dic[v] = set([(u, w)])

done = set()
def func(u):
    done.add(u)
    for v, w in dic[u]:
        if not v in done:
            arr[v-1] = (arr[u-1] + w) % 2
            func(v)


u, v, w = U[0]
arr[u-1] = 0
func(u)


for i in arr:
    print(i)

Submission status: Runtime Error

Solution code:
N = int(input())
W = []
for _ in range(N - 1):
    u, v, w = map(int, input().split())
    W.append([u - 1, v - 1, w])
color = [0] * N
tree = [[] for _ in range(N)]
for w in W:
    tree[w[0]].append([w[1], w[2]])
    tree[w[1]].append([w[0], w[2]])
for i, t in enumerate(tree):
    if len(t) == 1:
        start = i
        break


def rec(n, prev, w):
    if color[prev] == color[n]:
        if w % 2 == 1:
            color[n] = 1 if color[prev] == 0 else 0
    elif w % 2 == 0:
        color[n] = color[prev]
    for i in tree[n]:
        if i[0] == prev:
            continue
        else:
            rec(i[0], n, i[1])


rec(tree[start][0][0], start, tree[start][0][1])
for c in color:
    print(c)

Submission status: Runtime Error

Solution code:
import numpy as np

n = int(input())

g = np.zeros((n, n), dtype=np.int)
ans = np.full(n, -1, dtype=np.int)

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


ans[0] = 0 # white

def dfs(now):
    for i in range(n):
        if i == now or ans[i] != -1 or g[i][now] == 0:
            continue
        elif g[i][now] % 2 == 0:
            ans[i] = ans[now]
            dfs(i)
        else:
            ans[i] = ans[now] ^ 1
            dfs(i)


dfs(0)

for a in ans:
    print(a)

Submission status: Runtime Error

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

col = [-1 for _ in range(2*N)]
def dfs(x, c):
    col[x] = c
    for v, w in e[x]:
        if col[v] == -1:
            dfs(v, (c+w%2)%2)

dfs(1, 0)

for c in col[1:]:
    print(c)

Submission status: Runtime Error

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

n = int(input())
tree = [0]
for i in range(1, n+1):
    tree.append(i)


def root(x):
    if(tree[x] == x):
        return x
    tree[x] = root(tree[x])
    return tree[x]  # 経路圧縮


def same(x, y):  # xとyが同じ木に属するか
    return root(x) == root(y)


def unite(x, y):
    x = root(x)
    y = root(y)
    if(x == y):
        return
    tree[x] = y


for _ in range(n-1):
    u, v, w = map(int, input().split())
    if(w % 2 == 0):
        unite(u, v)

for i in range(1, n+1):
    if (same(1, i)):
        print(0)
    else:
        print(1)

Submission status: Runtime Error

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

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
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:
			p = (k + x[n][i][1]) % 2
			if p == 0:
				a[x[n][i][0]] = 0
				oon(x,x[n][i][0],n,p)
			else:
				oon(x,x[n][i][0],n,p)
		else:
			continue


nnn = int(input())

a = [1 for i in range(nnn)]
a[0] = 0
b = [[] for i in range(nnn)]

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

oon(b,0,0,0)

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

Submission status: Runtime Error

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

ans=[0]*n
ans[0]=0
for i in range(n-1):
  if w[i]%2==0:
    ans[v[i]-1]=ans[u[i]-1]
  else:
    ans[v[i]-1]=(ans[u[i]-1]+1)%2
for ii in range(n):
  print(a[ii])

Submission status: Runtime Error

Solution code:
def search(i, visited, ns, ans) :
    #print(i+1)
    visited[i] = True
    for next, weight in ns[i]:
        if visited[next] == False:
            if weight % 2 == 0:
                ans[next] = ans[i]
            else:
                ans[next] = (ans[i]+1) % 2
            search(next, visited, ns, ans)


def dfs(ns, ans):
    visited = [False] * len(ns)
    search(0, visited, ns, ans)

def main():
    n = int(input())
    ns = [[] for _ in range(n)]
    for _ in range(n-1):
        (st,end,weight) = map(int,input().split())
        ns[st-1].append((end - 1,weight))
        ns[end-1].append((st-1,weight))
    ans = [False] * n
    dfs(ns, ans)
    for a in ans:
        if a:
            print(1)
        else:
            print(0)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N = int(input())
ans = ['NIL' for i in range(N+1)]
appeared_num = []

if N == 1:
    print(1)
else:

    #1回目
    line = list(map(int, input().split()))
    appeared_num += [line[0], line[1]]
    if line[2] % 2 == 0:
        ans[line[0]] = 1
        ans[line[1]] = 1
    else:
        ans[line[0]] = 1
        ans[line[1]] = 0

    #2回目以降
    remain = []
    for i in range(N-2):
        line = list(map(int, input().split()))
        length = line[2] % 2
        if line[0] in appeared_num:
            if ans[line[0]] == 1:
                ans[line[1]] = (1 + length) % 2
            else:
                ans[line[1]] = length
            appeared_num += [line[1]]


        elif line[1] in appeared_num:
            if ans[line[1]] == 1:
                ans[line[0]] = (1 + length) % 2
            else:
                ans[line[0]] = length
                appeared_num += [line[0]]

        else:
            remain += line

    #2周目以降
    while len(remain) != 0:
        l = len(remain)
        for i in range(l):
            line = remain[i]
            length = line[2] % 2
            if line[0] in appeared_num:
                if ans[line[0]] == 1:
                    ans[line[1]] = (1 + length) % 2
                else:
                    ans[line[1]] = length
                appeared_num += [line[1]]
                remain.pop(i)


            elif line[1] in appeared_num:
                if ans[line[1]] == 1:
                    ans[line[0]] = (1 + length) % 2
                else:
                    ans[line[0]] = length
                    appeared_num += [line[0]]
                remain.pop(i)

            else:
                pass

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

Submission status: Runtime Error

Solution code:
N = int(input())
nodes = {}
for _ in range(N-1):
    l, r, d = map(int, input().split())
    if nodes.get(str(l)) is None:
        nodes[str(l)] = {'to': [], 'color': -1}
    if nodes.get(str(r)) is None:
        nodes[str(r)] = {'to': [], 'color': -1}

    nodes[str(l)]['to'].append((str(r), d))
    nodes[str(r)]['to'].append((str(l), d))


def dfs(node, color):
    nodes[node]['color'] = color
    for n, d in nodes[node]['to']:
        if nodes[n]['color'] != -1:
            continue

        if d % 2 == 0:
            dfs(n, color)
        else:
            dfs(n, (color+1) % 2)


dfs('1', 0)
for i in range(1,N+1):
    print(nodes[str(i)]['color'])

Submission status: Runtime Error

Solution code:
n = int(input())
ans = [-1]*(n+1)
data =[[] for i in range(n+1)]

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

ans[1] = 1
def color(i):
    for v, w in data[i]:
        if ans[v] == -1:
            if w % 2 == 0:
                ans[v] = ans[i]
            else:
                ans[v] = 1 - ans[i]
            color(v)
    return

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

Submission status: Runtime Error

Solution code:
import numpy as np
N=int(input())
G=np.zeros((N+1,N+1)).astype('int')
for _ in range(N-1):
    u,v,w = map(int, input().split())
    G[u][v]=w
dist=[0 for _ in range(N+1)]
def answer(i):
    index=np.where(G[i]>0)
    index=index[0]
    if len(index)>0:
        for j in index:
            dist[j]=dist[i]+G[i][j]
            answer(j)
answer(1)
for d in dist[1:]:
    if d%2==0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

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

col = [-1 for _ in range(N+1)]
def dfs(x, c):
    col[x] = c
    for v, w in e[x]:
        if col[v] == -1:
            dfs(v, (c+w%2)%2)

dfs(1, 0)

for c in col[1:]:
    print(c)

Submission status: Runtime Error

Solution code:
import sys

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

uvw = [(u, v, w) if u < v else (v, u, w) for u, v, w in uvw]
uvw = sorted(uvw, key=lambda x: x[0])

#  0: 白
#  1: 黒
# -1: 未確定
wb = [-1] * n

# とりあえず一箇所を白に固定する
wb[0] = 0

# 残りの未確定頂点数
progress = n - 1

i = 0
while uvw:
  u, v, w = uvw[i]
  u -= 1
  v -= 1
  if wb[u] == -1 and wb[v] == -1:
      # 両方未確定なので何も出来ない
      i = i + 1
      continue
  if wb[u] in (0, 1):
      u, v = v, u
  if w % 2 == 0:
      wb[u] = wb[v]
  else:
      wb[u] = 1 - wb[v]
  
  uvw.pop(i)
  progress -= 1
  if progress == 0:
      # 完了
      print(*wb, sep='\n')
      sys.exit(0)

Submission status: Runtime Error

Solution code:
def dfs(s):
    visited[s]=1
    for v in adj[s]:
        if v not in visited:
            if (s,v) in we:
                y[v]=y[s]+we[(s,v)]
            elif (v,s) in we:
                y[v]=y[s]+we[(v,s)]
            dfs(v)
n=int(input())
adj={}
we={}
visited={}
y=[0]*(n+1)
for q in range(n-1):
    a,b,w=map(int,input().split())
    if a not in adj:
        adj[a]=[b]
    else:
        adj[a].append(b)
    if b not in adj:
        adj[b]=[a]
    else:
        adj[b].append(a)
    we[(a,b)]=w
dfs(1)
for i in range(1,n+1):
    if y[1]%2==0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
N = int(input())

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

color = {}
for i in range(1, N+1):
    color[i] = -1

for i in range(1 ,len(odd)):
    print("{}:{}".format(i,odd[i]))
    color[odd[i][0]] = 0
    color[odd[i][1]] = 0

for i in range(1, len(even)):
    tmp = even.pop(i)
    print(tmp)
    if color[tmp[0]] == 0:
        color[tmp[1]] = 1
    elif color[tmp[0]] == 1:
        color[tmp[1]] = 0
    elif color[tmp[1]] == 0:
        color[tmp[0]] = 1
    elif color[tmp[1]] == 1:
        color[tmp[0]] = 0
    else:
        even.append(tmp)

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

Submission status: Runtime Error

Solution code:
import numpy as np
N = int(input())
D = np.zeros((N, N), dtype=np.uint)
for _ in range(N-1):
    u, v, w = map(int, input().split())
    D[u-1, v-1] = D[v-1, u-1] = 1
#print(D)
l = np.zeros(N, dtype=np.uint)
i = [0]
for n in range(N):
    w = np.where(D[i]==1)[1]
    l[w] = (1+n)%2
    #print(l)
    D[i] = 0
    D[:,i] = 0
    i = w
    #print(D)
    if np.max(D) == 0:
        break
for i in range(N):
    print(l[i])

Submission status: Runtime Error

Solution code:
n=int(input())
mat=[[]*n for _ in range(n)]
group=[0]*n
group[0]=1
for i in range(n-1):
    u, v, w = map(int, input().split())
    mat[u-1].append((v-1, w))
    mat[v-1].append((u-1, w))
def C(kw, p, l):
    global group
    k, w = kw
    if w%2==1:
        p*=-1
    group[k]=p
    for kwi in mat[k]:
        if kwi[0]!=l:
            C(kwi, p, k)
for kwi in mat[0]:
    C(kwi, 1, 0)
for gi in group:
    if gi>0:
        print(1)
    else:
        print(0)

Submission status: Runtime Error

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

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

dist = {}

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

def visit(current, v, dist, color):
   
    for it in v[current]:
        if color[it] != None:
            continue
        if dist[(it, current)]%2 == 0:
            color[it] = color[current]
        else:
            color[it] = not color[current]
        visit(it, v, dist, color)
        
color = [None for _ in range(n+1)]
color[1]=True
visit(1, v, dist, color)

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

Submission status: Runtime Error

Solution code:
class unionfind:
    def __init__(self, n):
        self.parent = [-1 for i in range(1, n + 1)]

    def find(self, x):
        if self.parent[x-1] < 0:
            return x
        else:
            self.parent[x-1] = self.find(self.parent[x-1])
            return self.parent[x-1]

    def union(self, x, y):
        x, y = self.find(x), self.find(y)
        if (x == y):
            pass
        else:
            self.parent[x-1] += self.parent[y-1]
            self.parent[y-1] = x

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

uf = unionfind(n)

for i in uvw:
    if i[2] % 2 == 0:
        uf.union(i[0],i[1])

for i in range(1,n+1):
    result = uf.find(i)
    print(result if result == 1 else "0")

Submission status: Runtime Error

Solution code:
import numpy as np

N = int(input())
mat = np.full((N, N), -1)
ans = [-1] * N
for _ in range(N-1):
    u, v, w = map(int, input().split())
    mat[u-1, v-1] = w
    mat[v-1, u-1] = w


def search(row):
    for j in range(N):
        if ans[j] == -1 and mat[row, j] != -1:
            # check column
            if mat[row, j] % 2 == 0:
                ans[j] = ans[row]
            else:
                if ans[row] == 0:
                    ans[j] = 1
                else:
                    ans[j] = 0
            # nest
            if ans[j] != -1:
                search(row=j)

ans[0] = 0
search(row=0)
for i in range(N):
    print(ans[i])

Submission status: Runtime Error

Solution code:
N = int(input())
u_v_w = []
ans = np.full(2,N)
u = []
for i in range(N):
	u_v_w.append(list(map(int,input())))	
	u.append(u_v_w[i][0])
	v.append(u_v_w[i][1])

ans[0] = 0
for j in range(N-1):
	spot = v.index(j+1)
	if u_v_w[spot][2] % 2 == 0:
		if ans[u_v_w[spot][0]] == 0:
			ans[j+1] = 0
		else:
			ans[j+1] = 1
	else:
		if ans[u_v_w[spot][0]] == 0:
			ans[j+1] = 1
		else:
			ans[j+1] = 0

Submission status: Runtime Error

Solution code:
import numpy as np
import math

def contrary_bit(bit):
    if (bit == 1):
        return 0
    elif (bit == 0):
        return 1
    else:
        print("error")

def dfs(adj_lists, nodes, node):
    # nodeから出発して，深さ優先探索
    neighbors = adj_lists[node]
    for neighbor in neighbors:
        if (nodes[neighbor[0]] != -1):
            #訪問済み
            continue
        else:
            if neighbor[1] %2 == 0:
                # 同じbit  
                nodes[neighbor[0]]= nodes[node]
                nodes = dfs(adj_lists, nodes, neighbor[0])
            else:
                nodes[neighbor[0]] = contrary_bit(nodes[node])
                nodes = dfs(adj_lists, nodes, neighbor[0])
    return nodes

def main():
    N = int(input())
    adj_lists = {}
    for i in range(1, N + 1):
        adj_lists[i] = []
    # adj_lists = {i: []} # u: [(v, w), []]
    nodes = [-1] * (N + 1)
    for _ in range(N - 1):
        u, v, w = map(int, input().split())
        adj_lists[u].append((v, w))
        adj_lists[v].append((u, w))
    nodes[1] = 1
    nodes = dfs(adj_lists, nodes, 1)
    ans = nodes[1:]
    for color in ans:
        print(color)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# AtCoder Beginner Contest 126
# https://atcoder.jp/contests/abc126
import sys
#import numpy as np

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N = i2n()
    uvw = ii2nnn(N-1)
    d = [[] for _ in range(N)]
    for u, v, w in uvw:
        b = w % 2 == 0
        d[u-1].append((v-1, b))
        d[v-1].append((u-1, b))
    nn = [-1 for _ in range(N)]
    nn[0] = 0
    def main2(src):
        links = d[src]
        c = nn[src]
        for dst, b in links:
            if nn[dst] == -1:
                nn[dst] = c if b else 1-c
                main2(dst)
    main2(0)
    for n in nn:
        print(n)

main()

Submission status: Runtime Error

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

col = [-1 for _ in range(N+1)]
def dfs(x, c):
    col[x] = c
    for v, w in e[x]:
        if col[v] == -1:
            dfs(v, c+w%2)

dfs(1, 0)

for c in col[1:]:
    print(c)

Submission status: Runtime Error

Solution code:
n = int(input())
edge = [[] for i in range(n)]
colors = [-1] * n
for i in range(n-1):
    u, v, w = [int(item) for item in input().split()] 
    u -= 1
    v -= 1
    edge[u].append([v, w%2])
    edge[v].append([u, w%2])

def dfs(frm, n):
    for tv, tw in edge[n]:
        if tv == frm:
            continue
        else:
            if tw == 1:
                colors[tv] = (colors[frm] + 1) % 2
            else:
                colors[tv] = colors[frm]
            dfs(n, tv)

colors[0] = 0
dfs(0, 0)
for item in colors:
    print(item)

Submission status: Runtime Error

Solution code:
n=int(input())
aa=set()
for _ in range(n-1):
    u,v,w=map(int,input().split())
    if w % 2:
        aa.add((u,v))
bb = [-1] * n
for u,v in aa:
    if bb[u-1] < 0 and bb[v-1] < 0:
        bb[u-1] = 0
        bb[v-1] = 1
    elif bb[u-1] < 0:
        bb[u-1] = 1 - bb[v-1]
    elif bb[v-1] < 0:
        bb[v-1] = 1 - bb[u-1]
    else:
        assert bb[u-1] == bb[v-1]
for b in bb:
    print(1 if b == 1 else 0)

Submission status: Runtime Error

Solution code:
n,m=[int(i) for i in input().split()]
ls=[]
for i in range(m):
    l=input().split()
    l.pop(2)
    ls.append([int(i) for i in l].sort())

from itertools import chain
count=len(set(range(n+1))-set(chain.from_iterable(ls))-{0})
sorted(ls)
while len(ls) != 0:
    ls = [i for i in ls if not (i.__contains__(ls[0][0]) or i.__contains__(ls[0][1]))]
    count+=1
print(count)

Submission status: Runtime Error

Solution code:
import sys,collections as cl,bisect as bs
Max = sys.maxsize

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:
			if (k + x[n][i][1]) % 2 == 0:
				a[x[n][i][0]] = 0
				oon(x,x[n][i][0],n,(k + x[n][i][1]) % 2)
			else:
				oon(x,x[n][i][0],n,(k + x[n][i][1]) % 2)


nnn = int(input())

a = [1 for i in range(nnn)]
a[0] = 0
b = [[] for i in range(nnn)]

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

oon(b,0,0,0)

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

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline

N = int(input())
nodes = deque()
for i in range(N - 1):
    nodes.append(list(map(int, input().split())))

B, W = set(), set()
u, v, w = nodes.popleft()
if w % 2 == 0:
    B.add(u)
    B.add(v)
else:
    B.add(u)
    W.add(v)

while len(nodes) != 0:
    u, v, w = nodes.popleft()
    if w % 2 == 0:
        if u in B or v in B:
            B.add(u)
            B.add(v)
        elif u in W or v in W:
            W.add(u)
            W.add(v)
        else:
            nodes.append(u, v, w)
    else:
        if u in B or v in W:
            B.add(u)
            W.add(v)
        elif u in W or v in B:
            W.add(u)
            B.add(v)
        else:
            nodes.append(u, v, w)

ans = [0] * N
for x in W:
    ans[x - 1] = 1
for x in ans:
    print(x)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void f(vector<vector<pair<int, int>>>& edges, int i, int len, vector<int>& ans){
    ans[i]=len%2==0 ? 1 : 2;
    for(auto& adj : edges[i]){
        if(ans[adj.first]) continue;
        f(edges, adj.first, adj.second+len, ans);
    }
}

int main(){
    int n; cin >> n;
    vector<int> degs(n);
    vector<vector<pair<int, int>>> edges(n);
    for(int i=0; i<n-1; ++i){
        int u, v, w; cin >> u >> v >> w;
        --u; --v;
        edges[u].push_back(make_pair(v, w%2));
        edges[v].push_back(make_pair(u, w%2));
        ++degs[u];
        ++degs[v];
    }
    int root=0;
    for(int i=0; i<n; ++i){
        if(degs[i]==1){
            root=i;
            break;
        }
    }
    vector<int> ans(n);
    f(edges, root, 0, ans);
    for(int i=0; i<n; ++i){
        cout << ans[i]-1 << endl;
    }
    return 0;
}

Submission status: Runtime Error

Solution code:
n = int(input())
ans = [0 for i in range(n)]
for i in range(n):
    u,v,w = map(int, input().split())
    if w % 2 == 0:
        ans[u-1] = 1
        ans[v-1] = 1
        break

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
import numpy as np

N = int(input())
mat = np.full((N, N), -1)
ans = [-1] * N
for _ in range(N-1):
    u, v, w = map(int, input().split())
    mat[u-1, v-1] = w
    mat[v-1, u-1] = w


def search(row):
    for j in range(N):
        if ans[j] == -1 and mat[row, j] != -1:
            if mat[row, j] % 2 == 0:
                ans[j] = ans[row]
            else:
                if ans[row] == 0:
                    ans[j] = 1
                else:
                    ans[j] = 0
            search(row=j)
print(mat)
ans[0] = 0
search(row=0)
for i in range(N):
    print(ans[i])

Submission status: Runtime Error

Solution code:
import math

N = int(input())


class Tree:
    def __init__(self, n):
        self.par = [i for i in range(N+1)]


tree = [list() for _ in range(N)]
color = [-1 for _ in range(N)]
color[0] = 0

for _ in range(N-1):
    u, v, w = map(int, input().strip().split(' '))
    tree[u-1] += [(v-1, w % 2)]
    tree[v-1] += [(u-1, w % 2)]


def dfs(pos):
    for (p, w) in tree[pos]:
        if color[p] != -1:
            continue
        color[p] = color[pos] ^ w
        dfs(p)


dfs(0)
for c in color:
    print(c)

Submission status: Runtime Error

Solution code:
###
### atcorder test program
###

import sys
import math

### math class
# class math:
#     ### pi
#     pi = 3.14159265358979323846264338

#     ### GCD
#     def gcd(self, a, b):
#         if b == 0:
#             return a
#         return self.gcd(b, a%b)

#     ### LCM
#     def lcm(self, a, b):
#         return (a*b)//self.gcd(a,b)

# math = math()

### output class
class output:
    ### list
    def list(self, l):
        l = list(l)
        print(" ", end="")
        for i, num in enumerate(l):
            print(num, end="")
            if i != len(l)-1:
                print(" ", end="")
        print()

output = output()

### input sample
#i = input()
#A, B, C = [x for x in input().split()]
#N, K = [int(x) for x in input().split()]
#inlist = [int(w) for w in input().split()]
#R = float(input())
#A = [int(x) for x in input().split()]
#for line in sys.stdin.readlines():
#    x, y = [int(temp) for temp in line.split()]

### output sample
#print("{0} {1} {2:.5f}".format(A//B, A%B, A/B))
#print("{0:.6f} {1:.6f}".format(R*R*math.pi,R*2*math.pi))
#print(" {}".format(i), end="")

N = int(input())
data = []
ans = [0 for i in range(N)]

for i in range(N-1):
    data.append([int(x) for x in input().split()])

data.sort()

for link in data:
    if link[2]%2 == 1:
        ans[link[1]-1] = 1 if ans[link[0]-1] == 0 else 0

for link in data:
    if link[2]%2 == 1:
        ans[link[1]-1] = 1 if ans[link[0]-1] == 0 else 0

###
### atcorder test program
###

import sys
import math

### math class
# class math:
#     ### pi
#     pi = 3.14159265358979323846264338

#     ### GCD
#     def gcd(self, a, b):
#         if b == 0:
#             return a
#         return self.gcd(b, a%b)

#     ### LCM
#     def lcm(self, a, b):
#         return (a*b)//self.gcd(a,b)

# math = math()

### output class
class output:
    ### list
    def list(self, l):
        l = list(l)
        print(" ", end="")
        for i, num in enumerate(l):
            print(num, end="")
            if i != len(l)-1:
                print(" ", end="")
        print()

output = output()

### input sample
#i = input()
#A, B, C = [x for x in input().split()]
#N, K = [int(x) for x in input().split()]
#inlist = [int(w) for w in input().split()]
#R = float(input())
#A = [int(x) for x in input().split()]
#for line in sys.stdin.readlines():
#    x, y = [int(temp) for temp in line.split()]

### output sample
#print("{0} {1} {2:.5f}".format(A//B, A%B, A/B))
#print("{0:.6f} {1:.6f}".format(R*R*math.pi,R*2*math.pi))
#print(" {}".format(i), end="")

N = int(input())
data = []
ans = [0 for i in range(N)]

for i in range(N-1):
    data.append([int(x) for x in input().split()])

data.sort()

for link in data:
    if link[2]%2 == 1:
        ans[link[1]-1] = 1 if ans[link[0]-1] == 0 else 0

for link in data:
    if link[2]%2 == 1:
        ans[link[1]-1] = 1 if ans[link[0]-1] == 0 else 0

for i in ans:
    print(i)


for i in ans:
    print(i)

Submission status: Runtime Error

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

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
N = int(input())

NG_pair_li = []
NG_set_li = []
NG_set = ()

first_li = []

color = [7]*N

for i in range(N-1):
    u, v, w =  list(map(int, input().split(" ")))
    if w%2 != 0:
        if u in NG_set and v in NG_set:
            first.append([u, v])
            NG_set_li.extend([u, v])
            NG_set = set(NG_set_li)
        else:
            NG_pair_li.append([u, v])
            NG_set_li.extend([u, v])
            NG_set = set(NG_set_li)
            
for u, v in first_li:
    color[u-1] = 1
    color[v-1] = 0
    
for u, v in NG_pair_li:
    u_bool = color[u-1] != 7
    v_bool = color[v-1] != 7
    
    if u_bool and v_bool:
        pass
    elif u_bool:
        if color[u-1] == 1:
            color[v-1] = 0
        else:
            color[v-1] = 1
    elif v_bool:
        if color[v-1] == 1:
            color[u-1] = 0
        else:
            color[u-1] = 1
    else:
        color[u-1] = 0
        color[v-1] = 1
        
for c in color:
    if c == 7:
        print(1)
    else:
        print(c)

Submission status: Runtime Error

Solution code:
from collections import deque

def parse(f):
    N = int(next(f))
    return N, deque([[int(s) for s in next(f).split()] for _ in range(N-1)])

def main(N, uvw):
    if N == 1:
        return [0]
    tree = [-1 for _ in range(N+1)]
    u, v, w = uvw.popleft()
    tree[u] = 0
    if w % 2 == 0:
        tree[v] = 0
    else:
        tree[v] = 1
    while uvw:
        u, v, w = uvw.popleft()
        if tree[u] < 0 and tree[v] < 0:
            uvw.push([u, v, w])
        elif tree[u] < 0 and tree[v] >= 0:
            u, v = v, u
            if w % 2 == 0:
                tree[v] = tree[u]
            else:
                tree[v] = 1 - tree[u]
        elif tree[u] >= 0 and tree[v] < 0:
            if w % 2 == 0:
                tree[v] = tree[u]
            else:
                tree[v] = 1 - tree[u]
        else:
            return [0] * N

    return tree[1:]


import sys

print('\n'.join(map(str, main(*parse(sys.stdin)))))

Submission status: Runtime Error

Solution code:
import collections

n=int(input())
ans=[0]*(n+1)
arr=[list(map(int,input().split())) for _ in range(n-1)]
arr=sorted(arr,key=lambda x:x[0])
s=set()
tmp=arr[0]
u,v,w=tmp[0],tmp[1],tmp[2]
s.add(u)
s.add(v)
if w%2==0:
  ans[u]=1
  ans[v]=1
elif w%2==1:
  ans[u]=1
  ans[v]=0
q=collections.deque()
cnt=1
cnt2=1
while 1:
  if cnt==n-1:
    break
  else:
    if cnt2<n:
      tmp=arr[cnt2]
      u,v,w=tmp[0],tmp[1],tmp[2]
    else:
      tmp=q.popleft()
      u,v,w=tmp[0],tmp[1],tmp[2]
    cnt2+=1
    if u in s:
      s.add(v)
      cnt+=1
      if w%2==0:
        ans[v]=ans[u]
      else:
        ans[v]=abs(ans[u]-1)
    elif v in s:
      s.add(u)
      cnt+=1
      if w%2==0:
        ans[u]=ans[v]
      else:
        ans[u]=abs(ans[v]-1)
    else:
      q.append([u,v,w])
for i in range(1,n+1):
  print(ans[i])

Submission status: Runtime Error

Solution code:
N = int(input())
uvw = [[int(x) for x in input().split()] for _ in range(N-1)]

par = [i for i in range(N)]
dist = [0]*N

def root(x):
    if(par[x]==x):
        return x
    else:
        return root(par[x])

def unite(x,y,z):
    rx = root(x)
    ry = root(y)
    if rx==ry:
        return
    else:
        par[rx] = ry
        dist[rx] = z%2

def dist_type(x):
    if(par[x]==x):
        return 0
    else:
        return (dist_type(par[x])+dist[x])%2

for u,v,w in uvw:
    unite(u-1,v-1,w%2)

for i in range(N):
    print(dist_type(i))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# coding: utf-8

import math

def paint(k, v, diff, visited, same, opposite):
    if k in visited:
        return
    if k in same:
        return
    same.add(k)
    visited.add(k)
    for e in v:
        if e in visited:
            continue
        paint(e, diff[e], diff, visited, opposite, same)

def main():
    n = int(input())
    diff = {}
    for _ in range(n-1):
        u, v, w = list(map(int, input().split()))
        if w % 2 == 1:
            diff.setdefault(u, [])
            diff.setdefault(v, [])
            diff[u].append(v)
            diff[v].append(u)
    white = set()
    black = set()
    visited = set()
    for k in diff:
        paint(k, diff[k], diff, visited, white, black)
    ret = []
    for i in range(n):
        if i+1 in white:
            ret.append("0")
        else:
            ret.append("1")
    print("\n".join(ret))


if __name__ == '__main__':
    main()