This page is still under construction.

Parts of this page are still being built. What you see may change.

Communication Network Between Vertices

Interview

Time limit1sMemory limit1536 MB

Summary
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 NN regions connected by N−1N-1 roads. Each region is numbered from 11 to NN. Region 11 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 NN that make up Yeonguk's country.

The second line gives the frequency A[i]A[i] of the communication tower in region ii for each ii from 11 to NN.

The third line gives the number P[i]P[i] of the region containing the parent node of region ii, in order for i=2,⋯ ,Ni=2, \cdots, N.

Output

Print the number of distinct pairs of communication towers that can communicate.

Constraints

  • 1≤N≤100 0001 \leq N \leq 100\,000
  • 1≤A[i]≤100 0001 \leq A[i] \leq 100\,000 (1≤i≤N1 \leq i \leq N)
  • 1≤P[i]<i1 \leq P[i] < i (2≤i≤N2 \leq i \leq N)
  • All input values are integers.

Examples1

  1. Example 1

    Input
    4
    1 2 3 4
    1 2 2
    
    Expected output
    4