#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MAXN = 2e5 + 100;
int N, M, color[MAXN];
bool vis[MAXN];
vector<int> adj[MAXN];
vector<int> toposort;
void dfs(int v) {
  vis[v] = true;
  for (auto x : adj[v]) {
    if (!vis[x]) {
      dfs(x);
    }
  }
  toposort.push_back(v);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int T;
  cin >> T;
  while (T--) {
    int N, M;
    cin >> N >> M;
    while (M--) {
      int u, v;
      cin >> u >> v;
      u--, v--;
      adj[u].push_back(v);
    }
    for (int i = 0; i < N; i++) {
      if (!vis[i]) {
        dfs(i);
      }
    }
    reverse(toposort.begin(), toposort.end());
    vector<int> ans;
    for (auto v : toposort) {
      if (color[v] == 2)
        ans.push_back(v);
      else {
        for (auto u : adj[v]) {
          if (u != v) color[u] = max(color[u], color[v] + 1);
        }
      }
    }
    cout << ((int)(ans).size()) << "\n";
    for (auto x : ans) cout << x + 1 << " ";
    cout << "\n";
    for (int i = 0; i < N; i++) {
      adj[i].clear();
      vis[i] = false;
      color[i] = 0;
    }
    toposort.clear();
  }
}
