题解
2023-08-12 17:17:30
发布于:浙江
#include<bits/stdc++.h>
using namespace std;
const int Max = 200005;
int n,m,size,Index,cnt,tot,ans = 1e9;
int dfn[Max],low[Max],sum[Max],p[Max << 1],vis[Max],head[Max];
struct e{
int to,next;
}edge[Max];
inline int read()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') f=-1,c=getchar();
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline void add(int u,int v)
{
edge[++ size].next = head[u];
head[u] = size;
edge[size].to = v;
}
inline void tarjan(int point)
{
dfn[point] = low[point] = ++ Index;
p[++ tot] = point,vis[point] = 1;
for(int u = head[point];u;u = edge[u].next)
{
int to = edge[u].to;
if(!dfn[to])tarjan(to),low[point] = min(low[point],low[to]);
else if(vis[to])low[point] = min(low[point],low[to]);
}
if(low[point] == dfn[point])
{
cnt ++;
while(1)
{
int x = p[tot --];
sum[cnt] ++;
vis[x] = 0;
if(x == point)break;
}
}
}
int main()
{
n = read();
for(int i = 1;i <= n;i ++)add(i,read());
for(int i = 1;i <= n;i ++)if(!dfn[i])tarjan(i);
for(int i = 1;i <= cnt;i ++)if(sum[i] != 1)ans = min(ans,sum[i]);
cout << ans << endl;
return 0;
}
这里空空如也
有帮助,赞一个