信息传递 LibreOJ - 2421
题意:
给你n个人。每个人会向
T
i
T_i
Ti传递信息。
问:
最少经过多少轮后,会有人搜到自己的电话。
思路:
- 其实就是求强联通分量时,把每个环的长度取个min。
AC
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fzhead EDGE(int _to, int _next)
#define fzbody to(_to), next(_next)
#define mst(x,a) memset(x,a,sizeof(x))
#pragma comment(linker,"STACK:102400000,102400000")
using namespace std;
const int maxn=2e5+10;
const int inf = 1e9+10;
struct EDGE{
int to,next;
EDGE(){}
fzhead:fzbody{}
}e[2*maxn];
int tot,head[maxn],vis[maxn];
void add(int bg, int to){
e[tot]=EDGE(to,head[bg]);
head[bg]=tot++;
}
int dfn[maxn],low[maxn];
int dfs_clock,bcc_cnt;
int ans,n;
stack<int>s;
void init(){
ans=inf;
dfs_clock=bcc_cnt=tot=0;
mst(head,-1);
mst(vis,0);
mst(dfn,0);
mst(low,0);
while(!s.empty())s.pop();
}
void tarjan(int u){
vis[u]=1;
dfn[u]=low[u]=++dfs_clock;
s.push(u);
for(int i=head[u]; i!=-1; i=e[i].next){
int v=e[i].to;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(vis[v]){
if(dfn[v]<dfn[u])ans=min(ans,dfn[u]-dfn[v]+1);
low[u]=min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u]){
vis[u]=0;
int j;
do{
j=s.top();s.pop();
}while(j!=u);
}
}
int main()
{
ios::sync_with_stdio(0);
cin>>n;
int v;
init();tot=2;
For(u,1,n){
cin>>v;
add(u,v);
}
For(i,1,n){
if(!dfn[i])dfs_clock=0,tarjan(i);
}
cout<<ans<<endl;
return 0;
}