題目描述
班裏N個小朋友,每個人都有自己最崇拜的一個小朋友(也可以是自己)。
在一個遊戲中,需要小朋友坐一個圈,
每個小朋友都有自己最崇拜的小朋友在他的右手邊。
求滿足條件的圈最大多少人?
小朋友編號爲1,2,3,…N
輸入
輸入第一行,一個整數N(3<N<100000)
接下來一行N個整數,由空格分開。
輸出
要求輸出一個整數,表示滿足條件的最大圈的人數。
樣例輸入
9
3 4 2 5 3 8 4 6 9
樣例輸出
4
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100001;
int N;
int dep[maxn], a[maxn];
int dfs(int now){
int next = a[now];
if(dep[next] != 0) return dep[now] - dep[next] + 1;
else{
dep[next] = dep[now] + 1;
int ans = dfs(next);
dep[next] = 0; //回溯
return ans;
}
}
int main()
{
cin>>N;
for(int i=1;i<=N;i++){
cin>>a[i];
}
int ans = -1;
for(int i=1;i<=N;i++){
dep[i] = 1;
int cnt = dfs(i);
dep[i] = 0; //回溯
ans = max(cnt,ans);
}
cout<<ans;
return 0;
}