#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 100008;
struct Node{
int to,next;
}edge[N];
int head[N],tot,n,m,indeg[N];
int a[N], mini[N];
void init(){
memset(head, -1, sizeof(head));
memset(indeg, 0, sizeof(indeg));
tot = 0;
}
void add(int u, int to){
indeg[to]++;
edge[tot].to=to;
edge[tot].next=head[u];
head[u]=tot++;
}
LL Topsort(){
priority_queue< int, vector<int>, less<int> > q;
int cnt = 0;
for(int i = 1;i <= n; i++) {
if(indeg[i]==0) {
q.push(i);
}
}
while(!q.empty()){
int cur = q.top();
q.pop();
a[cnt++] = cur;
for(int i = head[cur]; i != -1; i = edge[i].next){
int to= edge[i].to;
indeg[to]--;
if(!indeg[to]){
q.push(to);
}
}
}
mini[0] = a[0];
LL ans = mini[0];
for(int i = 1; i < n; i++){
mini[i] = min(mini[i - 1], a[i]);
ans += mini[i];
}
return ans;
}
int main(){
int t;
int a, b;
cin>>t;
while(t--){
init();
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++){
scanf("%d %d", &a, &b);
add(a, b);
}
printf("%I64d\n", Topsort());
}
return 0;
}