#P3893. [GDOI2014] Beyond

[GDOI2014] Beyond

Description

Jodie slowly walks into the laboratory. The spirit Aiden, who follows by her side, seems a bit upset, but still sticks closely to Jodie.

Today’s experiment takes place on a very large circular ring with LL cells. Each cell displays a lowercase English letter. Jodie starts from any cell. Whenever she leaves a cell, the letter in that cell changes randomly; no one knows what it will become. Jodie walks clockwise around the ring without ever turning back. Each time she enters a cell, she writes down the letter currently displayed in that cell.

Since Jodie cannot turn back and does not know how many cells the ring has, she does not know when she will reach a cell she has already visited. So she asks Aiden to remind her when her next step would enter a previously visited cell. However, after a quarrel, Aiden gets angry and decides to tell her only after Jodie has already stepped into KK repeated cells (with K0K \geq 0). Jodie performs two experiments and records the two paths. Before the second experiment begins, the letter in each cell is reset to the state it had before the first experiment started. Jodie discovers Aiden’s prank, so she can only report the largest possible LL to the experimenters.

To help you better understand the problem, please analyze the example:

Suppose L=4L = 4, K=1K = 1.

Before the first experiment starts, the letters displayed by each cell are as shown below:

Jodie starts walking from the cell showing the letter a. Aiden tells her to stop after she has stepped into KK repeated cells, so Jodie takes a total of 55 steps. After each step, the cells change as follows (the arrow points to the cell where Jodie is):

Jodie’s second experiment starts from the cell showing the letter c. After each step, the cells change as follows (the arrow points to the cell where Jodie is):

The two paths recorded by Jodie are:

abcdx

cdabz

Now you are given the length NN of each of Jodie’s two recorded paths, and the two strings she wrote down, but KK is unknown. Please find the maximum possible value of LL.

Input Format

The first line contains an integer NN.

The second line contains a string of length NN, consisting only of lowercase letters.

The third line contains a string of length NN, consisting only of lowercase letters.

Output Format

Output a single number LL, the maximum possible number of cells on the ring.

5
abcdx
cdabz

4
4
abcd
cdab

4

Hint

Constraints:

  • For 20%20\% of the testdata, 1N5,0001 \leq N \leq 5{,}000.
  • For 50%50\% of the testdata, 1N600,0001 \leq N \leq 600{,}000.
  • For 100%100\% of the testdata, 1N2,000,0001 \leq N \leq 2{,}000{,}000.

Translated by ChatGPT 5