Editorial
Consider the contribution of each color independently.
Fix a color . Every vertex has a value , which is either or a vertex of color . The contribution of color to the answer is the number of ordered pairs with equal values, namely
where is the number of vertices such that . Here, is either or a vertex of color .
Now consider a vertex of color . A vertex satisfies if and only if
- lies in the subtree of .
- On the path from down to , excluding itself, there is no vertex of color .
So we start with all vertices in the subtree of , then subtract the subtrees of the closest same-color descendants of .
Thus,
where the sum is over vertices such that is the closest same-color ancestor of .
It remains to compute, for every vertex , its closest same-color ancestor . This can be done in one DFS from the root. During DFS, maintain , the deepest vertex of color on the current root-to-current path.
When entering a vertex , the current value of is exactly . Store it, then set . When leaving , roll it back. Each vertex is processed once, so this is linear.
We also need the number of vertices with . For a fixed color , consider vertices of color that have no same-color ancestor. Their subtrees are disjoint, and every vertex inside them has some color- ancestor. Therefore,
where the sum is over color- vertices with no same-color ancestor.
In the implementation:
- If , add to .
- Otherwise, add to .
Then the answer is
Since can be , a recursive DFS may cause stack overflow. An iterative DFS is safer.
The time complexity is , and the memory complexity is .