Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.

A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.

Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. 

Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.

Arthur doesn't want to close too many spots. He will be happy to find any way to close at most $\frac{4}{7}n$ spots so that the remaining part is safe. Help him find any suitable way to do so.


-----Input-----

The first line contains a single positive integer $T$ — the number of test cases. $T$ test case description follows.

The first line of each description contains two integers $n$ and $m$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of landing spots and tracks respectively.

The following $m$ lines describe the tracks. Each of these lines contains two integers $x$ and $y$ ($1 \leq x < y \leq n$) — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, print a single integer $k$ ($0 \leq k \leq \frac{4}{7}n$) — the number of spots to be closed. In the next line, print $k$ distinct integers — indices of all spots to be closed, in any order.

If there are several answers, you may output any of them. Note that you don't have to minimize $k$. It can be shown that a suitable answer always exists.


-----Example-----
Input
2
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7

Output
2
3 4 
4
4 5 6 7 



-----Note-----

In the first sample case, closing any two spots is suitable.

In the second sample case, closing only the spot $1$ is also suitable.

Source: codeforces | Difficulty: VERY_HARD
Tags: Greedy algorithms

Graph algorithms

Constructive algorithms


Solutions:
import sys
inputr = lambda : sys.stdin.readline().rstrip('\n')
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	adj = [[] for _ in range(n)]
	for _ in range(m):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		adj[a].append(b)
	LP = [0] * n
	r = []
	for i in range(n):
		if LP[i] < 2:
			for j in adj[i]:
				LP[j] = max(LP[j], LP[i] + 1)
		else:
			r.append(str(i + 1))
	print(len(r))
	print(*r)
	assert 7 * len(r) <= 4 * n


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, m, g):
	dp = [0] * n
	ans = []
	for i in range(n):
		for w in g[i]:
			dp[i] = max(dp[i], dp[w] + 1)
		if dp[i] >= 2:
			dp[i] = -1
			ans.append(i + 1)
	wi(len(ans))
	wia(ans)

def main():
	for _ in range(ri()):
		(n, m) = ria()
		g = [[] for i in range(n)]
		for __ in range(m):
			(u, v) = ria()
			g[v - 1].append(u - 1)
		solve(n, m, g)
main()


import sys
from collections import deque
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
for i in range(int(input())):
	(n, m) = map(int, input().split())
	istok = [0] * n
	g = [set() for i in range(n)]
	for i in range(m):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		if b not in g[a]:
			g[a].add(b)
	delited = []

	def dfs(v, lvl):
		if lvl == 1:
			for u in g[v]:
				used[u] = 2
		else:
			for u in g[v]:
				used[u] = max(1, used[u])
	used = [0] * n
	for i in range(n):
		if used[i] == 0:
			dfs(i, 0)
		elif used[i] == 1:
			dfs(i, 1)
		else:
			delited.append(i + 1)
	print(len(delited))
	pprint(delited)


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	(n, m) = list(map(int, sys.stdin.readline().strip().split()))
	P = [[] for i in range(0, n)]
	G = [0] * n
	for i in range(0, m):
		(x, y) = list(map(int, sys.stdin.readline().strip().split()))
		(x, y) = (x - 1, y - 1)
		P[y].append(x)
	ans = []
	for i in range(0, n):
		for j in P[i]:
			for k in P[j]:
				if G[j] == 0 and G[k] == 0:
					if G[i] == 0:
						ans.append(str(i + 1))
						G[i] = 1
	print(len(ans))
	print(' '.join(ans))


import sys
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	for i in range(t):
		(n, m) = [int(x) for x in input().split()]
		graph = [[] for i in range(n)]
		for j in range(m):
			(a, b) = [int(x) - 1 for x in input().split()]
			graph[a].append(b)
		depth = [2 for x in range(n)]
		for u in range(n):
			if depth[u] > 0:
				for v in graph[u]:
					depth[v] = min(depth[v], depth[u] - 1)
		sol = [j + 1 for j in range(n) if depth[j] == 0]
		print(len(sol))
		print(*sol)
main()


from sys import stdin, stdout
t = int(stdin.readline())
while t != 0:
	t -= 1
	(n, m) = map(int, stdin.readline().split())
	adj = [[] for _ in range(n)]
	for i in range(m):
		(a, b) = map(int, stdin.readline().split())
		a -= 1
		b -= 1
		adj[a].append(b)
	indeg = [0 for _ in range(n)]
	ans = []
	for i in range(n):
		if indeg[i] < 2:
			for j in adj[i]:
				indeg[j] = max(indeg[j], indeg[i] + 1)
		else:
			ans.append(i + 1)
	stdout.write(str(len(ans)) + '\n')
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ms = []
	for _ in range(m):
		ms.append(list(map(int, input().split())))
	revGraph = [[] for _ in range(n)]
	for (s, z) in ms:
		revGraph[z - 1].append(s - 1)
	ress = [-1 for _ in range(n)]
	r = []
	for i in range(n):
		l = revGraph[i]
		if any(map(lambda x: ress[x] == 1, l)):
			ress[i] = 2
			r.append(i + 1)
		elif any(map(lambda x: ress[x] == 0, l)):
			ress[i] = 1
		else:
			ress[i] = 0
	print(len(r))
	print(*r)


import sys
input = sys.stdin.readline
from collections import deque

class DirectedGraph:

	def __init__(self, adj):
		self.n = len(adj)
		self.adj = adj
		self.is_asyclic = False
		self.max_path_len = None

	def topological_sort(self):
		indegree = [0] * self.n
		for vs in self.adj:
			for dest in vs:
				indegree[dest] += 1
		zero_v = []
		for (v, indeg) in enumerate(indegree):
			if indeg == 0:
				zero_v.append(v)
		max_path_len = 1
		tp_sorted = []
		to_be_added = []
		while True:
			while zero_v:
				v = zero_v.pop()
				tp_sorted.append(v)
				for dest in self.adj[v]:
					indegree[dest] -= 1
					if indegree[dest] == 0:
						to_be_added.append(dest)
			if len(to_be_added) > 0:
				zero_v.extend(to_be_added)
				to_be_added = []
				max_path_len += 1
			else:
				break
		if len(tp_sorted) == self.n:
			self.is_asyclic = True
			self.max_path_len = max_path_len
			return tp_sorted
		else:
			self.is_asyclic = False
			return None
t = int(input())
for case in range(t):
	(n, m) = map(int, input().split())
	forward = [[] for _ in range(n)]
	backward = [[] for _ in range(n)]
	seen = set()
	for _ in range(m):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		if (u, v) in seen:
			continue
		seen.add((u, v))
		forward[u].append(v)
		backward[v].append(u)
	DG = DirectedGraph(forward)
	tps = DG.topological_sort()
	state = [-1] * n
	state[0] = 0
	for v in tps:
		if len(backward[v]) == 0:
			state[v] = 0
		for pv in backward[v]:
			state[v] = max(state[v], (state[pv] + 1) % 3)
	ans = []
	for (i, color) in enumerate(state):
		if color == 2:
			ans.append(i + 1)
	print(len(ans))
	print(*ans)


from collections import deque
import sys
input = sys.stdin.buffer.readline

def topological_sort(graph: list) -> list:
	n = len(graph)
	degree = [0] * n
	for g in graph:
		for next_pos in g:
			degree[next_pos] += 1
	ans = [i for i in range(n) if degree[i] == 0]
	q = deque(ans)
	while q:
		pos = q.popleft()
		for next_pos in graph[pos]:
			degree[next_pos] -= 1
			if degree[next_pos] == 0:
				q.append(next_pos)
				ans.append(next_pos)
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	info = [list(map(int, input().split())) for i in range(m)]
	graph = [[] for i in range(n)]
	inv_graph = [[] for i in range(n)]
	for (a, b) in info:
		a -= 1
		b -= 1
		graph[a].append(b)
		inv_graph[b].append(a)
	tp_sort = topological_sort(graph)
	ans = [-1] * n
	for v in tp_sort:
		tmp = 0
		for prv_v in inv_graph[v]:
			tmp = max(tmp, (ans[prv_v] + 1) % 3)
		ans[v] = tmp
	res = [i + 1 for i in range(n) if ans[i] == 2]
	print(len(res))
	print(*res)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, m) = map(int, input().split())
	neig = [0] * n
	for i in range(n):
		neig[i] = [0]
	for i in range(m):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		neig[a][0] += 1
		neig[a].append(b)
	lev = [1] * n
	for i in range(n):
		for j in range(1, neig[i][0] + 1):
			x = lev[i] + 1
			if x == 4:
				x = 1
			lev[neig[i][j]] = max(lev[neig[i][j]], x)
	sol = 0
	s = []
	for i in range(n):
		if lev[i] == 3:
			sol += 1
			s.append(i + 1)
	print(sol)
	print(*s)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	(n, m) = mapi()
	gr = defaultdict(list)
	deg = [0] * (n + 1)
	for i in range(m):
		(x, y) = mapi()
		gr[x].append(y)
		deg[y] += 1
	q = deque()
	for i in range(1, len(deg)):
		if deg[i] == 0:
			q.append(i)
	top = []
	while q:
		node = q.popleft()
		top.append(node)
		for i in gr[node]:
			deg[i] -= 1
			if deg[i] == 0:
				q.append(i)
	dist = [0] * (n + 1)
	res = []
	for i in top:
		for j in gr[i]:
			dist[j] = max(dist[j], (dist[i] + 1) % 3)
	for i in range(1, n + 1):
		if dist[i] == 2:
			res.append(i)
	print(len(res))
	print(*res)


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def MI1():
	return map(int1, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		(n, m) = MI()
		to = [set() for _ in range(n)]
		for _ in range(m):
			(u, v) = MI1()
			to[u].add(v)
		dd = [0] * n
		for u in range(n):
			if dd[u] == 2:
				continue
			for v in to[u]:
				dd[v] = max(dd[v], dd[u] + 1)
		ans = [u + 1 for u in range(n) if dd[u] == 2]
		print(len(ans))
		print(*ans)
main()


import sys
from collections import deque
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	for i in range(t):
		(n, m) = [int(x) for x in input().split()]
		graph = [[] for j in range(n)]
		in_degree = [0 for j in range(n)]
		for j in range(m):
			(a, b) = [int(x) - 1 for x in input().split()]
			graph[a].append(b)
			in_degree[b] += 1
		q = deque()
		for j in range(n):
			if in_degree[j] == 0:
				q.append(j)
		s = []
		while len(q) > 0:
			u = q.popleft()
			s.append(u)
			for v in graph[u]:
				in_degree[v] -= 1
				if in_degree[v] == 0:
					q.append(v)
		depth = [2 for x in range(n)]
		for u in s:
			if depth[u] > 0:
				for v in graph[u]:
					depth[v] = min(depth[v], depth[u] - 1)
		sol = [j + 1 for j in range(n) if depth[j] == 0]
		print(len(sol))
		print(*sol)
main()


import sys
input = sys.stdin.buffer.readline
Q = int(input())
Query = []
for _ in range(Q):
	(N, M) = map(int, input().split())
	graph = [[] for _ in range(N)]
	for _ in range(M):
		(a, b) = map(int, input().split())
		graph[a - 1].append(b - 1)
	Query.append((N, M, graph))
for (N, M, graph) in Query:
	Delete = [False] * N
	Seq = [0] * N
	for i in range(N):
		if Seq[i] >= 2:
			Delete[i] = True
			Seq[i] = -1
		for p in graph[i]:
			Seq[p] = max(Seq[i] + 1, Seq[p])
	ans = []
	for i in range(N):
		if Delete[i]:
			ans.append(i + 1)
	print(len(ans))
	print(*ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	connectionList = []
	colorVertex = []
	for _ in range(n):
		connectionList.append([])
		colorVertex.append(0)
	for _ in range(m):
		(a, b) = map(int, input().split())
		connectionList[a - 1].append(b - 1)
	ans = []
	for i in range(n):
		if colorVertex[i] == 2:
			ans.append(str(i + 1))
			continue
		for elem in connectionList[i]:
			colorVertex[elem] = max(colorVertex[elem], colorVertex[i] + 1)
	print(len(ans))
	print(' '.join(ans))


import io
import os
from collections import Counter, defaultdict, deque
import random
from heapq import heappush, heappop, heapify

def solve(N, M, tracks):
	stops = range(1, N + 1)
	graph = [[] for i in range(N + 1)]
	graphT = [[] for i in range(N + 1)]
	for (u, v) in tracks:
		graph[u].append(v)
		graphT[v].append(u)
	danger = []
	for u in stops:
		for fr in graphT[u]:
			for to in graph[u]:
				danger.append([fr, u, to])
	if not danger:
		return '0\n'
	del graph
	del graphT
	maxRemove = 4 * N // 7
	dangerIds = list(range(len(danger)))
	removed = set()
	for i in dangerIds:
		needsRemove = [u for u in danger[i] if u not in removed]
		if len(needsRemove) == 3:
			removed.add(needsRemove[-1])
	assert len(removed) <= maxRemove
	return str(len(removed)) + '\n' + ' '.join(map(str, removed))
if True:
	tracks = []
	for i in range(1, 10 ** 4):
		tracks.append((i, 2 * i))
		tracks.append((i, 2 * i + 1))
	N = 2 * 10 ** 5
	solve(N, len(tracks), tracks)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	tracks = [[int(x) for x in input().split()] for i in range(M)]
	ans = solve(N, M, tracks)
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ms = []
	for _ in range(m):
		ms.append(list(map(int, input().split())))
	Graph = [[] for _ in range(n)]
	for (z, s) in ms:
		Graph[z - 1].append(s - 1)
	ones = [False for _ in range(n)]
	nones = [False for _ in range(n)]
	r = []
	for i in range(n):
		if ones[i]:
			r.append(i + 1)
			for x in Graph[i]:
				pass
		elif nones[i]:
			for x in Graph[i]:
				ones[x] = True
		else:
			for x in Graph[i]:
				nones[x] = True
	print(len(r))
	print(*r)


import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
from collections import Counter
from math import gcd
mod = 998244353

def main():
	for _ in range(int(input())):
		(n, m) = map(int, input().split())
		graph = [[] for i in range(n)]
		for i in range(m):
			(u, v) = map(lambda x: int(x) - 1, input().split())
			graph[v].append(u)
		delete = [False] * n
		for i in range(n):
			for p1 in graph[i]:
				for p2 in graph[p1]:
					if not (delete[p1] or delete[p2]):
						delete[i] = True
		ans = [i + 1 for i in range(n) if delete[i]]
		print(len(ans))
		print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin, stdout

def ski_accidents(n, dic, indgree):
	queue = []
	dis = [0 for i in range(n + 1)]
	visited = [False for i in range(n + 1)]
	res = []
	for i in range(1, n + 1):
		if visited[i]:
			continue
		queue.append(i)
		while len(queue) > 0:
			cur = queue.pop(-1)
			visited[cur] = True
			if dis[cur] == 2:
				res.append(cur)
				if cur in dic:
					for nxt in dic[cur]:
						indgree[nxt] -= 1
					continue
			if cur in dic:
				for nxt in dic[cur]:
					indgree[nxt] -= 1
					dis[nxt] = max(dis[nxt], dis[cur] + 1)
					if indgree[nxt] == 0:
						queue.append(nxt)
	return res
T = int(stdin.readline())
for i in range(T):
	(n, m) = list(map(int, stdin.readline().split()))
	dic = {}
	indgree = [0 for k in range(n + 1)]
	for j in range(m):
		(x, y) = list(map(int, stdin.readline().split()))
		if x not in dic:
			dic[x] = []
		dic[x].append(y)
		indgree[y] += 1
	res = ski_accidents(n, dic, indgree)
	stdout.write(str(len(res)) + '\n')
	stdout.write(' '.join(map(str, res)) + '\n')


from sys import stdin, gettrace
from collections import deque
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def readGraph(n, m):
	adj = [set() for _ in range(n)]
	adjr = [set() for _ in range(n)]
	for _ in range(m):
		(u, v) = map(int, inputi().split())
		adj[u - 1].add(v - 1)
		adjr[v - 1].add(u - 1)
	return (adj, adjr)

def solve(n, adj, adjr):
	path = [0] * n
	res = []
	for i in range(n):
		for j in adjr[i]:
			path[i] = max(path[i], path[j] + 1)
		if path[i] == 2:
			res.append(i + 1)
			path[i] = -1
	return res

def main():
	t = int(inputi())
	for _ in range(t):
		(n, m) = map(int, inputi().split())
		(adj, adjr) = readGraph(n, m)
		res = solve(n, adj, adjr)
		print(len(res))
		print(' '.join(map(str, res)))
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m) = [int(c) for c in input().split()]
	adj = [[] for i in range(n + 1)]
	for i in range(m):
		(a, b) = [int(c) for c in input().split()]
		adj[a].append(b)
	lp = [0 for i in range(n + 1)]
	ans = []
	for i in range(1, n + 1):
		if lp[i] < 2:
			for j in adj[i]:
				lp[j] = max(lp[j], lp[i] + 1)
		else:
			ans.append(str(i))
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(a, b) = list(map(int, input().split()))
	N = [[] for j in range(a)]
	for j in range(b):
		(x, y) = list(map(int, input().split()))
		N[x - 1].append(y - 1)
	visited = {}
	rem = set([])
	D = [0] * a
	for i in range(a):
		if D[i] < 2:
			for j in N[i]:
				D[j] = max(D[j], D[i] + 1)
		else:
			rem.add(i + 1)
	rem = list(rem)
	print(len(rem))
	print(*rem)


from types import GeneratorType
from sys import stdin, stdout

def input():
	return stdin.readline().strip()

def ans(n, children):
	V = [-1] * (n + 1)
	for i in range(1, n + 1):
		if V[i] == -1:
			V[i] = 0
			for j in children[i]:
				V[j] = max(V[j], 1)
		elif V[i] == 0:
			assert False
		elif V[i] == 1:
			for j in children[i]:
				V[j] = max(V[j], 2)
	ret = []
	for i in range(1, n + 1):
		if V[i] == 2:
			ret += [i]
	print(len(ret))
	print(' '.join(list(map(str, ret))))
T = int(input())
for _ in range(T):
	(n, m) = input().split(' ')
	n = int(n)
	m = int(m)
	children = dict()
	for i in range(1, n + 1):
		children[i] = set()
	for _ in range(m):
		(x, y) = input().split(' ')
		x = int(x)
		y = int(y)
		children[x].add(y)
	ans(n, children)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
	(n, m) = map(int, input().split())
	g = [[] for _ in range(n)]
	for _ in range(m):
		(u, v) = map(int, input().split())
		g[v - 1].append(u - 1)
	dp = [int(0) for _ in range(n)]
	ans = []
	for i in range(n):
		for w in g[i]:
			dp[i] = max(dp[i], dp[w] + 1)
		if dp[i] >= 2:
			dp[i] = int(-1)
			ans.append(i + 1)
	print(len(ans))
	print(' '.join(map(str, ans)))


import sys
input = sys.stdin.readline
readline = lambda : map(int, input().split())
for _ in range(int(input())):
	(n, m) = readline()
	g = [[] for i in range(n)]
	for i in range(m):
		(a, b) = readline()
		g[a - 1].append(b - 1)
	f = [0] * n
	for i in range(n):
		if f[i] < 2:
			for j in g[i]:
				f[j] = max(f[j], f[i] + 1)
	ans = [i + 1 for i in range(n) if f[i] == 2]
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
from heapq import heapify, heappush, heappop
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ab = [list(map(int, input().split())) for i in range(m)]
	go = [[] for i in range(n + 1)]
	come = [[] for i in range(n + 1)]
	for (a, b) in ab:
		go[a].append(b)
		come[b].append(a)
	exist = [1] * (n + 1)
	flg = [10] * (n + 1)
	for i in range(1, n + 1):
		if flg[i] == 10:
			flg[i] = 2
		if flg[i] == 0:
			exist[i] = 0
		if go[i]:
			if flg[i] == 0:
				for j in go[i]:
					flg[j] = min(flg[j], 2)
			else:
				for j in go[i]:
					flg[j] = min(flg[j], flg[i] - 1)
	print(exist.count(0))
	ansls = []
	for i in range(1, n + 1):
		if exist[i] == 0:
			ansls.append(i)
	print(*ansls)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	t = int(input())
	while t != 0:
		(n, m) = map(int, input().split())
		paths = [[] for i in range(0, n)]
		visited = [0] * n
		for i in range(0, m):
			(x, y) = map(int, input().split())
			x -= 1
			y -= 1
			paths[y].append(x)
		ans = []
		for i in range(0, n):
			for j in paths[i]:
				for k in paths[j]:
					if visited[j] == 0 and visited[k] == 0:
						if visited[i] == 0:
							ans.append(str(i + 1))
							visited[i] = 1
		print(len(ans))
		print(' '.join(ans))
		t -= 1
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()