We will divide the problem into two parts.

Part 1: We need to find out the list LuL_u of each node uu. For a node uu, the list LuL_u is actually the sorted list of distinct elements in the subtree of the node uu. We can find out the distinct elements in the subtree of node uu efficiently by using “DSU on Tree (Sack)”. But if we store the list LuL_u of each node uu, it will take too much time and memory. To avoid this, we can apply hashing. While running DSU on Tree, when we get a new element, we will add the hash value of that element. Similarly, when an element will be erased totally, we will subtract the hash value of that element. Thus we can calculate the hash value of the list LuL_u of each node uu.

Part 2: The final answer of node uu is actually the number of distinct lists LvL_v in its subtree, where vv is any node in the subtree of node uu. If we know the hash value of all the lists LvL_v, the problem comes down to counting the distinct hashes in the subtree of node uu. This can be done easily by applying “DSU on Tree” again.

P.S: Single hash and unsigned hash may lead to wrong answers due to collision. Use double hash instead.

Complexity: O(nlogn)\mathcal{O}(n\log n)
Tester’s Sol: https://pastebin.com/tr8km8E6

Instead of “DSU on Tree (Sack)”, we can also apply “DFS time (discovery time)” and “MO’s Algorithm” together to get the necessary information of the subtree of any node uu. The complexity will increase though.

Statistics

67% Solution Ratio
serotoninEarliest, Dec '21
ChatGPTFastest, 2.1s
serotoninLightest, 26 MB
ChatGPTShortest, 2284B
Toph uses cookies. By continuing you agree to our Cookie Policy.