10420: USACO 2023 December Contest, Silver Problem 2. Cycle Correspondence
Description
Farmer John has $N$ barns $(3≤N≤5⋅10^5)$, of which $K\ (3≤K≤N)$ distinct pairs of barns are connected.
First, Annabelle assigns each barn a distinct integer label in the range $[1,N]$, and observes that the barns with labels $a_1,…,a_K$ are connected in a cycle, in that order. That is, barns $a_i$ and $a_{i+1}$ are connected for all $1≤i<K$, and barns $a_K$ and $a_1$ are also connected. All $a_i$ are distinct.
Next, Bessie also assigns each barn a distinct integer label in the range $[1,N]$ and observes that the barns with labels $b_1,…,b_K$ are connected in a cycle, in that order. All $b_i$ are distinct.
Some (possibly none or all) barns are assigned the same label by Annabelle and Bessie. Compute the maximum possible number of barns that are assigned the same label by Annabelle and Bessie.
Input
The next line contains $a_1,…,a_K$.
The next line contains $b_1,…,b_K$.
Output
Sample 1 Input
6 3
1 2 3
2 3 1
Sample 1 Output
6
Sample 2 Input
6 3
1 2 3
4 5 6
Sample 2 Output
0
Sample 3 Input
6 4
1 2 3 4
4 3 2 5
Sample 3 Output
4