3397: Two permutations
Description
You are given two permutations p and q, consisting of n elements, and m queries of the form: l1,r1,l2,r2 (l1≤r1;l2≤r2). The response for the query is the number of such integers from 1 to n, that their position in the first permutation is in segment [l1,r1] (borders included), and position in the second permutation is in segment [l2,r2] (borders included too).
A permutation of n elements is the sequence of n distinct integers, each not less than 1 and not greater than n.
Position of number v (1≤v≤n) in permutation g1,g2,...,gn is such number i, that gi=v.
The first line contains one integer n (1≤n≤106), the number of elements in both permutations. The following line contains n integers, separated with spaces: p1,p2,...,pn (1≤pi≤n). These are elements of the first permutation. The next line contains the second permutation q1,q2,...,qn in same format.
The following line contains an integer m (1≤m≤2·105), that is the number of queries.
The following m lines contain descriptions of queries one in a line. The description of the i-th query consists of four integers: a,b,c,d (1≤a,b,c,d≤n). Query parameters l1,r1,l2,r2 are obtained from the numbers a,b,c,d using the following algorithm:
- Introduce variable x. If it is the first query, then the variable equals 0, else it equals the response for the previous query plus one.
- Introduce function f(z)=((z-1+x) mod n)+1.
- Suppose l1=min(f(a),f(b)),r1=max(f(a),f(b)),l2=min(f(c),f(d)),r2=max(f(c),f(d)).
Print a response for each query in a separate line.
3
3 1 2
3 2 1
1
1 2 3 3
1
4
4 3 2 1
2 3 4 1
3
1 2 3 4
1 3 2 1
1 4 2 3
1
1
2