We will divide the problem into two parts.
Part 1: We need to find out the list of each node . For a node , the list is actually the sorted list of distinct elements in the subtree of the node . We can find out the distinct elements in the subtree of node efficiently by using “DSU on Tree (Sack)”. But if we store the list of each node , 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 of each node .
Part 2: The final answer of node is actually the number of distinct lists in its subtree, where is any node in the subtree of node . If we know the hash value of all the lists , the problem comes down to counting the distinct hashes in the subtree of node . 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:
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 . The complexity will increase though.