Implement a function count_trees_in_forest that counts the number of distinct trees in a forest based on the relationships among Balls represented in a list. Each Ball has a most distant relative that contributes to forming tree structures.
Functionality:
The function should take an integer n that represents the total number of Balls in the forest and a list p of length n where each element p[i] indicates the most distant relative of Ball i.
The function logic should determine how many unique pairs of Balls form trees based on mutual relationships, where if Ball i's most distant relative is Ball j, Ball j's most distant relative should also be Ball i.
Input/Output Requirements:
Input:
An integer n (1 ≤ n ≤ 100,000), the number of Balls in the forest.
A list p of length n where p[i] (1 ≤ p[i] ≤ n) represents the most distant relative of Ball i.
Output:
An integer representing the number of distinct trees formed by the relationships among Balls.
Implementation Details:
The solution should be written in a file called /app/solution.py.
Ensure the function is efficient enough to handle the upper bounds of input constraints.
Example:
python
# Example Input
n = 5
p = [2, 1, 4, 3, 5]
# Example Output
result = count_trees_in_forest(n, p) # should return 2