Tree
Time limit3sMemory limit256 MB
Support parent changes, path recoloring, and distinct-color path queries on a dynamic rooted tree.
- Level
Medium6 of 10
- Topics
- Tree, Brute force, Hash map
- Solved
- No attempts yet
Problem
A tree has nodes numbered 0 to . Node 0 is the root, and at the start every other node is a child of node 0. Every edge starts with color 0.
Three operations apply to the tree. They change the shape of the tree or paint its edges.
- paint(a, b, c): find the shortest path between node a and node b, then paint every edge on that path with color c.
- move(a, b): change the parent of node a to node b. Node b is never inside the subtree rooted at node a. If p is the parent of node a before the change, the new edge (a, b) keeps the color of the original edge (a, p).
- count(a, b): find the shortest path between node a and node b, then print how many distinct colors appear on the edges of that path.
A color c is written as an integer.
Consider an initial tree with 6 nodes and the operations move(1,3), move(5,3), paint(5,4,8), move(3,4), paint(0,3,7), count(2,5) applied in that order. Figure 1 is the initial shape. Figures 2 to 4 show, in order, how the shape of the tree and the edge colors change after each operation.

Figure 1. The initial shape

Figure 2. Left: after move(1,3). Right: after move(5,3)

Figure 3. After paint(5,4,8)

Figure 4. Left: after move(3,4). Right: after paint(0,3,7)
The last operation count(2,5) prints 3. As the right half of Figure 4 shows, the edges on the shortest path between node 2 and node 5 carry the colors , which is three distinct colors.
Given the operations in order, write a program that carries out each one efficiently.
Input
The first line contains the number of nodes () and the number of operations (). Each of the next lines holds one operation. The first integer on a line is (), the type of the operation.
- If the operation is paint, and three more integers follow on the same line: , () and (). Here and are node numbers and is a color number.
- If the operation is move, and two more integers follow on the same line: () and (). Both are node numbers.
- If the operation is count, and two more integers follow on the same line: and (). Both are node numbers.
In the initial tree of nodes, node 0 is the root, every other node has node 0 as its parent, and every edge has color 0.
For a paint or a count operation, the shortest path between node a and node b always has length at most 1,000.
Output
For each count operation in the input, print its result on its own line, in the order the operations are given. If a and b are equal, the path has no edges, so print 0.