Two permutations#4653

Two permutations

5 seconds
512 megabytes
Hard

You are given two permutations of elements and queries, each described by four integers: l_1, r_1, l_2, r_2.

For each query, your task is to determine how many numbers from to have their position in the first permutation within the range [l_1, r_1] and their position in the second permutation within the range [l_2, r_2].

Input

The first line contains a single integer (1 \leq n \leq 10^6), representing the number of elements in both permutations.

The second line lists integers, separated by spaces: a_1, a_2, \ldots, a_n (1 \leq a_i \leq n), which are the elements of the first permutation.

The third line provides the second permutation in the same format.

The fourth line contains a single integer (1 \leq m \leq 10^5), indicating the number of queries.

The following lines each describe a query with four integers: a, b, c, d (1 \leq a, b, c, d \leq n). The parameters l_1, r_1, l_2, r_2 for each query are derived from a, b, c, d as follows:

  1. Define a variable . For the first query, x = 0. For subsequent queries, is the answer to the previous query plus .

  2. Define a function f(z) = ((z + x - 1) \bmod n) + 1.

  3. Replace with , with , with , and with .

  4. Set l_1 = \min(a, b), r_1 = \max(a, b), l_2 = \min(c, d), r_2 = \max(c, d).

Output

For each query, output a single integer on a separate line, representing the answer to that query.

Examples

Example 1

Loading
Loading