#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef tree < int, null_type, less <int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set;
const int N = 2e5 + 7;
//cartesian tree node
//while creating we calculate set of elements and number of inversions
struct node{
int splitter = -1;
long long invs = 0;
ordered_set S;
node *left = nullptr, *right = nullptr;
node(){}
};
int n;
int in[N];
int weight[N];
long long ans = 0;
node *root = nullptr;
void read(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
scanf("%d", &in[i]);
for(int i = 1; i < n; ++i)
scanf("%d", &weight[i]);
}
//add/delete contribution from fiven node to result
void add_result(node *cur, int mt = 1){
if(cur -> splitter == 0)
return;
ans += mt * min(cur -> invs, (ll)cur -> left -> S.size() * (ll)cur -> right -> S.size() - cur -> invs);
}
//Create cartesian tree
//Because expected depth is O(logn) we can use bruteforce to find the smallest weight
node* get_cartesian(int from, int to){
node *ret = new node();
if(from == to){
ret -> S.insert(in[from]);
return ret;
}
int id = from;
for(int i = from + 1; i < to; ++i)
if(weight[i] < weight[id])
id = i;
ret -> splitter = id;
ret -> left = get_cartesian(from, id);
ret -> right = get_cartesian(id + 1, to);
//get elements from ordered set
for(auto v: ret -> right -> S)
ret -> S.insert(v);
//calculate number of inversions
for(auto v: ret -> left -> S){
ret -> S.insert(v);
ret -> invs += ret -> right -> S.order_of_key(v);
}
//add contribution to the result
add_result(ret);
return ret;
}
//depending on mt, removes/add element val on position p
void update_cart(int p, int val, int mt){
node *cur = root;
while(cur -> splitter != -1){
add_result(cur, -1);
if(mt == -1)
cur -> S.erase(val);
else
cur -> S.insert(val);
if(p <= cur -> splitter){
cur -> invs += mt * (int)(cur -> right -> S.order_of_key(val));
cur = cur -> left;
}
else{
cur -> invs += mt * (int)(cur -> left -> S.size() - cur -> left -> S.order_of_key(val));
cur = cur -> right;
}
}
if(mt == -1)
cur -> S.erase(val);
else
cur -> S.insert(val);
cur = root;
while(cur -> splitter != -1){
add_result(cur, 1);
if(p <= cur -> splitter)
cur = cur -> left;
else
cur = cur -> right;
}
}
int main(){
read();
root = get_cartesian(1, n);
int q;
scanf("%d", &q);
while(q--){
int x, y;
scanf("%d %d", &x, &y);
if(x == y){
printf("%lld\n", ans);
continue;
}
//remove both numbers
update_cart(x, in[x], -1);
update_cart(y, in[y], -1);
swap(in[x], in[y]);
//add both numbers
update_cart(x, in[x], 1);
update_cart(y, in[y], 1);
printf("%lld\n", ans);
}
return 0;
}