#include "september.h"
#include <bits/stdc++.h>
using namespace std;
int solve(int N, int M, vector<int> F, vector<vector<int>> S) {
vector<vector<int>> adj(N);
vector<int> child(N), cnt(N);
vector<bool> del(N, false);
for(int i = 1; i < N; ++i) child[F[i]]++;
int ans = 0, c = 0, leaf = 0;
for(int i = 0; i < N - 1; ++i){
if(child[S[0][i]] == 0) leaf++;
del[S[0][i]] = true;
int par = F[S[0][i]];
if(par != -1) {
child[par]--;
if(del[par] && child[par] == 0) leaf++;
}
for(int j = 0; j < M; ++j) {
cnt[S[j][i]]++;
if(cnt[S[j][i]] == M) c++;
}
if(leaf == i + 1 && c == i + 1) ans++;
}
return ans;
}
/*
void taskcase() {
int N, M;
assert(2 == scanf("%d%d", &N, &M));
std::vector<int> F(N);
F[0] = -1;
for (int i = 1; i < N; ++i)
assert(1 == scanf("%d", &F[i]));
std::vector<std::vector<int>> S(M, std::vector<int>(N - 1));
for (int i = 0; i < M; ++i)
for (int j = 0; j < N - 1; ++j)
assert(1 == scanf("%d", &S[i][j]));
printf("%d\n", solve(N, M, F, S));
}
int main() {
int T;
assert(1 == scanf("%d", &T));
while(T--) taskcase();
return 0;
}
1
5 2
-1 0 0 1 1
1 2 3 4
4 1 2 3
*/