每一年,在威斯康星州,奶牛們都會穿上衣服,收集農夫約翰在N(1<=N<=100,000)個牛棚隔間中留下的糖果,以此來慶祝美國秋天的萬聖節。ios
因爲牛棚不太大,FJ經過指定奶牛必須遵循的穿越路線來確保奶牛的樂趣。爲了實現這個讓奶牛在牛棚裏來回穿梭的方案,FJ在第i號隔間上張貼了一個「下一個隔間」Next_i(1<=Next_i<=N),告訴奶牛要去的下一個隔間;這樣,爲了收集它們的糖果,奶牛就會在牛棚裏來回穿梭了。ide
FJ命令奶牛i應該從i號隔間開始收集糖果。若是一隻奶牛回到某一個她已經去過的隔間,她就會中止收集糖果。spa
在被迫中止收集糖果以前,計算一下每頭奶牛要前往的隔間數(包含起點)。code
第1行 整數n。blog
第2行到n+1行 每行包含一個整數 next_i 。ip
n行,第i行包含一個整數,表示第i只奶牛要前往的隔間數。input
4
1
3
2
3 string
1
2
2
3it
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<map> 6 #include<set> 7 #include<vector> 8 #include<queue> 9 #include<algorithm> 10 #include<cmath> 11 using namespace std; 12 typedef long long ll; 13 const int N=100000+100; 14 int Link[N],len=0,bok[N]; 15 int n,yy,ans[N],que[N]; 16 struct student 17 { 18 int y,next; 19 }e[N]; 20 void insert(int xx,int yy) 21 { 22 e[++len].next=Link[xx]; 23 Link[xx]=len; 24 e[len].y=yy; 25 } 26 int bfs(int x) 27 { 28 memset(bok,0,sizeof(bok)); 29 int head=1,tail=2; 30 ans[x]++; 31 que[head]=x; 32 bok[x]=1; 33 while(head<tail) 34 { 35 for(int i=Link[que[head]];i;i=e[i].next) 36 { 37 if(!bok[e[i].y]) 38 { 39 ans[x]++; 40 bok[e[i].y]=1; 41 que[tail++]=e[i].y; 42 } 43 } 44 head++; 45 } 46 return ans[x]; 47 } 48 int main() 49 { 50 scanf("%d",&n); 51 for(int i=1;i<=n;i++) 52 { 53 scanf("%d",&yy); 54 insert(i,yy); 55 } 56 for(int i=1;i<=n;i++) 57 cout<<bfs(i)<<endl; 58 59 return 0; 60 }