Bob's Longest Common Path

View as PDF

Submit solution

Points: 25 (partial)
Time limit: 3.0s
Memory limit: 512M

Problem types

Bob has a tree with N nodes, numbered from 1 to N. On the tree, there are K simple paths, numbered from 1 to K. The i-th simple path is from the node a_i to the node b_i. Bob wants to find out the longest common path between any two given paths. The longest common path is defined as the number of common edges between two paths.

Your task is to help Bob find out the length of the longest common path between any two given paths.

Input Specification:

The first line of input contains two integers N and K (2 \le N, K \le 2 \times 10^5), the number of nodes and the number of given paths.

The second line contains N-1 integers, p_2, p_3, \ldots, p_N (1 \le p_i \le N), indicating the parent of each node.

Each of the following K lines contains two integers, a_i and b_i, (1 \le a_i, b_i \le N and a_i \neq b_i), the two endpoints of the i-th given path.

Output Specification:

Output one integer, the length of the longest commont path.

Constraints

Subtask Points Additional constraints
1 29 2 \le N, K \le 100
2 12 2 \le N \le 4000, 2 \le K \le 1000
3 15 2 \le N \le 10^5, 2 \le K \le 5000
4 10 2 \le N \le 10^5, 2 \le K \le 50\,000, the length of each path is \le 20
5 12 2 \le N \le 10^5, 2 \le K \le 50\,000, either a_i or b_i is the LCA(a_i, b_i).
6 22 No additional constraints.

Sample Input 1:

4 2
1 2 2
1 3
1 4

Sample Output 1:

1

Sample Input 2:

7 3
1 2 2 4 5 5
1 3
3 7
6 1

Sample Output 2:

2

Comments

There are no comments at the moment.