#P9978. [USACO23DEC] Cycle Correspondence S

[USACO23DEC] Cycle Correspondence S

Problem Description

Farmer John has NN barns (3N51053 \le N \le 5\cdot 10^5), with KK pairs of distinct barns connected.

At first, Annabelle assigns each barn an integer label in the range [1,N][1,N], and she finds that the barns with labels a1,,aKa_1,\dots,a_K form a cycle connection in order. In other words, for all 1i<K1 \le i < K, barn aia_i is connected to barn ai+1a_{i+1}, and barn aKa_K is also connected to barn a1a_1. All aia_i are distinct.

Then, Bessie also assigns each barn an integer label in the range [1,N][1,N], and she finds that the barns with labels b1,,bKb_1,\dots,b_K also form a cycle connection in order. All bib_i are distinct.

Some (possibly none or all) barns are assigned the same label by both Annabelle and Bessie. Compute the maximum number of such barns.

Input Format

The first line contains NN and KK.

The next line contains a1,,aKa_1,\dots,a_K.

The next line contains b1,,bKb_1,\dots,b_K.

Output Format

The maximum number of barns that can be assigned the same label.

6 3
1 2 3
2 3 1
6
6 3
1 2 3
4 5 6
0
6 4
1 2 3 4
4 3 2 5
4

Hint

Sample Explanation 1

Annabelle and Bessie can assign the same label to every barn.

Sample Explanation 2

Annabelle and Bessie cannot assign the same label to any barn.

Sample Explanation 3

Annabelle and Bessie can assign labels 2,3,4,62,3,4,6 to the same barns.

Test Point Properties

  • Test points 454-5 satisfy N8N \le 8.
  • Test points 686-8 satisfy N5000N \le 5000.
  • Test points 9159-15 have no additional constraints.

Translated by ChatGPT 5