#include #include using namespace std; using namespace atcoder; typedef long long int ll; typedef long double ld; #define FOR(i,l,r) for(int i=l;i=l;i--) #define RREP(i,n) RFOR(i,0,n) #define ALL(x) x.begin(),x.end() #define P pair #define F first #define S second #define BS(A,x) binary_search(ALL(A),x) #define LB(A,x) (ll)(lower_bound(ALL(A),x)-A.begin()) #define UB(A,x) (ll)(upper_bound(ALL(A),x)-A.begin()) #define COU(A,x) (UB(A,x)-LB(A,x)) templateusing min_priority_queue=priority_queue,greater>; //using mint=modint1000000007; using mint=modint998244353; void chmax(ll&a,ll b){a=max(a,b);} void chmin(ll&a,ll b){a=min(a,b);} signed main(){ int T,N;cin>>T; vectorA(2e5),B(2e5);setS; vector>M(2e5); vector>X(2e5+1); while(T--){ scanf("%d",&N); REP(i,N)scanf("%d",&A[i]); REP(i,N)scanf("%d",&B[i]); S.clear();REP(i,N)S.insert(A[i]); bool ans=1;dsu D(N); REP(i,N+1)X[i].clear(); REP(i,N){ ans=ans&&S.count(B[i])&&A[i]<=B[i]; M[i].clear();M[i][A[i]]=1; if(i==0||B[i-1]!=B[i])X[B[i]].emplace_back(i); } REP(i,N-1)if(B[i]==B[i+1]){ int u=D.leader(i),v=D.leader(i+1),r=D.merge(u,v); if(r==u)for(auto[key,val]:M[v])M[u][key]=1; else for(auto[key,val]:M[u])M[v][key]=1; } RREP(v,N+1)for(auto i:X[v]){ int l=i,r=N-1; while(l!=r){int m=(l+r+1)/2;if(D.same(i,m))l=m;else r=m-1;} if(i&&B[i-1]>B[i]){ int u=D.leader(i-1),v=D.leader(i),r=D.merge(u,v); if(r==u)for(auto[key,val]:M[v])M[u][key]=1; else for(auto[key,val]:M[u])M[v][key]=1; } if(lB[l]){ int u=D.leader(l+1),v=D.leader(l),r=D.merge(u,v); if(r==u)for(auto[key,val]:M[v])M[u][key]=1; else for(auto[key,val]:M[u])M[v][key]=1; } ans=ans&&M[D.leader(i)][v]; //if(!ans){cout<