Mancunian And Colored Tree
Practice
3.9 (82 votes)
Easy
Trees
Problem
90% Success 6969 Attempts 20 Points 2s Time Limit 256MB Memory 1024 KB Max Code

After a hectic week at work, Mancunian and Liverbird decide to go on a fun weekend camping trip. As they were passing through a forest, they stumbled upon a unique tree of N nodes. Vertices are numbered from 1 to N.

Each node of the tree is assigned a color (out of C possible colors). Being bored, they decide to work together (for a change) and test their reasoning skills. The tree is rooted at vertex 1. For each node, they want to find its closest ancestor having the same color.

Input format

The first line contains two integers N and C denoting the number of vertices in the tree and the number of possible colors.
The second line contains \(N-1\) integers. The \(i \ th\) integer denotes the parent of the \(i+1 \ th\) vertex.
The third line contains N integers, denoting the colors of the vertices. Each color lies between 1 and C inclusive.

Output format

Print N space-separated integers. The \(ith\) integer is the vertex number of lowest ancestor of the \(ith\) node which has the same color. If there is no such ancestor, print 1 for that node.

Constraints

  • \(1 \le N \le 100,000\)
  • \(1 \le C \le 100,000\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
23 votes
Tags:
Binary TreeData StructuresDepth First SearchEasyTrees
Points:20
57 votes
Tags:
Binary TreeData StructuresDepth First SearchEasyHash MapsTrees
Points:50
2 votes
Tags:
Prime FactorizationLCMMedium-HardMathematicsFactorization