#P10388. [蓝桥杯 2024 省 A] 团建

[蓝桥杯 2024 省 A] 团建

Problem Description

Xiaolan is doing team building with friends. There is a game that requires two people to cooperate. Each person receives a tree of size nn and mm respectively, and each node on the tree has a positive integer weight.
Starting from the root node 11 of their own tree, each person needs to walk to some leaf node. The weights of all nodes on the path from the root to that leaf form a positive integer sequence. Their score is the length of the longest common prefix of the two sequences. Given the two trees, compute the maximum possible score.

Input Format

The first line contains two positive integers n,mn, m, separated by a space.
The second line contains nn positive integers c1,c2,,cnc_1, c_2,\cdots , c_n, separated by spaces, where cic_i denotes the weight of node ii in the first tree.
The third line contains mm positive integers d1,d2,,dmd_1, d_2,\cdots, d_m, separated by spaces, where did_i denotes the weight of node ii in the second tree.
The next n1n - 1 lines each contain two positive integers ui,viu_i , v_i indicating that the first tree has an edge between uiu_i and viv_i.
The next m1m - 1 lines each contain two positive integers pi,qip_i , q_i indicating that the second tree has an edge between pip_i and qiq_i.

Output Format

Output one line containing one integer, the answer.

2 2
10 20
10 30
1 2
2 1
1
5 4
10 20 30 40 50
10 40 20 30
1 2
1 3
2 4
3 5
1 2
1 3
3 4
2

Hint

For 20%20\% of the test cases, 1n,m5001 \le n, m \le 500.
For all test cases, 1n,m2×1051 \le n, m \le 2 \times 10^5, 1ci,di1081 \le c_i , d_i \le 10^8, 1ui,vin1 \le u_i , v_i \le n, 1pi,qim1 \le p_i , q_i \le m. For any node, the weights of its child nodes are all distinct.

Translated by ChatGPT 5