algorithm_2024/P2661/main.cpp
2024-10-01 22:48:00 +08:00

67 lines
1.3 KiB
C++

#include <algorithm>
#include <iostream>
#include <istream>
#include <queue>
#include <vector>
using std::cin,std::cout;
const int MAX_N {(int)2e5+5};
int n;
std::vector<int> next[MAX_N];
int in_degree[MAX_N];
bool vis[MAX_N];
std::queue<int> q;
int ans;
int input;
int dfs(const int start, const int now, int depth){
depth++;
vis[now] = true;
int max_depth{ depth };
for (int i : next[now]) {
if (i == start) {
max_depth = std::max(max_depth, depth);
}
else {
max_depth = std::max(dfs(start, i, depth), max_depth);
}
}
return max_depth;
};
int main(){
std::iostream::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
std::cin>>n;
for(int i=1;i<=n;i++){
cin>>input;
in_degree[input]++;
next[i].push_back(input);
}
const auto push_vis = [](int n){
q.push(n);
vis[n]=true;
};
for(int i=1;i<=n;i++){
if(in_degree[i]<=0){
push_vis(i);
}
}
while(q.empty()==false){
int front = q.front();
q.pop();
for(int i:next[front]){
if(--in_degree[i]<=0){
push_vis(i);
}
}
}
for(int i=1;i<=n;i++){
if(vis[i])continue;
ans=std::max(ans,dfs(i,i,0));
}
cout<<ans<<"\n";
}