#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include<queue>
#include<map>
#include<vector>
using namespace std;
#define ll __int64
#define inf 99999999
int n,m;
int du[100010];
int flag[100010];
int ans[100010];
void init()
{
memset(du,0,sizeof(flag));
memset(flag,0,sizeof(flag));
}
int main() {
int x,y,z,i,t;
int T;
scanf("%d",&T);
while(T--)
{
init();
vector<int>v[100010];
priority_queue<int>q;
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
{
int u,vv;
scanf("%d%d",&u,&vv);
v[u].push_back(vv);
du[vv]++;
}
int ji=0;
for(i=1;i<=n;i++)
if(du[i]==0)
q.push(i),flag[i]=1;
while(!q.empty())
{
int gg=q.top();
q.pop();
ans[ji++]=gg;
for(i=0;i<v[gg].size();i++)
{
int vv=v[gg][i];
du[vv]--;
if(du[vv]==0&&!flag[vv])
q.push(vv),flag[vv]=1;
}
}
int minn=inf;
ll getans=0;
for(i=0;i<ji;i++)
minn=min(minn,ans[i]),getans+=minn;
printf("%I64d\n",getans);
}
return 0;
}