algorithm_2024/P2661/main.cpp

68 lines
1.4 KiB
C++
Raw Normal View History

2024-10-01 13:08:27 +00:00
#include <algorithm>
#include <iostream>
#include <istream>
#include <queue>
2024-10-01 14:43:16 +00:00
#include <vector>
#include <functional>
2024-10-01 13:08:27 +00:00
using std::cin,std::cout;
const int MAX_N {(int)2e5+5};
int n;
2024-10-01 14:03:35 +00:00
std::vector<int> next[MAX_N];
2024-10-01 14:43:16 +00:00
int in_degree[MAX_N];
2024-10-01 13:08:27 +00:00
bool vis[MAX_N];
std::queue<int> q;
int ans;
2024-10-01 14:03:35 +00:00
int input;
2024-10-01 13:08:27 +00:00
2024-10-01 14:43:16 +00:00
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;
};
2024-10-01 09:35:03 +00:00
int main(){
2024-10-01 13:38:46 +00:00
std::iostream::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
2024-10-01 13:08:27 +00:00
std::cin>>n;
for(int i=1;i<=n;i++){
2024-10-01 14:03:35 +00:00
cin>>input;
2024-10-01 14:43:16 +00:00
in_degree[input]++;
2024-10-01 14:03:35 +00:00
next[i].push_back(input);
2024-10-01 13:08:27 +00:00
}
const auto push_vis = [](int n){
q.push(n);
vis[n]=true;
};
for(int i=1;i<=n;i++){
2024-10-01 14:43:16 +00:00
if(in_degree[i]<=0){
2024-10-01 13:08:27 +00:00
push_vis(i);
}
}
while(q.empty()==false){
int front = q.front();
q.pop();
2024-10-01 14:03:35 +00:00
for(int i:next[front]){
2024-10-01 14:43:16 +00:00
if(--in_degree[i]<=0){
2024-10-01 14:03:35 +00:00
push_vis(i);
}
2024-10-01 13:08:27 +00:00
}
2024-10-01 14:03:35 +00:00
2024-10-01 13:08:27 +00:00
}
2024-10-01 14:43:16 +00:00
2024-10-01 13:08:27 +00:00
for(int i=1;i<=n;i++){
if(vis[i])continue;
2024-10-01 14:43:16 +00:00
ans=std::max(ans,dfs(i,i,0));
2024-10-01 13:08:27 +00:00
}
2024-10-01 13:38:46 +00:00
cout<<ans<<"\n";
2024-10-01 09:35:03 +00:00
}