#P11670. Farm Reversal Inspection Sum

    ID: 13760 Type: Default 1000ms 256MiB

Farm Reversal Inspection Sum

Farm Reversal Inspection Sum

Farmer John has N cows standing in a line (1 ≤ N ≤ 5×105). Each cow’s breed is denoted by an integer; the i-th cow in line is of breed \(a_i\) (1 ≤ \(a_i\) ≤ N). The cows are sent for a check‐up at the local cow hospital. However, the cow doctor is very picky and will only examine the cow in position i if its breed is exactly \(b_i\) (1 ≤ \(b_i\) ≤ N).

Farmer John is too lazy to completely rearrange his cows, so he will perform exactly one operation:

  • Choose two integers \(l\) and \(r\) with \(1 \le l \le r \le N\) and reverse the segment of cows from position \(l\) to \(r\).

For each possible reversal (there are \(\frac{N(N+1)}{2}\) choices), let the number of cows that the doctor actually examines be determined as follows:

  • For any position i not in the interval \([l,r]\), the cow remains unchanged so it is examined if \(a_i = b_i\).
  • For any position i in \([l,r]\), after reversal the cow at position i is the one originally at position \(l+r-i\). It will be examined if \(a_{l+r-i} = b_i\).

The task is to compute the sum, over all reversal operations, of the number of cows examined by the doctor.

More formally:

Let \(I(\cdot)\) be the indicator function. For a fixed reversal defined by \(l\) and \(r\) and for each position \(i\) (1 ≤ i ≤ N):

[ \text{if } i \notin [l,r]: ; I(a_i = b_i), \quad \text{if } i \in [l,r]: ; I(a_{l+r-i} = b_i). ]

You need to output:

[ \sum_{1 \le l \le r \le N} \sum_{i=1}^{N} \text{[examination indicator]}. ]

Note: All formulas above must be written in LaTeX format.

inputFormat

The first line contains a single integer \(N\). The second line contains \(N\) integers \(a_1, a_2, \dots, a_N\). The third line contains \(N\) integers \(b_1, b_2, \dots, b_N\).

outputFormat

Output a single integer — the sum over all \(\frac{N(N+1)}{2}\) reversal operations of the number of cows that are examined by the doctor.

sample

3
1 2 3
1 2 3
12