Beauty of tree
Memory limit1024 MB
Given a rooted tree, two players each start at a uniformly random node and paint every A-th (or B-th) ancestor up to the root; find the expected number of nodes painted at least once.
- Level
Medium7 of 10
- Topics
- Tree, Probability, Math, DFS
- Solved
- No attempts yet
Problem
Amadea and Bilva are decorating a rooted tree containing N nodes, labelled from 1 to N. Node 1 is the root of the tree, and every other node has a node with a numerically smaller label as its parent.
Amadea and Bilva decorate the tree as follows:
- Amadea picks a node of the tree uniformly at random and paints it. Then she travels up the tree painting every A-th node until she reaches the root.
- Bilva picks a node of the tree uniformly at random and paints it. Then she travels up the tree painting every B-th node until she reaches the root.
The beauty of the tree is the number of nodes painted at least once by either Amadea or Bilva. If both paint the same node, it still counts only once.
What is the expected beauty of the tree?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the three integers N, A and B. The second line contains N-1 integers. The i-th integer is the parent of node i+1.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the expected beauty of the tree.
y is considered correct if it is within an absolute or relative error of 10-6 of the correct answer.
Limits
- 1 ≤ T ≤ 100.
- 1 ≤ A ≤ N.
- 1 ≤ B ≤ N.
Hint
The trees for each sample case are shown in the diagram below.
A few example colourings for sample case #1 are shown below.
- If Amadea picks node 5 and Bilva picks node 8, then together they paint 4 unique nodes: Amadea paints nodes 5 and 3, while Bilva paints nodes 8 and 1.
- If Amadea picks node 7 and Bilva picks node 6, then together they paint 3 unique nodes: Amadea paints nodes 7 and 1, while Bilva paints nodes 6 and 1 (note that Amadea painted node 1 as well).