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:
from collections import defaultdict
import sys
input = sys.stdin.readline
N = int(input())

tree_dict = defaultdict(list)
for i in range(N-1):
    u, v, w = list(map(int, input().split()))
    tree_dict[u].append((v, w))
    tree_dict[v].append((u, w))
# print(tree_dict)


# 探索
for key, value in tree_dict.items():
    if len(value) == 1:
        break
# print(key)
paint_dict = dict()

q = [key]
paint_dict[key] = 0

idx = 0
while idx < N:
    k = q[idx]
    #print("k", k, paint_dict[k])
    for to, w in tree_dict[k]:
        if to not in [i[0] for i in tree_dict[to]]:
            if (w + paint_dict[k]) % 2 == 0:
                paint_dict[to] = 0
            else:
                paint_dict[to] = 1
            #print(paint_dict[to], to, w)
            q.append(to)
    idx += 1
for i in range(N):
    print(paint_dict[i+1])

Submission status: Runtime Error

Solution code:
import random
n = int(input())
listA = []
listB = []
listN=[]
stockL=[]
index=0
while index < n-1:
    u, v, w = map(int, input().split())
    if w %2== 1:
        listA.append(u)
        listB.append(v)
        listN.append(u)
        listN.append(v)
    else:
        stockL.append([u, v])
    index+=1

flag=1
while flag:
    flag=0
    index=0
    while index < len(stockL):
        u = stockL[index][0]
        v = stockL[index][1]
        if u in listA:
            if v in listB:
                flag=1
                vI = listB.index(v)
                uI = listA.index(u)
                if random.random() > 0.5:
                    listA[vI], listB[vI] = listB[vI], listA[vI]
                else:
                    listA[uI], listB[uI] = listB[uI], listA[uI]
            else:
                if v in listA:
                    pass
                else:
                    listA.append(v)
        elif u in listB:
            if v in listA:
                flag=1
                vI = listA.index(v)
                uI = listB.index(u)
                if random.random() > 0.5:
                    listA[vI], listB[vI] = listB[vI], listA[vI]
                else:
                    listA[uI], listB[uI] = listB[uI], listA[uI]
            else:
                if v in listB:
                    pass
                else:
                    listB.append(v)
        else:
            if v in listB:
                listB.append(u)
            elif v in listA:
                listA.append(u)
            else:
                pass
        index+=1
index2=1
while index2 < n+1:
    if index2 in listA:
        print(0)
    elif index2 in listB:
        print(1)
    else:
        print(0)
    index2+=1

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10000)
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:
nnn = int(input())

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

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


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



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())
uvw = [list(map(int,input().split())) for i in range(N)]

list_ans = []
list_ans.append(True)
buf_0 = 0
buf_1 = 1
for i in range(1,N):
    if list_ans[i-1] == 0:
        buf_0 = 0
        buf_1 = 1
    else:
        buf_0 = 1
        buf_1 = 1
    if (uvw[i][2] % 2) == 0:
        list_ans.append(buf_0)
    else:
        list_ans.append(buf_1)

for ans in list_ans:
    print(ans)

Submission status: Runtime Error

Solution code:
n = list(map(int, input().split()))
dist = [list(map(int, input().split())) for _ in range(n)]

branch = [0]*n

dist.sort()

for i in range(n):
    if dist[i][2] % 2 == 1:
        if branch[dist[i][0]-1] == 0:
            branch[dist[i][1]-1] == 1
        if branch[dist[i][0]-1] == 1:
            branch[dist[i][1]-1] == 0

for j in range(n):
    print(branch[j])

Submission status: Runtime Error

Solution code:
import sys

input = sys.stdin.readline

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

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

Submission status: Runtime Error

Solution code:
def solve():
    n = int(input())
    ans = [-1] * (n + 1)
    li = [[] for _ in range(n + 1)]
    for _ in range(n - 1):
        u, v, w = map(int, input().split())
        li[u].append((v, w))
        li[v].append((u, w))
    def f(i, ans, c):
        for u, w in li[i]:
            if ans[u] == -1:
                if w % 2 == 0:
                    ans[u] = c
                    f(u, ans, c)
                else:
                    ans[u] = c ^ 1
                    f(u, ans, c ^ 1)
    for i in range(1, n):
        if li[i] != [] and ans[i] == -1:
            ans[i] = 0
            f(i, ans, 0)
    print(*ans[1:], sep="\n")
solve()

Submission status: Runtime Error

Solution code:
import numpy as np
N = int(input().strip())
edges = np.zeros((N,N))
distance = np.zeros(N)

def find(idx):
	check.append(idx)
	route = edges[idx,:]
	for j, x in enumerate(route):
		if x != 0:
			distance[j]+=x
			if j not in check:
				find(j)
				#print(j)
			check.append(j)


for i in np.arange(N-1):
	s, d, w = [ int(x) for x in input().strip().split(" ")]
	edges[s-1][d-1] = w
	edges[d-1][s-1] = w
#print(edges)

check = []

find(0)

for x in distance:
	if x%2==0:
		print(0)
	else:
		print(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:
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 = []

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

uvw = sorted(uvw)
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):
    print("1" if uf.find(i) == uf.find(1) else "0")

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] % 10**9
            answer(j)
answer(1)
for d in dist[1:]:
    if d%2==0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
class UnionFind():
    def __init__(self, size):
        self.table = [-1 for _ in range(size)]
        self.size = [1 for _ in range(size)]

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

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] > self.table[s2]:
                self.table[s2] = s1
                self.table[s1] -= 1
                self.size[s1] += self.size[s2]
                self.size[s2] = 0
            else:
                self.table[s1] = s2
                self.table[s2] -= 1
                self.size[s2] += self.size[s1]
                self.size[s1] = 0
        return

n = int(input())

uf = UnionFind(n)

for i in range(n-1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    # 同じなら0、違ったら1
    if w % 2 == 0:
        uf.union(u, v)

ans = []
for i in range(n):
    ans.append(uf.find(i))
num = list(set(ans))[0]
out = list(map(lambda x: 0 if x == num else 1, ans))

for color in out:
    print(color)

Submission status: Runtime Error

Solution code:
import pandas as pd

N = int(input())

u = [0] * (N-1)
v = [0] * (N-1)
w = [0] * (N-1)
ans = [0] * N

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

df = pd.DataFrame({'u': u, 'v': v, 'w': w})
df_sorted = df.sort_values(['u', 'v'])

u = df_sorted['u'].values
v = df_sorted['v'].values
w = df_sorted['w'].values

for i in range(N-1):
    if w[i] % 2 == 1:
        if ans[u[i]-1] == 0:
            ans[v[i]-1] = 1
        if ans[u[i]-1] == 1:
            ans[v[i]-1] = 0

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

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] % 10**9
            answer(j)
answer(1)

Submission status: Runtime Error

Solution code:
from collections import deque


ans = {1:1}

def dfs(tree,nodes):
    for node in nodes:
        nexts = tree[node]
        for next,l in nexts.items():
            if l% 2 == 0 :
                ans[next] = ans[node]
            else:
                ans[next] = 1 - ans[node]
        if len(ans) == N:
            return
        dfs(tree,nexts)

    return 0




if __name__ == "__main__":
    tree= {}
    N = int(input())
    for i in range(N-1):
        u,v,w = list(map(int,input().split(" ")))

        if u not in tree:
            tree[u] = {}
        tree[u][v] = w

        if v not in tree:
            tree[v] = {}
        tree[v][u] = w

    dfs(tree,[1])
    for i in range(1,N+1):
        print(ans[i])

Submission status: Runtime Error

Solution code:
import copy
N=int(input())
data=[[int(i) for i in input().split()] for _ in range(N-1)]
state = [-1 for _ in range(N+1)]
def search(depth,copyed_state):
    if depth==len(data):
        # print('end')
        return copyed_state
    kl = data[depth]
    anss=[]
    # print('depth:{} state:{}'.format(depth,copyed_state))
    if kl[2]%2 ==0:
        if copyed_state[kl[0]]==-1 and copyed_state[kl[1]]==-1:
            new_lizeros = copy.copy(copyed_state)
            new_lizeros[kl[0]] = 0
            new_lizeros[kl[1]] = 0
            anss.append(search(depth+1,new_lizeros))
            new_liones = copy.copy(copyed_state)
            new_liones[kl[0]] = 1
            new_liones[kl[1]] = 1
            anss.append(search(depth+1,new_liones))
        elif copyed_state[kl[0]]==0 and copyed_state[kl[1]]==-1:
            one_lizeros = copy.copy(copyed_state)
            one_lizeros[kl[1]] = 0
            anss.append(search(depth+1,one_lizeros))
        elif copyed_state[kl[0]]==1 and copyed_state[kl[1]]==-1:
            one_lizeros = copy.copy(copyed_state)
            one_lizeros[kl[1]] = 1
            anss.append(search(depth+1,one_lizeros))
        elif copyed_state[kl[0]]==-1 and copyed_state[kl[1]]==0:
            one_lizeros = copy.copy(copyed_state)
            one_lizeros[kl[0]] = 0
            anss.append(search(depth+1,one_lizeros))
        elif copyed_state[kl[0]]==-1 and copyed_state[kl[1]]==1:
            one_lizeros = copy.copy(copyed_state)
            one_lizeros[kl[0]] = 1
            anss.append(search(depth+1,one_lizeros))
    if copyed_state[kl[0]] == -1 and copyed_state[kl[1]] == -1:
        new_lizeros2 = copy.copy(copyed_state)
        new_lizeros2[kl[0]] = 0
        new_lizeros2[kl[1]] = 1
        anss.append(search(depth + 1, new_lizeros2))
        new_liones2 = copy.copy(copyed_state)
        new_liones2[kl[0]] = 1
        new_liones2[kl[1]] = 0
        anss.append(search(depth + 1, new_liones2))
    elif copyed_state[kl[0]] == 0 and copyed_state[kl[1]] == -1:
        one_lizeros2 = copy.copy(copyed_state)
        one_lizeros2[kl[1]] = 1
        anss.append(search(depth + 1, one_lizeros2))
    elif copyed_state[kl[0]] == 1 and copyed_state[kl[1]] == -1:
        one_lizeros2 = copy.copy(copyed_state)
        one_lizeros2[kl[1]] = 0
        anss.append(search(depth + 1, one_lizeros2))
    elif copyed_state[kl[0]] == -1 and copyed_state[kl[1]] == 0:
        one_lizeros2 = copy.copy(copyed_state)
        one_lizeros2[kl[0]] = 1
        anss.append(search(depth + 1, one_lizeros2))
    elif copyed_state[kl[0]] == -1 and copyed_state[kl[1]] == 1:
        one_lizeros2 = copy.copy(copyed_state)
        one_lizeros2[kl[0]] = 0
        anss.append(search(depth + 1, one_lizeros2))
    else: # dottimo haittetara
        sktyu = copy.copy(copyed_state)
        anss.append(search(depth + 1, sktyu))

    for i in anss:
        if len(i)!=0:
            return i
ans=search(0,state)
for i in range(1,N+1):
    print(ans[i])

Submission status: Runtime Error

Solution code:
import numpy as np
n = int(input())

u,v,w = [],[],[]
for k in range(n-1):
    uu, vv, ww =  list(map(int, input().split()))
    uuu = min([uu, vv])
    vvv = max([uu, vv])
    u.append(uu)
    v.append(vv)
    w.append(ww)

u = np.array(u)
v = np.array(v)
w = np.array(w)

same_ind = w%2 == 0
color = np.int32(np.zeros(n))


color = np.int32(np.zeros(n))
for k in range(n-1):
    if same_ind[k]:
        if color[v[k] - 1] == 0:
            color[v[k] - 1] = u[k]
        else:
            color[u[k] - 1] = v[k]
    else:
        if color[v[k] - 1] == 0:
            color[v[k] - 1] = -u[k]
        else:
            color[u[k] - 1] = -v[k]

def find(color, ind, original_ind = None, reverse = False):

    if original_ind is None:
        original_ind = ind
    if color[ind - 1] == 0:
        if ind != original_ind:
            if reverse:
                color[original_ind - 1] = -ind
            else:
                color[original_ind - 1] = ind
        return ind, reverse
    else:
        if color[ind - 1] > 0:
            return find(color, color[ind - 1], original_ind, reverse)
        else:
            return find(color, -color[ind - 1], original_ind, not reverse)

groups = []
for k in range(1, n+1):
    if k == 1:
        a, rf = find(color, k)
        print(0)
    else:
        b, r = find(color, k)
        if a == b and r == rf:
            print(0)
        elif a!= b and r!= rf:
            print(0)
        else:
            print(1)

Submission status: Runtime Error

Solution code:
import networkx as nx

G = nx.DiGraph()
for _ in range(int(input()) - 1):
    u, v, w = map(int, input().split())
    G.add_edge(u, v)
    G.edges[u, v]['dist'] = w
    if w % 2 == 0:
        if not 'color' in G.nodes[u].keys() and not 'color' in G.nodes[v].keys():
            G.nodes[u]['color'] = 0
            G.nodes[v]['color'] = 0
        elif not 'color' in G.nodes[u].keys():
            G.nodes[u]['color'] = G.nodes[v]['color']
        else:
            G.nodes[v]['color'] = G.nodes[u]['color']
    else:
        if not 'color' in G.nodes[u].keys() and not 'color' in G.nodes[v].keys():
            G.nodes[u]['color'] = 1
            G.nodes[v]['color'] = 0
        elif not 'color' in G.nodes[u].keys():
            G.nodes[u]['color'] = (G.nodes[v]['color'] + 1) % 2
        else:
            G.nodes[v]['color'] = (G.nodes[u]['color'] + 1) % 2

for i in G.nodes:
    print(G.nodes[i]['color'])

Submission status: Runtime Error

Solution code:
import numpy as np
import copy

N = int(input())

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

for _ in range(N - 1):
    u, v, w = list(map(int, input().split()))
    roots[v - 1] += [(u-1, w)]
    roots[u - 1] += [(v-1, w)]
    
def initialize():
    explored_list = np.zeros((N, 1))
    color_list = np.zeros((N, 1))
    return explored_list, color_list
  
explored_list, color_list = initialize()
stack = []
color_list[0] = 1

def is_move(vertex, stack, roots):
    target_root = roots[vertex]
    for root in target_root:
        if root[0] not in stack:
            return True
    return False
  
def check_color(a, b):
    if a == b:
        return True
    else:
        return False

def splatoon(vertex, stack, roots):
    global color_list
    
    stack.append(vertex)
    
    #Recursive end
    if not is_move(vertex, stack, roots):
        return 0
    
    #Recursive
    target_root = roots[vertex]
    for root in target_root:
        if root[0] not in stack:
            if root[1] % 2 == 0:
                if not check_color(color_list[vertex], color_list[root[0]]):
                    color_list[root[0]] = color_list[vertex]
            splatoon(root[0], copy.copy(stack), roots)
            
splatoon(0, stack, roots)

for i in color_list:
    print(int(i))

Submission status: Runtime Error

Solution code:
N = int(input())
        
G = [[] for i in range(N)]
for _ in range(N - 1):
    a, b, c = map(int, input().split())
    G[a - 1].append([b - 1, c])
    G[b - 1].append([a - 1, c])
    
color = [0] * N

def dfs(v, c):
    if color[v] == 0:
        color[v] = c
    for i in range(len(G[v])):
        if color[G[v][i][0]] == 0:
            if G[v][i][1] % 2 == 0:
                dfs(G[v][i][0], color[v])
            else:
                dfs(G[v][i][0] , -color[v])
                
for i in range(N):
    dfs(i, 1)
    # print(color)
    
for i in range(N):
    if color[i] == 1:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
n = int(input())
d = [[] for i in range(n)]
for i in range(n-1):
	a,b,x = map(int,input().split())
	a -= 1
	b -= 1
	x = x%2
	d[a].append([b,x])
	d[b].append([a,x])
color = [0]*n
used = set()
def dfs(v):
	for e,l in d[v]:
		if e not in used:
			used.add(e)
			if l == 1:
				color[e] = 1
			dfs(e)
dfs(0)
for c in color:
	print(c)

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
S = []
kisyutu = []
cnt = 0
for i in range(m):
    aa = list(input().split())
    S.append(aa)
#print(S)
for j in S:
    if j[0] not in kisyutu and j[1] not in kisyutu:
        kisyutu.append(j[0])
        kisyutu.append(j[1])
        cnt += 1
    if j[0] in kisyutu and j[1] not in kisyutu:
        kisyutu.append(j[1])
        cnt += 1
    if j[0] not in kisyutu and j[1] in kisyutu:
        kisyutu.append(j[0])
        cnt += 1
print(n-cnt)

Submission status: Runtime Error

Solution code:
N = int(input())

dist = []
ans = [-1*N]
for i in range(N-1):
  u, v, w = map(int,input().split())
  print(u)
  dist.append([u,v,w])
  
dist.sort()

#  0: white
#  1: black
# -1: unknown
#  a: is same color as ans[a-1]
# -a: is diff color as ans[a-1]

ans[0] = 0
for i in range(N:1):
  u, v, w = dist[i]
  if(ans[u-1] != -1):
    if(w%2 == 0):
        ans[v-1] = ans[u-1]
    else:
      if(ans[u-1] == 0):
        ans[v-1] = 1
      else if (ans[u-1] == 1):
        ans[v-1] = 0
      else:
        ans[v-1] = -ans[u-1]
  else if(ans[v-1] != -1):
    if(w%2 == 0):
        ans[u-1] = ans[v-1]
    else:
      if(ans[v-1] == 0):
        ans[u-1] = 1
      else if (ans[v-1] == 1):
        ans[u-1] = 0
      else:
        ans[u-1] = -ans[v-1]
  else:
    if(w%2 == 0):
      ans[u-1] = i
      ans[v-1] = i
    else:
      ans[u-1] = i
      ans[v-1] = -i
      
for i in range(N):
  print(ans[i])

Submission status: Runtime Error

Solution code:
N = int(input())

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


tree = {}
for i in inputs:
	if i[0] in tree:
		tree[i[0]].append({'to': i[1], 'w': i[2]})
	else:
		tree[i[0]] = [{'to': i[1], 'w': i[2]}]

	if i[1] in tree:
		tree[i[1]].append({'to': i[0], 'w': i[2]})
	else:
		tree[i[1]] = [{'to': i[0], 'w': i[2]}]

# tree = {2: [{'to': 5, 'w': 3}, {'to': 3, 'w': 10}], 5: [{'to': 2, 'w': 3}, {'to': 6, 'w': 2}], 6: [{'to': 5, 'w': 2}], 3: [{'to': 2, 'w': 10}, {'to': 1, 'w': 3}, {'to': 4, 'w': 3}], 1: [{'to': 3, 'w': 3}], 4: [{'to': 3, 'w': 3}]}
# result = [-1] * N

def reverse(i):
	if i == 0:
		return 1
	if i == 1:
		return 0

for n in range(1, N + 1):
	for leaf in tree[n]:
		if leaf['w'] % 2 != 0:
			if result[n - 1] == -1:
				result[n - 1] = 0

			result[leaf['to'] - 1] = reverse(result[n - 1])

		if leaf['w'] % 2 == 0:
			result[leaf['to'] - 1] = result[n - 1]

for r in result:
	print(r)

Submission status: Runtime Error

Solution code:
import numpy as np

N, K = map(int, input().split())

def get_x(n, K):
    if n >= K:
        return 0
    else:
        x_raw = np.log2(K) - np.log2(n)
        return np.ceil(x_raw)

def get_prob_inv(n, K):
    x = get_x(n, K)
    if x == 0:
        return 1
    else:
        return (1/2)**x
    
x_alls = [get_x(n, K) for n in range(1, N+1)]
x_max = np.max(x_alls)
x_sum = np.sum(x_alls)
x_minus_x_max = x_sum - x_max
x_denos = [x_sum - x - x_minus_x_max for x in x_alls]
x_nume = x_max

ans = np.sum([2 ** x for x in x_denos])
ans = np.divide(ans, 2**x_max * N, dtype=np.float64)


# ans = np.sum([get_prob(n, K) for n in range(1, N+1)], dtype=np.float64)

print('{0:.12f}'.format(ans))

Submission status: Runtime Error

Solution code:
import numpy as np

n=int(input())
E=[]
W=[]
node_l=np.zeros(n)
node_l[0]=1
for i in range(n-1):
    u,v,w=map(int,input().split())
    #print(u,v,w)
    E.append([u,v])
    W.append(w)
#print(E,W)

def bfs(node,node_l,l,w_l):
    i=0
    A=[]
    L=[]
    for edge in l:
        if edge[0]==node:
            L.append(edge[1])
            A.append(i)
        elif edge[1]==node:
            L.append(edge[0])
            A.append(i)
        i+=1
    if L==[]:
        return
    for j in range(len(L)):
        if node_l[L[j]-1]==0:
                if W[A[j]]%2==0:
                    node_l[L[j]-1]=node_l[node-1]
                    bfs(L[j],node_l,l,w_l)
                else:
                    node_l[L[j]-1]=node_l[node-1]*-1
                    bfs(edge[0],node_l,l,w_l)
    return
bfs(1,node_l,E,W)
for i in range(n):
    if node_l[i]==1:
        print('1',end='\n')
    else:
        print('0',end='\n')

Submission status: Runtime Error

Solution code:
N = int(input())
e = [[] for _ in range(2*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(2*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:N+1]:
    print(c)

Submission status: Runtime Error

Solution code:
nnn = int(input())

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

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


def oon(x,n,nn,k):
	global a
	for i in range(len(x[n])):
		if x[n][i][0] != nn and a[nn] != -2:
			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:
				a[x[n][i][0]] = 1
				oon(x,x[n][i][0],n,p)
		else:
			continue



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:
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
if n>1:
	dfs(1)
for i in range(1,n+1):
    if y[i]%2==0:
        print(0)
    else:
        print(1)

Submission status: Runtime Error

Solution code:
import pandas as pd

N = int(input())

u = [0] * (N-1)
v = [0] * (N-1)
w = [0] * (N-1)
ans = [0] * N

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

df = pd.DataFrame({'u': u, 'v': v, 'w': w})
df_sorted = df.sort_values(['u', 'v'])

u = df_sorted['u'].values
v = df_sorted['v'].values
w = df_sorted['w'].values

for i in range(N-1):
    if w[u[i]-1] % 2 == 1:
        if ans[u[i]-1] == 0:
            ans[v[i]-1] = 1
        if ans[u[i]-1] == 1:
            ans[v[i]-1] = 0

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

Submission status: Runtime Error

Solution code:
N = int(input())

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


tree = {}
for i in inputs:
	if i[0] in tree:
		tree[i[0]].append({'to': i[1], 'w': i[2]})
	else:
		tree[i[0]] = [{'to': i[1], 'w': i[2]}]

	if i[1] in tree:
		tree[i[1]].append({'to': i[0], 'w': i[2]})
	else:
		tree[i[1]] = [{'to': i[0], 'w': i[2]}]

N = 6
# tree = {2: [{'to': 5, 'w': 3}, {'to': 3, 'w': 10}], 5: [{'to': 2, 'w': 3}, {'to': 6, 'w': 2}], 6: [{'to': 5, 'w': 2}], 3: [{'to': 2, 'w': 10}, {'to': 1, 'w': 3}, {'to': 4, 'w': 3}], 1: [{'to': 3, 'w': 3}], 4: [{'to': 3, 'w': 3}]}
# result = [-1] * N

def reverse(i):
	if i == 0:
		return 1
	if i == 1:
		return 0

for n in range(1, N + 1):
	for leaf in tree[n]:
		if leaf['w'] % 2 != 0:
			if result[n - 1] == -1:
				result[n - 1] = 0

			result[leaf['to'] - 1] = reverse(result[n - 1])

		if leaf['w'] % 2 == 0:
			result[leaf['to'] - 1] = result[n - 1]

for r in result:
	print(r)

Submission status: Runtime Error

Solution code:
n = int(input())
d = [[] for i in range(n)]
for i in range(n-1):
	a,b,x = map(int,input().split())
	a -= 1
	b -= 1
	x = x%2
	d[a].append([b,x])
	d[b].append([a,x])
print(d)
color = [0]*n
used = set()
def dfs(v):
	for e,l in d[v]:
		#print(e)
		if e not in used:
			used.add(e)
			if l == 1:
				color[e] = 1
			dfs(e)
dfs(0)
for c in color:
	print(c)

Submission status: Runtime Error

Solution code:
N =int(raw_input())
A = []
for i in range(N-1):
    a,b,d=map(int ,raw_input().split())
    if d%2 ==1:
        A.append((a,b))
#print A
#print A.pop()
#print A

D =[]
for i in range(N):
    D.append(-1)

for i in A:
    a = A.pop()
    if D[a[0]]==-1 and D[a[1]]==-1:
        D[a[0]]==1 
        D[a[1]]==0
    elif D[a[0]]==-1:
        D[a[0]]==1-D[a[1]]
    elif D[a[1]]==-1:
        D[a[1]]==1-D[a[0]]
for i in range(N):
    if D[i]==-1:
        D[i] = 0

for i in D:
    print 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:
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 = []

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

uvw = sorted(uvw)
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:
N = int(input())

BLACK = -1
GRAY = 0
WHITE = 1
nodes = [GRAY] * N
nodes[0] = BLACK
neighbors = [[] for _ in range(N)]

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


def dfs(u):
    neiss = neighbors[u]
    for neis in neiss:
        v, w = neis
        if nodes[v] == GRAY:
            if w % 2 == 0:
                nodes[v] = nodes[u]
            else:
                nodes[v] = -nodes[u]
            dfs(v)


dfs(0)

for n in nodes:
    if n == BLACK:
        print(0)
    else:
        print(1)

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()
    d = [[] for _ in range(N)]
    #uvw = ii2nnn(N-1)
    #for u, v, w in uvw:
    for _ in range(N-1):
        u, v, w = i2nn()
        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()