#include <bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define rep(i,m,n) for(int i=(m); i<=(n); i++)
#define reb(i,m,n) for(int i=(m); i>=(n); i--)
#define iter(id, v) for(auto id : v)
#define fs first
#define se second
#define MP make_pair
#define pb push_back
#define bit(msk, i) ((msk >> i) & 1)
#define SZ(v) (ll)v.size()
#define ALL(v) v.begin(),v.end()
using namespace std;
mt19937_64 rd(chrono :: steady_clock :: now ().time_since_epoch().count());
ll Rand (ll l, ll r) { return uniform_int_distribution<ll> (l, r) (rd); }
const int N = 1e5 + 7;
const int Mod = 1e9 + 7;
const int INF = 1e9;
const ll BASE = 137;
const int szBL = 350;
int n, m;
int P[N];
vector<int> ke[N];
int pos[N];
pii rr[N];
int mnP[N], mxC[N];
void dfs (int u, int p) {
rr[u].fs = min(rr[u].fs, pos[u]);
mxC[u] = pos[u];
iter (&v, ke[u]) {
dfs(v, u);
mxC[u] = max(mxC[u], mxC[v]);
}
rr[u].se = max(rr[u].se, mxC[u]);
}
void solution() {
rep (i, 0, n) vector<int> ().swap(ke[i]);
cin >> n >> m;
--n;
rep (i, 1, n) {
cin >> P[i];
ke[P[i]].pb(i);
}
rep (i, 1, n) rr[i].fs = INF, rr[i].se = 0;
rep (j, 1, m) {
rep (i, 1, n) {
int x; cin >> x;
pos[x] = i;
}
dfs(0, 0);
mnP[0] = INF;
rep (i, 1, n - 1) {
mnP[i] = min(mnP[P[i]], pos[i]);
if (mnP[i] < pos[i]) {
rr[i].fs = min(rr[i].fs, rr[P[i]].fs);
rr[i].se = max(rr[i].se, rr[P[i]].se);
}
}
}
// rep (i, 1, n) cout << i<<": "<<rr[i].fs <<","<<rr[i].se <<"\n";
// return;
sort (rr + 1, rr + 1 + n, [] (pii A, pii B) { return A.fs < B.fs || (A.fs == B.fs && A.se > B.se); });
int res = 0;
int L = -1, R = -1;
rep (i, 1, n) {
pii id = rr[i];
if (R < id.fs) {
++res;
tie(L, R) = id;
}
R = max(R, id.se);
}
cout << res <<"\n";
}
#define file(name) freopen(name".inp","r",stdin); \
freopen(name".out","w",stdout);
int main () {
// file("c");
ios_base :: sync_with_stdio(false); cin.tie(0); cout.tie(0);
int num_Test = 1;
cin >> num_Test;
while (num_Test--)
solution();
}
/*
no bug +7
1
5 2
0 0 1 1
4 3 1 2
3 4 2 1
1
3 1
0 0
1 2
*/
Compilation message
/usr/bin/ld: /tmp/ccOhJ6pI.o: in function `main':
grader.cpp:(.text.startup+0x0): multiple definition of `main'; /tmp/ccfNT8JI.o:september.cpp:(.text.startup+0x0): first defined here
/usr/bin/ld: /tmp/ccOhJ6pI.o: in function `mtbpdhr2zxjo1o4i9oreohsbuzzl4s6u::taskcase()':
grader.cpp:(.text+0x4f0): undefined reference to `solve(int, int, std::vector<int, std::allocator<int> >, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >)'
collect2: error: ld returned 1 exit status