1这使我意识到提高组有些题难就难在他的算法标签是隐晦的,读完题,感觉除了暴力就没有其他想法了……看了题解,才知道原来是求有向图中最小的环,仔细想想还真是的
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
#define e exp(1.0)
typedef long long ll;
const ll maxn=2e5+7;
ll N,head[maxn],in[maxn],cnt,jie;
bool vis[maxn];
queue<ll>Q;
struct Edge
{
ll w;
ll to;
ll next;
}edge[maxn];
void Add(ll u,ll v,ll w)
{
edge[cnt].to=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
return ;
}
void solve()
{
ll jie;
ll i,j;
while(!Q.empty())
{
ll u=Q.front();
vis[u]=1;
Q.pop();
for(u;u;u=edge[u].next)
{
ll v=edge[u].to;
in[v]--;
if(!in[v])
Q.push(v);
}
}
return ;
}
void DFS(ll pre,ll u,ll pos,ll n)
{
vis[u]=1;
if(u==pos&&pre)
{
jie=n;
return ;
}
ll U=u;
for(u;u;u=edge[u].next)
{
ll v=edge[u].to;
DFS(U,v,pos,n+1);
}
}
int main()
{
ios::sync_with_stdio(false);
cin>>N;
ll i,j;
cnt=1;
memset(in,0,sizeof(in));
memset(head,0,sizeof(head));
memset(vis,0,sizeof(vis));
for(i=1;i<=N;i++)
{
ll v;
cin>>v;
Add(i,v,1);
in[v]++;
}
for(i=1;i<=N;i++)
{
if(!in[i])
Q.push(i);
}
solve();
ll ans=0x3f3f3f3f;
for(i=1;i<=N;i++)
{
if(!vis[i])
{
DFS(0,i,i,0);
ans=min(ans,jie);
}
}
cout<<ans<<endl;
return 0;
}