Similarity of Subtrees
Time limit2sMemory limit512 MB
For every node, count how many nodes share its depth profile in the rooted tree; sum the number of pairs with identical profiles.
Problem
The depth of a node in a rooted tree is defined by applying the following rules recursively.
- The depth of the root node is 0.
- A child of a node with depth has depth .
Let be the number of nodes of with depth . Two rooted trees and are similar if and only if for every non-negative integer .
You are given a rooted tree with nodes. The nodes of are numbered from 1 to , and node 1 is the root of . Let be the rooted subtree of whose root is node . Write a program that counts the pairs such that and are similar and .
Input
The input consists of a single test case.
N
a1 b1
...
aN-1 bN-1
The first line contains an integer (), the number of nodes in the tree. The following lines describe the branches: the -th of them contains and , meaning that node is the parent of node (, ). The root node is numbered 1. The given graph is guaranteed to be a rooted tree: every node except node 1 has exactly one parent, and the graph is connected.
Output
Print the number of pairs of nodes such that the subtree rooted at and the subtree rooted at are similar and .