題目描述 Description
有個同學(編號爲 1 到)正在玩一個信息傳遞的遊戲。在遊戲裏每人都有一個固定的信息傳遞對象,其中,編號爲的同學的信息傳遞對象是編號爲的同學。遊戲開始時,每人都只知道自己的生日。之後每一輪中,所有人會同時將自己當前所知的生日信息告訴各自的信息傳遞對象(注意:可能有人可以從若干人那裏獲取信息,但是每人只會把信息告訴一個人,即自己的信息傳遞對象)。當有人從別人口中得知自己的生日時,遊戲結束。請問該遊戲一共可以進行幾輪?
輸入描述 Input Description
輸入共 2行。
第 1行包含1個正整數n,表示n個人
第 2 行包含n 個用空格隔開的正整數T1 ,T 2 ,……,Tn , 其中第i個整數Ti表示編號爲i
的同學的信息傳遞對象是編號爲 T i 的同學,Ti≤n 且 Ti≠i。
數據保證遊戲一定會結束。
輸出描述 Output Description
輸出共 1行,包含 1個整數,表示遊戲一共可以進行多少輪。
樣例輸入 Sample Input
5
2 4 2 3 1
樣例輸出 Sample Output
3
數據範圍及提示 Data Size & Hint
【輸入輸出樣例 1 說明】
遊戲的流程如圖所示。當進行完第 3 輪遊戲後,4 號玩家會聽到 2 號玩家告訴他自己的生日,所以答案爲 3。當然,第 3 輪遊戲後,2 號玩家、3 號玩家都能從自己的消息來源得知自己的生日,同樣符合遊戲結束的條件。
對於 30%的數據, ≤ 200;
對於 60%的數據, ≤ 2500;
對於 100%的數據, ≤ 200000。
用tarjan找最小的環,代碼如下:
#include <cstdio>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
const int MAXN = 500005;
int n,tot,scc[MAXN],scccnt=0,sz[MAXN],to[MAXN],lt[MAXN],q,head[MAXN],nxt[MAXN],dfn[MAXN],low[MAXN];
int rd[MAXN];
struct Edge
{
int from,to;
}edge[MAXN<<1];
void build(int f,int t)
{
to[++tot] = t;
nxt[tot] = head[f];
head[f] = tot;
}
int tim = 0;
stack<int>s;
void dfs(int u)
{
low[u] = dfn[u] = ++tim;
s.push(u);
int v;
for(int i = head[u]; i ; i = nxt[i])
{
v = to[i];
if(!dfn[v])
{
dfs(v);
low[u] = min(low[u],low[v]);
}
else if(!scc[v])
{
low[u] = min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u])
{
int x;
scccnt ++;
while(!s.empty())
{
int tot = 0;
x = s.top();
s.pop();
scc[x] = scccnt;
sz[scccnt] ++;
if(u == x)
break;
}
}
}
int main()
{
int m;
scanf("%d",&n);
for(int i = 1; i <= n; i ++)
{
scanf("%d",&edge[i].to);
rd[edge[i].to]++;
}
for(int i = 1; i <= n; i ++)
{
if(rd[i]>0)
{
build(i,edge[i].to );
}
}
for(int i = 1; i <= n; i ++)
if(!dfn[i])
dfs(i);
for(int i = 1; i <= n ; i ++)
{
if(scc[i] != scc[edge[i].to] )
{
lt[scc[i]]++;
}
}
int ans = 21478483;
for(int i = 1; i <= scccnt ; i ++)
{
if(!lt[i]&& sz[i]>1)
{
ans = min(sz[i],ans);
q ++;
}
}
if(q >= 1)
{
cout <<ans<<endl;
}
else
puts("0");
return 0;
}