Communication Network Between Vertices
InterviewTime limit1sMemory limit1536 MB
Given a rooted tree and a frequency per node, count ancestor-descendant pairs whose frequencies divide one another. Since every parent index is smaller than the child, nodes are already topologically ordered.
- Level
Medium6 of 10
- Topics
- Math, Number theory, Tree, DFS
- Solved
- No attempts yet
Problem
Yeonguk made a fortune in the stock market, used the money to found a country, and installed communication towers that handle the country's communications.
As everyone knows, Yeonguk's country is a tree made of regions connected by roads. Each region is numbered from to . Region is where Yeonguk lives, and it is both the capital and the root of the tree. Each region has one communication tower, and the towers of two regions that are ancestors and descendants in the tree can exchange information.
However, Daniel from an enemy country saw this and began firing communication jamming waves. Because of the jamming waves, only some pairs of towers can now communicate. Each tower is assigned one frequency, and only towers whose frequencies are divisors or multiples of each other can communicate.
We must count the number of distinct pairs of communication towers in Yeonguk's country that can communicate. Indirect communication through another tower is not allowed.
Input
The first line gives the number of regions that make up Yeonguk's country.
The second line gives the frequency of the communication tower in region for each from to .
The third line gives the number of the region containing the parent node of region , in order for .
Output
Print the number of distinct pairs of communication towers that can communicate.
Constraints
- ()
- ()
- All input values are integers.