import java.io.*;
import java.util.*;
public class Main {
public static Read scanner = new Read(System.in);
public static final long MOD = 998244353;
public static final int MID = (int) (1 * 1e5 + 10);
public static long[] arr = new long[MID];
public static int N, M, n, m;
public static long ans;
public static int[] row = {1, -1, 0, 0};
public static int[] cos = {0, 0, 1, -1};
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static ArrayList<Integer>[] list = new ArrayList[MID];
public static HashSet<Integer>[] sets = new HashSet[MID];
public static boolean[] pool = new boolean[MID];
public static int iq = 1;
public static void solve() {
n = scanner.nextInt();
int m = scanner.nextInt();
for (int i = 0; i <= n + 1; i++) {
list[i] = new ArrayList<>();
sets[i] = new HashSet<>();
pool[i] = false;
}
for (int i = 1; i <= m; i++) {
int a = scanner.nextInt();
int b = scanner.nextInt();
if (a == b) continue;
if (a > b) {
list[b].add(a);
sets[b].add(a);
} else {
list[a].add(b);
sets[a].add(b);
}
}
list[1].add(n + 1);
for (int i = 1; i <= n; i++) Collections.sort(list[i]);
if (n == 1) {
out.println(0);
return;
}
iq = 1;
ans = 0;
dfs(1);
out.println(Math.max(0, ans));
}
public static void dfs(int in) {
if (iq > n) return;
pool[in] = true;
if (pool[iq]) iq++;
for (Integer i : list[in]) {
if (i < iq) continue;
if (pool[i]) continue;
if (i == iq) {
dfs(i);
} else {
while (i >= iq && iq <= n) {
if (i == iq) {
dfs(iq);
} else {
ans++;
dfs(iq);
}
}
}
}
}
public static void main(String[] args) {
int T = scanner.nextInt();
while (T-- != 0) {
solve();
}
out.flush();
}
static class Read {
BufferedReader br;
StringTokenizer st;
public Read(InputStream in) {
br = new BufferedReader(new InputStreamReader(in), 16384);
eat("");
}
public void eat(String s) {
st = new StringTokenizer(s);
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
public boolean hasNext() {
while (!st.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
}