Evolutionary Algorithms
Time limit40sMemory limit1024 MB
Count ordered triplets (a, b, c) where b is an ancestor of a but not of c, and S_b is at least K times both S_a and S_c plus 1.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Binary search, Sorting
- Solved
- No attempts yet
Problem
Ada is working on a science project for school. She is studying evolution and wants to compare how different species perform when solving a coding competition problem.
There are species numbered from 1 to . Species 1 has no direct ancestor, and every other species has exactly one direct ancestor, from which it evolved. An ancestor of species (direct or indirect) is any other species that can be reached from by repeatedly moving to a direct ancestor. So species 1 is an ancestor of every other species.
Each species has an average score in a particular coding competition. Ada calculated these scores with genetic simulations.
An interesting triplet is an ordered triplet of distinct species such that:
- Species is an ancestor of species .
- Species is not an ancestor of species .
- Species has an average score strictly more than times higher than both and , that is, .
Count the interesting triplets.
Input
The first line contains , the number of test cases. Each test case is given as follows.
The first line contains two integers and .
The second line contains integers .
The third line contains integers , where is the direct ancestor of species .
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1, and is the total number of interesting triplets.
Constraints
- .
- .
- for all .
- for all .
- Species 1 is a (direct or indirect) ancestor of all other species.
Hint

In Sample Case #1, the only interesting triplet is . Species 3 is an ancestor of species 5, and it is not an ancestor of species 4. Also, .

In Sample Case #2, there are seven interesting triplets: