atcoder#ARC151E. [ARC151E] Keep Being Substring

[ARC151E] Keep Being Substring

Score : 700700 points

Problem Statement

You are given an integer sequence A=(A1,A2,,AN)A = (A_1, A_2, \ldots, A_N) of length NN. Additionally, its contiguous subsequences of lengths PP and QQ are given: X=(X1,X2,,XP)X = (X_1, X_2, \ldots, X_P) and Y=(Y1,Y2,,YQ)Y = (Y_1, Y_2, \ldots, Y_Q).

You can perform the four operations on XX below any number of times (possibly zero) in any order.

  • Add an arbitrary integer at the beginning of XX.
  • Delete the element at the beginning of XX.
  • Add an arbitrary integer at the end of XX.
  • Delete the element at the end of XX.

Here, XX must be a non-empty contiguous subsequence of AA before and after each operation. Find the minimum total number of operations needed to make XX equal YY. Under the Constraints of this problem, it is guaranteed that one can always make XX equal YY by repeating operations.

What is a contiguous subsequence?

A sequence X=(X1,X2,,XP)X = (X_1, X_2, \ldots, X_P) is a contiguous subsequence of A=(A1,A2,,AN)A = (A_1, A_2, \ldots, A_N) when there is an integer ll satisfying 1lNP+11 \leq l \leq N-P+1 such that Xi=Al+i1X_i = A_{l+i-1} for every i=1,2,,Pi = 1, 2, \ldots, P.

Constraints

  • 1N2×1051 \leq N \leq 2 \times 10^5
  • 1AiN1 \leq A_i \leq N
  • 1P,QN1 \leq P, Q \leq N
  • (X1,X2,,XP)(X_1, X_2, \ldots, X_P) and (Y1,Y2,,YQ)(Y_1, Y_2, \ldots, Y_Q) are contiguous subsequences of (A1,A2,,AN)(A_1, A_2, \ldots, A_N).
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN

A1A_1 A2A_2 \ldots ANA_N

PP

X1X_1 X2X_2 \ldots XPX_P

QQ

Y1Y_1 Y2Y_2 \ldots YQY_Q

Output

Print the answer.

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

You can make XX equal YY while keeping XX a non-empty contiguous subsequence of AA, as follows.

  1. First, delete the element at the beginning of XX. Now, you have X=(1)X = (1).
  2. Next, add 55 at the end of XX. Now, you have X=(1,5)X = (1, 5).
  3. Furthermore, add 77 at the end of XX. Now, you have X=(1,5,7)X = (1, 5, 7), which equal YY.

Here, you perform three operations, which is the fewest possible.

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