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: Time Limit Exceeded

Solution code:
N = int(input())                                         # N:ノード数、M:エッジ数
visited = [False for i in range(N)]                                     # ノードの訪問済みフラグ
graph = [[0 for i in range(N)] for j in range(N)]                   # 接続行列の入れ物
# 重み0=エッジなし
colors = [0 for i in range(N)]

# 各エッジについて、情報を接続行列に埋め込む
for i in range(N-1):
  u, v, w = map(int,input().split())
  graph[u-1][v-1] = w
  graph[v-1][u-1] = w

def dfs(v):
  queue = [v]
  while len(queue) != 0:
    now = queue.pop()
    visited[now] = True
    for next in range(N):
      if graph[now][next] == 0:continue
      if visited[next] == True:continue
      if graph[now][next]%2:
        colors[next] = 1-colors[now]
      else:
        colors[next] = colors[now]

      queue.append(next)
      
dfs(0)
for i in range(N):
  print(colors[i])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())                                         # N:ノード数、M:エッジ数
visited = [False for i in range(N)]                                     # ノードの訪問済みフラグ
graph = [[0 for i in range(N)] for j in range(N)]                   # 接続行列の入れ物
# 重み0=エッジなし
colors = [0 for i in range(N)]

# 各エッジについて、情報を接続行列に埋め込む
for i in range(N-1):
  u, v, w = map(int,input().split())
  graph[u-1][v-1] = w
  graph[v-1][u-1] = w

def bfs(v):
  queue = [v]
  while len(queue) != 0:
    now = queue.pop(0)
    visited[now] = True
    for next in range(N):
      if graph[now][next] == 0:continue
      if visited[next] == True:continue
      if graph[now][next]%2:
        colors[next] = 1-colors[now]
      else:
        colors[next] = colors[now]

      queue.append(next)
      
bfs(0)
for i in range(N):
  print(colors[i])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
tree = [list() for _ in range(N)]
for _ in range(N-1):
    u, v, w = map(int, input().split())
    tree[u-1].append((v-1, w))
    tree[v-1].append((u-1, w))
stack = [0]
ans = [0] * N
searched = [False] * N
while stack:
    node = stack.pop()
    for v, w in tree[node]:
        if not searched[v]:
            searched[v] = True
            if w % 2 != 0:
                ans[v] = ans[node] ^ 1
            else:
                ans[v] = ans[node]
        stack.append(v)
print(*ans, sep='\n')

Submission status: Time Limit Exceeded

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

N = int(input())
edges = [[] for _ in range(N+1)]
for _ in range(N-1):
    u, v, w = map(int, input().split())
    edges[u].append([v, w])
    edges[v].append([u, w])
parent = [[] for _ in range(N)]
ans = [0 for _ in range(N)]


def dfs(edge, pd):
    for child, d in edges[edge]:
        if edge in parent[child-1]:
            continue
        cd = pd + d
        if cd % 2 == 0:
            ans[child-1] = 0
        else:
            ans[child-1] = 1
        parent[child-1].append(edge)
        dfs(child, cd)


def solve():
    dfs(1, 0)
    for i in range(N):
        print(ans[i])


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
Glaph=[[0 for i in range(N)] for i in range(N)]
ans=[0 for i in range(N)]

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

flag=[0 for i in range(N)]
def dfs(s,dist):
  flag[s]=1
  if dist%2==0:
    ans[s]=1
  
  for i in range(N):
    if Glaph[s][i]!=0  and flag[i]==0:    
      dfs(i,dist+Glaph[s][i])
  return 1

dfs(0,0)

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    d = {}
    for _ in range(N-1):
        u, v, w = map(int, input().split())
        w %= 2
        if u in d:
            d[u].append((v, w))
        else:
            d[u] = [(v,w)]
        if v in d:
            d[v].append((u, w))
        else:
            d[v] = [(u,w)]
    cur = [1]
    nextp = []
    l = [0] * N
    v = set([1])
    while v != set(range(1,N+1)):
        for i in cur:
            for j, k in d[i]:
                if j not in v:
                    if k:
                        l[j-1] = 1 - l[i-1]
                    else:
                        l[j-1] = l[i-1]
                    v.add(j)
                    nextp.append(j)
        cur = nextp
        nextp = []
    return l
l = main()
for i in l:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
a=[set() for v in range(N+1)]
d=[[-1 for v in range(N+1)] for u in range(N+1)]
for e in range(1,N):
    u,v,w=map(int,input().split())
    a[u].add(v);a[v].add(u)
    d[u][v]=d[v][u]=w

#c=[None for v in range(N+1)] # color
d1=[None for v in range(N+1)] # distance from 1

# print(a)
# print(d)

q=deque()
q.append(1);d1[1]=0
while q:
    u=q.popleft()
    for v in a[u]:
        if d1[v] is None:
            d1[v]=d1[u]+d[u][v]
            q.append(v)

# print(d1)
for d1i in d1[1:]:
    print(d1i%2)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

#c=[None for v in range(N+1)] # color
d1=[None for v in range(N+1)] # distance from 1

# print(a)
# print(d)

q=deque()
q.append(1);d1[1]=0
while q:
    u=q.popleft()
    for v in a[u]:
        if d1[v] is None:
            d1[v]=d1[u]+d[u][v]
            q.append(v)

# print(d1)
for d1i in d1[1:]:
    print(d1i%2)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

c=[None for v in range(N+1)] # color

# print(a)
# print(d)

q=deque()
q.append(1);c[1]=True #;d1[1]=0 
while q:
    u=q.popleft()
    for v in a[u]:
        if c[v] is None:
            c[v]=c[u] if d[u][v]%2==0 else not c[u]
            q.append(v)

for ci in c[1:]:
    print(1 if ci else 0)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
A=[[-1 for i in range(N+1)] for j in range(N+1)]
B=[[] for i in range(N+1)]
for i in range(N-1):
  u,v,w=map(int,input().split())
  A[u][v]=A[v][u]=w
  B[u].append(v)
  B[v].append(u)
#print(A)
#print(B)

check=[-1]*(N+1)
check[1]=0
D = deque()
D.append(1)

while D:
  d=D.popleft()
  for b in B[d]:
    if check[b]==-1:
      D.append(b)
      check[b]=(check[d]+A[d][b])%2

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque

class Node:

    def __init__(self, id, parent_id=None):
        self.id = id
        self.parent_id = parent_id
        self.distance = 0 

def distance_between(id1, id2):
    return distance_dict[(id1, id2)]


N = int(input())

distance_dict = {}
adj_dict = defaultdict(list)
for i in range(N-1):
    ui, vi, wi = map(int, input().split())
    distance_dict[(ui, vi)] = wi
    distance_dict[(vi, ui)] = wi
    adj_dict[ui].append(vi)
    adj_dict[vi].append(ui)

id_to_node = {}
cur_node = Node(id=2)
id_to_node[cur_node.id] = cur_node
open_list = deque()
open_list.append(cur_node)
closed_list = []
while True:
    if len(open_list) == 0:
        break
    cur_node = open_list.pop()
    closed_list.append(cur_node.id)
    adj_id_list = adj_dict[cur_node.id]
    for adj_id in adj_id_list:
        if adj_id in closed_list: 
            continue
        adj_node = Node(id=adj_id, parent_id=cur_node.id)
        adj_node.distance = distance_between(cur_node.id, adj_node.id)+cur_node.distance
        id_to_node[adj_id] = adj_node
        open_list.append(adj_node)

for id in range(1, N+1):
    if id_to_node[id].distance%2==0:
        print(0)
    else:
        print(1)

Submission status: Time Limit Exceeded

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

#print(Tree)
queue = [0]
Color=dict()
Color[0] = '0'

while queue:
    if len(Color) == N:
        break
    value = queue.pop(0)
    for i in range(N):
        if Tree[value][i] == 0 or i == value: continue
        if i in Color:
            continue
        if Tree[value][i] % 2 == 0:
            queue.append(i)
            Color[i] = Color[value]
        else:
            queue.append(i)
            Color[i] = '1' if Color[value] == '0' else '0'
for i in range(N):
    print(Color[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
vertexes=[[] for i in range(N)]
edges=[[int(s) for s in input().split()] for i in range(N-1)]
#頂点ごとに、頂点から伸びる辺のデータを記録
for e in edges:
  vertexes[e[0]-1].append([e[1]-1,e[2]])
  vertexes[e[1]-1].append([e[0]-1,e[2]])

#幅優先探索の開始（v_possibleに入った順に頂点を訪れる）
answer=[-1 for i in range(N)]  #到達していない頂点は-1
answer[0]=0
v_possible=[] #到達可能な頂点と、辺の情報
v=0 #現在の位置
for i in range(N-1):
  for e in vertexes[v]: #行き先の更新
    if answer[e[0]]==-1: #未到達ならv_possibleに追加
      v_possible.append([e[0],v,e[1]]) #[行き先,つながる頂点,距離] 
  v2=v_possible[0] #v_possibleの最初の頂点に移動
  answer[v2[0]]=(answer[v2[1]]+v2[2])%2
  v=v2[0]
  del v_possible[0]
  
#答を出力
for i in range(N):
  print(answer[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
vertexes=[[] for i in range(N)]
edges=[[int(s) for s in input().split()] for i in range(N-1)]
#頂点ごとに、頂点から伸びる辺のデータを記録
for e in edges:
  vertexes[e[0]-1].append([e[1]-1,e[2]])
  vertexes[e[1]-1].append([e[0]-1,e[2]])

#幅優先探索の開始（v_possibleに入った順に頂点を訪れる）
answer=[-1 for i in range(N)]  #到達していない頂点は-1
answer[0]=0
v_possible=[] #到達可能な頂点と、辺の情報
v=0 #現在の位置
for i in range(N-1):
  for e in vertexes[v]: #行き先の更新
    v_possible.append([e[0],v,e[1]]) #[行き先,つながる頂点,距離]
  Len=len(v_possible)
  x=0
  for k in range(Len):
    vx=v_possible[k-x]
    if answer[vx[0]]==-1: #まだ訪れていないなら移動
      answer[vx[0]]=(answer[vx[1]]+vx[2])%2
      v=vx[0]
      break
    else: #すでに訪れたなら、その情報は消す
      del v_possible[k-x]
      x+=1

#答を出力
for i in range(N):
  print(answer[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
vertexes=[[] for i in range(N)]
edges=[[int(s) for s in input().split()] for i in range(N-1)]
#頂点ごとに、頂点から伸びる辺のデータを記録
for e in edges:
  vertexes[e[0]-1].append([e[1]-1,e[2]])
  vertexes[e[1]-1].append([e[0]-1,e[2]])

#幅優先探索の開始（v_possibleに入った順に頂点を訪れる）
answer=[-1 for i in range(N)]  #到達していない頂点は-1
answer[0]=0
v_possible=[] #到達可能な頂点と、辺の情報
v=0 #現在の位置
for i in range(N-1):
  for e in vertexes[v]: #行き先の更新
    v_possible.append([e[0],v,e[1]]) #[行き先,つながる頂点,距離]
  for j in v_possible:
    if answer[j[0]]==-1: #まだ訪れていないなら移動
      answer[j[0]]=(answer[j[1]]+j[2])%2
      v=j[0]
      break

#答を出力
for i in range(N):
  print(answer[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
UVW=[list(map(int,input().split())) for i in range(N-1)]
UVW.sort(key=lambda x:x[1])
UVW.sort()
L=[-1]*(N+1)
L[1]=0

while -1 in L[1:]:
    for i in range(N-1):
        if L[UVW[i][0]]==0:
            if UVW[i][2]%2==0:
                L[UVW[i][1]]=0
            else:
                L[UVW[i][1]]=1
        elif L[UVW[i][0]]==1:
            if UVW[i][2]%2==0:
                L[UVW[i][1]]=1
            else:
                L[UVW[i][1]]=0
        else:
            if L[UVW[i][1]]==0:
                if UVW[i][2]%2==0:
                    L[UVW[i][0]]=0
                else:
                    L[UVW[i][0]]=1
            elif L[UVW[i][1]]==1:
                if UVW[i][2]%2==0:
                    L[UVW[i][0]]=1
                else:
                    L[UVW[i][0]]=0

L.pop(0)
for i in L:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import heapq as hp
N = int(input())
d = [-1]*N
arr = []
for i in range(N-1):
    u,v,w = map(int,input().split())
    u -= 1
    v -= 1
    arr.append([u,v,w])
e_list = [set() for i in range(N)]
e_graph = [[0]*N for i in range(N)]
for u,v,w in arr:
    e_list[u].add(v)
    e_list[v].add(u)
    e_graph[u][v] = w
    e_graph[v][u] = w

stack = [[0,0]]
d[0] = 0
for w in range(N):
    if stack == []:
        break
    cost,cur_pos = hp.heappop(stack)
    cost *= -1
    for des in e_list[cur_pos]:
        if d[des] < 0:
            d[des] = d[cur_pos] + e_graph[cur_pos][des]
            hp.heappush(stack,[-d[des],des])

for i in d:
    print(i%2)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
ans = [-1]*N
arr = []
for i in range(N-1):
    u,v,w = map(int,input().split())
    u -= 1
    v -= 1
    arr.append([u,v,w])
e_list = [set() for i in range(N)]
e_graph = [[0]*N for i in range(N)]
for u,v,w in arr:
    e_list[u].add(v)
    e_list[v].add(u)
    e_graph[u][v] = w
    e_graph[v][u] = w

stack = [0]
ans[0] = 0
for rnd in range(N):
    if stack == []:
        break
    cur_pos = stack.pop()
    for des in e_list[cur_pos]:
        if ans[des] < 0:
            if e_graph[cur_pos][des] %2 == 0:
                ans[des] = ans[cur_pos]
            else:
                ans[des] = (ans[cur_pos] + 1)%2
            e_list[des].remove(cur_pos)
            stack.append(des)
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
ans = [-1]*N
arr = []
for i in range(N-1):
    u,v,w = map(int,input().split())
    u -= 1
    v -= 1
    arr.append([u,v,w])
e_list = [[] for i in range(N)]
e_graph = [[0]*N for i in range(N)]
for u,v,w in arr:
    e_list[u].append(v)
    e_list[v].append(u)
    e_graph[u][v] = w
    e_graph[v][u] = w

stack = [0]
ans[0] = 0
while (stack):
    cur_pos = stack.pop()
    for des in e_list[cur_pos]:
        t = ans[des]
        if ans[des] < 0:
            if e_graph[cur_pos][des] %2 == 0:
                ans[des] = ans[cur_pos]
            else:
                ans[des] = (ans[cur_pos] + 1)%2
            stack.append(des)
for i in ans:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
c=[[] for i in range(n+1)]
d=[[float("inf")]*(n+1) for i in range(n+1)]
for i in range(n-1):
    x,y,z=map(int,input().split())
    c[x].append(y)
    c[y].append(x)
    d[x][y]=z%2
    d[y][x]=z%2
stack=[1]
color=[-1]*(n+1)
color[1]=0
parent=[None]*(n+1)
append=stack.append
while stack:
    i=stack.pop()
    for j in c[i]:
        if j==parent[i]:
            continue
        color[j]=(color[i]+d[i][j])%2
        parent[j]=i
        append(j)
print("\n".join(map(str,color[1:])))

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra
N = int(input())
d = [0]*N
route = [[10**9]*N for i in range(N)]
for i in range(N-1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    route[u][v] = w
    route[v][u] = w
    d[u] += 1
    d[v] += 1

g = csgraph_from_dense(route, null_value=10**9)

G = dijkstra(g)
d = d.index(max(d))


ans = [0]*N

for i in range(N):
    if i == d:
        continue
    if G[d][i] % 2 != 0:
        ans[i] = 1
for i in range(N):
    print(ans[i])

Submission status: Time Limit Exceeded

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

from collections import deque

n = int(input())
uvw = [list(map(int, input().split())) for _ in range(n-1)]
 
graph = [[] for _ in range(n)]
for i in range(n-1):
    graph[uvw[i][0]-1].append((uvw[i][1]-1, uvw[i][2]))
    graph[uvw[i][1]-1].append((uvw[i][0]-1, uvw[i][2]))
 
stack = deque([0])
visited = []
ans = [0]*n
while stack:
    node = stack.popleft()
    visited.append(node)
    for child in graph[node]:
        if child[0] in visited:
            continue
        
        stack.append(child[0])
        if child[1]%2 == 0:
            ans[child[0]] = ans[node]
        else:
            ans[child[0]] = (ans[node]+1)%2
 
[print(ans[i]) for i in range(n)]

Submission status: Time Limit Exceeded

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

from collections import deque

n = int(input())
uvw = [list(map(int, input().split())) for _ in range(n-1)]
 
graph = [[] for _ in range(n)]
for i in range(n-1):
    graph[uvw[i][0]-1].append((uvw[i][1]-1, uvw[i][2]))
    graph[uvw[i][1]-1].append((uvw[i][0]-1, uvw[i][2]))
 
stack = deque([0])
visited = []
ans = [0]*n
while stack:
    node = stack.pop()
    visited.append(node)
    for child in graph[node]:
        if child[0] in visited:
            continue
        
        stack.append(child[0])
        if child[1]%2 == 0:
            ans[child[0]] = ans[node]
        else:
            ans[child[0]] = (ans[node]+1)%2
 
[print(ans[i]) for i in range(n)]

Submission status: Time Limit Exceeded

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

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

graph = [[] for _ in range(n)]
for i in range(n-1):
    graph[uvw[i][0]-1].append((uvw[i][1]-1, uvw[i][2]))
    graph[uvw[i][1]-1].append((uvw[i][0]-1, uvw[i][2]))

stack = [0]
visited = []
ans = [0]*n
while stack:
    node = stack.pop()
    visited.append(node)
    for child in graph[node]:
        if child[0] in visited:
            continue
        
        stack.append(child[0])
        if child[1]%2 == 0:
            ans[child[0]] = ans[node]
        else:
            ans[child[0]] = (ans[node]+1)%2

[print(ans[i]) for i in range(n)]

Submission status: Time Limit Exceeded

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

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

graph = [[] for _ in range(n)]
for i in range(n-1):
    graph[uvw[i][0]-1].append((uvw[i][1]-1, uvw[i][2]))
    graph[uvw[i][1]-1].append((uvw[i][0]-1, uvw[i][2]))

stack = [0]
visited = []
ans = [0]*n
while stack:
    node = stack.pop()
    visited.append(node)
    for child in graph[node]:
        if child[0] not in visited:
            stack.append(child[0])
            if child[1]%2 == 0:
                ans[child[0]] = ans[node]
            else:
                ans[child[0]] = (ans[node]+1)%2

[print(ans[i]) for i in range(n)]

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
dis=[10**15]*n
dis[0]=0
pair=[[]for _ in range(n)]
for i in range(n-1):
	a,b,c=map(int,input().split())
	pair[a-1].append([b-1,c])
	pair[b-1].append([a-1,c])
now=0
stack=set()
cnt=n-1
while cnt!=0:
	for i in range(len(pair[now])):
		if dis[pair[now][i][0]]==10**15:
			dis[pair[now][i][0]]=dis[now]+pair[now][i][1]
			stack.add(pair[now][i][0])
	now=list(stack)[0]
	stack=set(stack)
	stack.remove(now)
	cnt-=1
for i in range(n):
	if dis[i]%2==0:
		print(0)
	else:
		print(1)

Submission status: Time Limit Exceeded

Solution code:
#D
from collections import deque
N = int(input())
UVW = [list(map(int,input().split())) for i in range(N-1)]
UVW.sort()
UVW = deque(UVW)
inf = float("inf")
dist = [inf for i in range(N)] #頂点1からの距離
dist[0] = 0
while UVW:
    uvw = UVW.popleft()
    u,v,w = uvw
    if dist[u-1] == dist[v-1] == inf:
        UVW.append(uvw)
    else:
        if dist[u-1] != inf and dist[v-1] == inf:
            dist[v-1] = dist[u-1]+w
        elif dist[u-1] == inf and dist[v-1] != inf:
            dist[u-1] = dist[v-1]+w
        else:
            dist[v-1] = min(dist[v-1],dist[u-1]+w)
            
for d in dist:
    print(d%2)

Submission status: Time Limit Exceeded

Solution code:
#D
import heapq
inf = float("inf")
N = int(input())
UVW = [list(map(int,input().split())) for i in range(N-1)]
cost = [[inf for i in range(N)] for j in range(N)]
for i in range(N):
    cost[i][i] = 0
    
for uvw in UVW:
    u,v,w = uvw
    cost[u-1][v-1] = w
    cost[v-1][u-1] = w

#dijkstra
def dijkstra(s):
    global cost
    dist = [inf for i in range(N)]
    dist[s] = 0
    P = []
    heapq.heappush(P,[0,s])
    while P:
        p = heapq.heappop(P)
        f = p[0]
        v = p[1]
        if dist[v] < f:
            continue
        
        for i in range(N):
            e = cost[v][i]
            if e != inf and dist[i] > dist[v] + e:
                dist[i] = dist[v]+e
                heapq.heappush(P,[dist[i],i])
                
    return dist

dist = dijkstra(0)
for d in dist:
    print(d%2)

Submission status: Time Limit Exceeded

Solution code:
#%%
import sys
def input():
    return sys.stdin.readline().rstrip()


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

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

    def dfs(p, n, even):
        for i in range(N):
            if i != p and M[n][i] != 0:
                if M[n][i]%2 != 0:
                    ans[i] = not even
                else:
                    ans[i] = even
                dfs(n, i, ans[i])

    for u, v, w in UVW:
        M[u-1][v-1] = w
        M[v-1][u-1] = w

    ans=[True for _ in range(N)]
    dfs(0, 0, True)

    for i in range(N):
        if ans[i]:
            print(0)
        else:
            print(1)


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

# %%
# from atcoder_test import doTest
# doTest("abc126","d",main)

Submission status: Time Limit Exceeded

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

MOD = 10 ** 9 + 7

n = int(input())

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

dist = [-1] * n
dist[0] = 0
que = [0]
while len(que) != 0:
    i = que.pop()
    for j in range(n):
        if dist[j] == -1 and graph[i][j] != -1:
            dist[j] = dist[i] + graph[i][j]
            que.append(j)

for d in dist:
    print(d % 2)

Submission status: Time Limit Exceeded

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

MOD = 10 ** 9 + 7

n = int(input())

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

root = 0
dist = [-1] * (n)
new = {0}
not_yet = set(list(range(n)))
not_yet -= {0}
while len(new) != 0:
    next_new = set()
    for i in new:
        for j in not_yet:
            if graph[i][j] != -1:
                dist[j] = dist[i] + graph[i][j]
                next_new.add(j)
    not_yet -= next_new
    new = next_new

for d in dist:
    print(d % 2)

Submission status: Time Limit Exceeded

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

MOD = 10 ** 9 + 7

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

graph = [[-1] * n for _ in range(n)]
for u, v, w in uvw_n:
    graph[u - 1][v - 1] = w
    graph[v - 1][u - 1] = w

root = 0
dist = [-1] * (n)
new = {0}
not_yet = set(list(range(n)))
not_yet -= {0}
while len(new) != 0:
    next_new = set()
    for i in new:
        for j in not_yet:
            if graph[i][j] != -1:
                dist[j] = dist[i] + graph[i][j]
                next_new.add(j)
    not_yet -= next_new
    new = next_new

for d in dist:
    print(d % 2)

Submission status: Time Limit Exceeded

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

MOD = 10 ** 9 + 7

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

graph = [[-1] * n for _ in range(n)]
for u, v, w in uvw_n:
    graph[u - 1][v - 1] = w
    graph[v - 1][u - 1] = w

# print(graph)

root = 0
dist = [-1] * (n)
new = {0}
while len(new) != 0:
    next_new = set()
    for i in new:
        for j in range(n):
            if dist[j] == -1 and graph[i][j] != -1:
                dist[j] = dist[i] + graph[i][j]
                next_new.add(j)
    # print(next_new)
    new = next_new

for d in dist:
    print(d % 2)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.buffer.readline
    N = int(input())
    G = [[] for _ in range(N+1)]
    st = 0
    st_w = 0
    for i in range(N-1):
        u, v, w = (int(i) for i in input().split())
        G[u].append((v, w))
        G[v].append((u, w))
        if i == 0:
            st = u
            st_w = w
    color = [-1] * (N+1)  # 1: 0: white, black, -1: undefined

    def coloring(v, w):
        todo = []
        cur = 0
        color[v] = cur
        todo.append((v, w))
        while todo:
            u, w = todo[-1]
            for next_v, d in G[u]:
                if color[next_v] != -1:
                    continue
                if d % 2 != 0:
                    cur = (cur + 1) % 2
                color[next_v] = cur
                todo.append((next_v, d))
                break
            else:
                _, dist = todo.pop()
                if dist % 2 != 0:
                    cur = (cur + 1) % 2

    coloring(st, st_w)
    for c in color[1:]:
        print(c)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    G = [[] for _ in range(N+1)]
    st = 0
    st_w = 0
    for i in range(N-1):
        u, v, w = (int(i) for i in input().split())
        G[u].append((v, w))
        G[v].append((u, w))
        if i == 0:
            st = u
            st_w = w
    color = [-1] * (N+1)  # 1: 0: white, black, -1: undefined

    def coloring(v, w):
        todo = []
        cur = 0
        color[v] = cur
        todo.append((v, w))
        while todo:
            u, w = todo[-1]
            for next_v, d in G[u]:
                if color[next_v] != -1:
                    continue
                if d % 2 != 0:
                    cur = (cur + 1) % 2
                color[next_v] = cur
                todo.append((next_v, d))
                break
            else:
                _, dist = todo.pop()
                if dist % 2 != 0:
                    cur = (cur + 1) % 2

    coloring(st, st_w)
    for c in color[1:]:
        print(c)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def dfs(i, _d):
    dd[i] = _d
    for c in e[i]:
        if dd[c]!=-1: continue
        dfs(c, _d+d[i][c])

dfs(0,0)
for _dd in dd:
    print(_dd%2)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import sys
input = sys.stdin.readline

N = int(input())
INF = float('inf')
graph = [[INF] * N for _ in range(N)]

for i in range(N):
    graph[i][i] = 0

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

distance = floyd_warshall(graph, directed=False)

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

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import sys
input = sys.stdin.readline

N = int(input())
INF = float('inf')
graph = [[INF] * N for _ in range(N)]

for i in range(N):
    graph[i][i] = 0

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

distance = floyd_warshall(graph, directed=False)

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

Submission status: Time Limit Exceeded

Solution code:
# D - Even Relation

# 木なのでノードAB間の辺を辿ればそれがAB間の最短経路となる

from collections import deque

N = int(input())

dist = [[0]*N for _ in range(N)]
neighbor = [[] for _ in range(N)]

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

d = deque([0])
color = [0] + [-1]*(N-1)

while d:
    current_point = d.popleft()
    for next_point in neighbor[current_point]:
        if color[next_point] != -1:
            continue
        else:
            color[next_point] = (color[current_point] + dist[current_point][next_point]) % 2
            d.append(next_point)

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

Submission status: Time Limit Exceeded

Solution code:
# D - Even Relation

# 木なのでノードAB間の辺を辿ればそれがAB間の最短経路となる

from collections import deque

N = int(input())

dist = [[0]*N for _ in range(N)]
neighbor = [[] for _ in range(N)]

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

d = deque([0])
color = [0] + [-1]*(N-1)

while color.count(-1) > 0:
    current_point = d.popleft()
    for next_point in neighbor[current_point]:
        if color[next_point] != -1:
            continue
        else:
            color[next_point] = (color[current_point] + dist[current_point][next_point]) % 2
            d.append(next_point)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import scipy.sparse as sparse
from collections import deque

n = int(input())

color_ls = {i: None for i in range(n)}
_map = sparse.lil_matrix((n, n))
already = set()
for i in range(n - 1):
    u, v, w = [int(i) for i in sys.stdin.readline().split()]
    u -= 1
    v -= 1
    if i == 0:
        root = u
    _map[u, v] = w
    _map[v, u] = w
    already.update({u, v})
color_ls[root] = 0
cur = root
already.clear()
que = deque()
while True:
    candidate = _map[cur].nonzero()[1]
    for cand in candidate:
        if cand in already:
            continue
        already.add(cand)
        que.append(cand)
        if _map[cur, cand] % 2 == 0:
            color_ls[cand] = 0 if color_ls[cur] == 0 else 1
        else:
            color_ls[cand] = 1 if color_ls[cur] == 0 else 0
    if len(que) == 0 or len(already) == n:
        break
    cur = que.popleft()

for i in range(n):
    print(color_ls[i])

Submission status: Time Limit Exceeded

Solution code:
# D - Even Relation

# ある頂点からの距離の偶奇が一致する点を同じ色で塗る

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra

N = int(input())

neighbor = [[0]*N for _ in range(N)]

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

neighbor = csr_matrix(neighbor)
dist_from_0 = dijkstra(neighbor, indices = 0)

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