信息传递 题解
2023-08-27 09:32:50
发布于:广东
31阅读
0回复
0点赞
稍微分析一下可知是求一个有向且无自环的图的最小环,但是明显不能用Floyd求最小环,所以考虑使用Tarjan求强连通,由于边数等于点数,所以每个强连通分量内有且只有一个环,所以求最小的强连通分量就是求最小环。
#include <bits/stdc++.h>
using namespace std;
const int Max=200005;
int n,m,size,Index,cnt,tot,ans=1e9;
int num[Max],low[Max],sum[Max],p[Max<<1],vis[Max],first[Max];
struct shu{int to,next;};
shu edge[Max];
inline int get_int()
{
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 build(int x,int y)
{
edge[++size].next=first[x];
first[x]=size;
edge[size].to=y;
}
inline void tarjan(int point)
{
num[point]=low[point]=++Index;
p[++tot]=point,vis[point]=1;
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to;
if(!num[to]) tarjan(to),low[point]=min(low[point],low[to]);
else if(vis[to]) low[point]=min(low[point],num[to]);
}
if(low[point]==num[point])
{
cnt++;
while(1)
{
int x=p[tot--];
sum[cnt]++;
vis[x]=0;
if(x==point) break;
}
}
}
int main()
{
n=get_int();
for(int i=1;i<=n;i++) build(i,get_int());
for(int i=1;i<=n;i++) if(!num[i]) tarjan(i);
for(int i=1;i<=cnt;i++) if(sum[i]!=1) ans=min(ans,sum[i]);
cout<<ans<<"\n";
return 0;
}
这里空空如也
有帮助,赞一个