#include "september.h"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void dbg() { cout << "\n"; }
template<typename H, typename... T>
void dbg(H h, T... t) {
cout << h << " ";
dbg(t...);
}
const int MX = 10;
const int NX = 1e5+10;
int ti,t[NX],low[NX],comp[NX],mark[NX],dis[NX],deg[NX];
vector<int> adj[NX],adj2[NX];
stack<int> st;
void dfs(int u) {
t[u] = low[u] = ++ti;
mark[u] = 1;
st.push(u);
for (auto v : adj[u]) {
if (t[v] == 0) {
dfs(v);
low[u] = min(low[u],low[v]);
} else if (mark[v]) {
low[u] = min(low[u],t[v]);
}
}
if (low[u] == t[u]) {
while (true) {
int top = st.top(); st.pop();
mark[top] = 0;
comp[top] = u;
if (top == u) break;
}
}
}
int solve(int N, int M, vector<int> F, vector<vector<int>> S) {
ti = 0;
while (!st.empty()) st.pop();
for (int i = 0; i < N; i++) t[i] = low[i] = comp[i] = mark[i] = dis[i] = deg[i] = 0, adj[i].clear(), adj2[i].clear();
for (int i = 1; i < N; i++) {
int p = F[i];
if (p == 0) continue;
adj[i].push_back(p);
}
for (int i = 0; i < M; i++) {
for (int j = 0; j+1 < N-1; j++) {
int u = S[i][j], v = S[i][j+1];
adj[u].push_back(v);
}
}
for (int i = 1; i < N; i++) {
if (t[i]) continue;
dfs(i);
}
for (int i = 1; i < N; i++) {
for (auto x : adj[i]) {
int ci = comp[i], cx = comp[x];
if (ci == cx) continue;
adj2[ci].push_back(cx);
deg[cx]++;
}
}
queue<int> qu;
for (int i = 1; i < N; i++) {
if (comp[i] != i) continue;
if (deg[i] == 0) qu.push(i);
}
int ans = 0;
while (!qu.empty()) {
int top = qu.front(); qu.pop();
ans = max(ans,dis[top]);
for (auto x : adj[top]) {
dis[x] = max(dis[x],dis[top]+1);
if (--deg[x] == 0) qu.push(x);
}
}
return ans+1;
}