1. 程式人生 > >洛谷2661 資訊傳遞(最小環)

洛谷2661 資訊傳遞(最小環)

傳送門

【題目分析】

好歹也是道提高組的題啊。。。。淪為了黃題。。。。

顯然,如果一個人從另一個人口中知道了自己的生日,那麼就是跑了一個環後回到自己,所以遊戲結束的輪數就是最小環的大小。暴力dfs即可。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=2e5+10;
const int INF=0x3f3f3f3f;

int n;
int to[MAXN],depth[MAXN],num[MAXN];
int tot,ans=INF;

int Read(){
	int i=0,f=1;
	char c;
	for(c=getchar();(c>'9'||c<'0')&&c!='-';c=getchar());
	if(c=='-')
	  f=-1,c=getchar();
	for(;c>='0'&&c<='9';c=getchar())
	  i=(i<<3)+(i<<1)+c-'0';
	return i*f;
}

void dfs(int u,int d)
{
    depth[u]=d;
    num[u]=tot;
    if(depth[to[u]]){
        if(num[to[u]]<tot){
            return ;
        }
        ans=min(ans,d-depth[to[u]]+1);
    }
    else
      dfs(to[u],d+1);
}

int main()
{
    n=Read();
    for(int i=1;i<=n;++i)
      to[i]=Read();
    for(int i=1;i<=n;++i){
        if(!depth[i]){
            tot++;
            dfs(i,1);
        }
    }
    cout<<ans;
    return 0;
}