#include <bits/stdc++.h>
using namespace std;
#define int long long
#define fir first
#define sec second
#define mkp make_pair
#define pb push_back
#define lep( i, l, r ) for ( int i = ( l ); i <= ( r ); ++ i )
#define rep( i, r, l ) for ( int i = ( r ); i >= ( l ); -- i )
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair < int, int > pii;
char _c; bool _f; template < class type > inline void read ( type &x ) {
_f = 0, x = 0;
while ( _c = getchar (), !isdigit ( _c ) ) if ( _c == '-' ) _f = 1;
while ( isdigit ( _c ) ) x = x * 10 + _c - '0', _c = getchar (); if ( _f ) { x = -x; }
}
template < class type > inline void chkmin ( type &x, type y ) { x = ( x <= y ? x : y ); }
template < class type > inline void chkmax ( type &x, type y ) { x = ( x >= y ? x : y ); }
const int N = 5e5 + 5;
int ans;
int head[N], tot;
struct Node {
int to, next;
} edges[N << 1];
void add ( int u, int v ) {
tot ++;
edges[tot].to = v;
edges[tot].next = head[u];
head[u] = tot;
}
int fa[N], siz[N], p[N], tmp[N];
int find ( int x ) {
if ( x == fa[x] ) {
return x;
}
return fa[x] = find ( fa[x] );
}
void unionn ( int x, int y ) {
x = find ( x ), y = find ( y );
if ( x != y ) {
fa[x] = y;
}
}
void init ( int n ) {
tot = 0;
for ( int i = 1; i <= n; i ++ ) {
head[i] = siz[i] = p[i] = tmp[i] = 0;
}
for ( int i = 0; i < n; i ++ ) {
fa[i] = i;
}
}
void help ( int l, int r ) {
for ( int i = l; i < r; i ++ ) {
if ( find ( i ) != find ( i + 1 ) ) {
unionn ( i, i + 1 );
ans --;
}
}
}
void dfs ( int x ) {
siz[x] = p[x];
for ( int i = head[x]; i; i = edges[i].next ) {
dfs ( edges[i].to );
siz[x] = max ( siz[x], siz[edges[i].to] );
}
if ( x && siz[x] > p[x] ) {
help ( p[x], siz[x] );
}
}
int solve ( int n, int m, vector < int > fa, vector < vector < int > > s ) {
init ( n );
for ( int i = 1; i < n; i ++ ) {
add ( fa[i], i );
}
ans = n - 1;
for ( int j = 0; j < m; j ++ ) {
for ( int i = 0; i < n - 1; i ++ ) {
p[s[j][i]] = i;
}
dfs ( 0 );
if ( j ) {
for ( int i = 1; i < n; i ++ ) {
if ( p[i] < tmp[i] ) {
help ( p[i], tmp[i] );
}
else {
help ( tmp[i], p[i] );
}
}
}
for ( int i = 0; i < n; i ++ ) {
tmp[i] = p[i];
}
}
return ans;
}
void Solve () {
int t;
cin >> t;
while ( t -- ) {
int n, m;
cin >> n >> m;
vector < int > fa ( n + 1 );
for ( int i = 1; i < n; i ++ ) {
cin >> fa[i];
}
vector < vector < int > > s ( m, vector < int > ( n - 1 ) );
for ( int i = 0; i < m; i ++ ) {
for ( int j = 0; j < n - 1; j ++ ) {
cin >> s[i][j];
}
}
cout << solve ( n, m, fa, s ) << '\n';
}
}
// signed main () {
// #ifdef judge
// freopen ( "Code.in", "r", stdin );
// freopen ( "Code.out", "w", stdout );
// freopen ( "Code.err", "w", stderr );
// #endif
// Solve ();
// return 0;
// }