// what is matter? never mind.
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,sse4,popcnt,abm,mmx,avx,avx2")
#include<bits/stdc++.h>
#define For(i,a,b) for(int i=(a);i<=(b);++i)
#define Rep(i,a,b) for(int i=(a);i>=(b);--i)
#define ll __uint128_t
//#define ll __int128
//#define ull unsigned long long
#define int long long
#define SZ(x) ((int)((x).size()))
#define ALL(x) (x).begin(),(x).end()
using namespace std;
inline int read()
{
char c=getchar();int x=0;bool f=0;
for(;!isdigit(c);c=getchar())f^=!(c^45);
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);
return f?-x:x;
}
#define fi first
#define se second
#define pb push_back
#define mkp make_pair
typedef pair<int,int>pii;
typedef vector<int>vi;
#define maxn 500005
#define inf 0x3f3f3f3f
int n,m;
vi e[maxn];
namespace TT{
vi e[maxn],g[maxn],dom[maxn];
int fa[maxn],dfn[maxn],que[maxn],idx;
void adde(int u,int v){e[u].pb(v);}
void dfs(int u){
que[dfn[u]=++idx]=u;
for(int v:e[u]){
if(!dfn[v])dfs(v),fa[dfn[v]]=dfn[u];
g[dfn[v]].pb(dfn[u]);
}
}
int p[maxn],mn[maxn],sdom[maxn],idom[maxn];
int get(int u){
if(p[u]!=p[p[u]]){
if(sdom[mn[u]]>sdom[get(p[u])])mn[u]=get(p[u]);
p[u]=p[p[u]];
}return mn[u];
}
void solve()
{
For(i,1,n)p[i]=mn[i]=sdom[i]=i;
dfs(1);
Rep(i,n,2){
for(int j:g[i])sdom[i]=min(sdom[i],sdom[get(j)]);
dom[sdom[i]].pb(i);
int x=p[i]=fa[i];
for(int j:dom[x])idom[j]=(sdom[get(j)]<x?get(j):x);
dom[x].clear();
}
For(i,2,n){
if(idom[i]!=sdom[i])idom[i]=idom[idom[i]];
::e[que[idom[i]]].pb(que[i]);
}
}
void init(){
For(i,1,n) e[i].clear(),g[i].clera(),dom[i].clear(),fa[i]=dfn[i]=que[i]=p[i]=mn[i]=sdom[i]=idom[i]=0; idx=0;
For(i,1,m){
int u=read(),v=read();
e[v].pb(u);
}
solve();
}
}
void dfs()
void work()
{
n=read(),m=read();
TT::init();
}
signed main()
{
int T=read();
while(T--)work();
return 0;
}
/*
*/