#include<iostream>
#include<cstdio>
#define maxn 250005
#define ull unsigned long long
using namespace std;
int T,n,q,l,r,a[maxn],b[maxn],la[maxn],lb[maxn],s[maxn],top=0; ull ans=0uLL;
int main(){
	freopen("match.in","r",stdin); freopen("match.out","w",stdout);
	scanf("%d",&T); T=max(T,1); while(T--){
		scanf("%d",&n); for(int i=1;i<=n;i++){scanf("%d",&a[i]); la[i]=lb[i]=0;}
		for(int i=1;i<=n;i++) scanf("%d",&b[i]);
		for(int i=1;i<=n;i++){while(a[i]>a[s[top]]&&top) la[s[top--]]=i; s[++top]=i;}
		while(top) la[s[top--]]=n+1;
		for(int i=1;i<=n;i++){while(b[i]>b[s[top]]&&top) lb[s[top--]]=i; s[++top]=i;}
		while(top) lb[s[top--]]=n+1;

		scanf("%d",&q); while(q--){
			scanf("%d%d",&l,&r); ans=0uLL;
			for(int i=l;i<=r;i++){
				int posa=i,posb=i,maxa=a[i],maxb=b[i]; while(posa<=r&&posb<=r){
					if(la[posa]-1<lb[posb]-1){
						ans+=(1uLL*maxa*maxb*(min(la[posa]-1,r)-max(posa,posb)+1));
						posa=min(la[posa]-1,r)+1; maxa=a[posa];
					}else if(la[posa]-1>lb[posb]-1){
						ans+=(1uLL*maxa*maxb*(min(lb[posb]-1,r)-max(posa,posb)+1));
						posb=min(lb[posb]-1,r)+1; maxb=b[posb];
					}else{
						ans+=(1uLL*maxa*maxb*(min(lb[posb]-1,r)-max(posa,posb)+1));
						posa=posb=min(lb[posb]-1,r)+1; maxa=a[posa]; maxb=b[posb];
					}
				}
			} cout<<ans<<endl;
		}
	}
	return 0;
}
/*
By qzhwlzy
T4 match
------code------
points 1~? -> [8,36]pts
starts at  11:28
ends   at  12:09
----------------
*/
/*
1 3
1 2 3
3 1 2
1
1 3
*/

