#include<stdio.h>
#include<iostream>
#include<algorithm>
#define inf 0X7fffffff
using namespace std;
const int N=2e6+9;
int read(int &x){
int dat=0,oko=1;char chc=getchar();
while(chc<'0'||chc>'9'){if(chc=='-')oko=-1;chc=getchar();}
while(chc>='0'&&chc<='9'){dat=dat*10+chc-'0';chc=getchar();}
x=dat*oko;return x;
}int T,n,a,b,flag,;bool vis[N];
int cnt,head[N],nxt[N<<1],to[N<<1];
void link(int f,int t){
nxt[++cnt]=head[f],head[f]=cnt,to[cnt]=t;
}void dfs(int x){
vis[x]=true;
for(int i=head[x];i;i=nxt[i]){
if(vis[to[i]]){
flag=0;return;
}dfs(to[i]);
}
}int main(){
read(T);
while(T--){
read(n);cnt=0;flag=1;
for(int i=1;i<=n+1;i++){
head[i]=0;vis[i]=false;
}for(int i=1;i<=n;i++){
read(a),read(b);
link(a,b+1);
}dfs(1);printf("%d\n",flag);
}return 0;
}