Description
每年万圣节,威斯康星的奶牛们都要打扮一番,出门在农场的N(1≤N≤100000)个牛棚里转悠,来采集糖果.她们
每走到一个未曾经过的牛棚,就会采集这个棚里的1颗糖果. 农场不大,所以约翰要想尽法子让奶牛们得到快乐.
他给每一个牛棚设置了一个“后继牛棚”.牛棚i的后继牛棚是Xi.他告诉奶牛们,她们到了一个牛棚之后,只要
再往后继牛棚走去,就可以搜集到很多糖果.事实上这是一种有点欺骗意味的手段,来节约他的糖果. 第i只奶
牛从牛棚i开始她的旅程.请你计算,每一只奶牛可以采集到多少糖果.
Input
第1行输入N,之后一行一个整数表示牛棚i的后继牛棚Xi,共N行.
Output
共N行,一行一个整数表示一只奶牛可以采集的糖果数量.
Sample Input
4 //有四个点
1 //1有一条边指向1
3 //2有一条边指向3
2 //3有一条边指向2
3
INPUT DETAILS:
Four stalls.
* Stall 1 directs the cow back to stall 1.
* Stall 2 directs the cow to stall 3
* Stall 3 directs the cow to stall 2
* Stall 4 directs the cow to stall 3
1 //1有一条边指向1
3 //2有一条边指向3
2 //3有一条边指向2
3
INPUT DETAILS:
Four stalls.
* Stall 1 directs the cow back to stall 1.
* Stall 2 directs the cow to stall 3
* Stall 3 directs the cow to stall 2
* Stall 4 directs the cow to stall 3
Sample Output
1
2
2
3
//Cow 1: Start at 1, next is 1. Total stalls visited: 1.
Cow 2: Start at 2, next is 3, next is 2. Total stalls visited: 2.
Cow 3: Start at 3, next is 2, next is 3. Total stalls visited: 2.
Cow 4: Start at 4, next is 3, next is 2, next is 3. Total stalls visited: 3.
2
2
3
//Cow 1: Start at 1, next is 1. Total stalls visited: 1.
Cow 2: Start at 2, next is 3, next is 2. Total stalls visited: 2.
Cow 3: Start at 3, next is 2, next is 3. Total stalls visited: 2.
Cow 4: Start at 4, next is 3, next is 2, next is 3. Total stalls visited: 3.
思路: 强连通分量缩点以后求最长路。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int const N=100000+10; 4 struct edge{ 5 int to,nt; 6 }e[N<<1]; 7 int s[N],top,n,cnt,h[N],num[N],sum,bl[N],scc,dfn[N],low[N],h2[N],f[N]; 8 void add(int a,int b){ 9 e[++cnt].to=b; 10 e[cnt].nt=h[a]; 11 h[a]=cnt; 12 } 13 void add2(int a,int b){ 14 e[++cnt].to=b; 15 e[cnt].nt=h2[a]; 16 h2[a]=cnt; 17 } 18 void dfs(int x){ 19 s[++top]=x; 20 dfn[x]=low[x]=++sum; 21 for(int i=h[x];i;i=e[i].nt){ 22 int v=e[i].to; 23 if(!dfn[v]){ 24 dfs(v); 25 low[x]=min(low[x],low[v]); 26 }else if(!bl[v]) low[x]=min(low[x],dfn[v]); 27 } 28 if(low[x]==dfn[x]){ 29 scc++; num[scc]=1; 30 while (s[top]!=x) 31 bl[s[top--]]=scc,num[scc]++; 32 bl[s[top--]]=scc; 33 } 34 } 35 void solve(int x){ 36 if(f[x]) return ; 37 f[x]=num[x]; 38 for(int i=h2[x];i;i=e[i].nt){ 39 int v=e[i].to; 40 solve(v); 41 f[x]=max(f[x],f[v]+num[x]); 42 } 43 } 44 int main(){ 45 //freopen("std.in","r",stdin); 46 scanf("%d",&n); 47 for(int i=1;i<=n;i++){ 48 int x; 49 scanf("%d",&x); 50 add(i,x); 51 } 52 for(int i=1;i<=n;i++) 53 if(!dfn[i]) dfs(i); 54 for(int i=1;i<=n;i++){ 55 for(int j=h[i];j;j=e[j].nt){ 56 int x=bl[i]; 57 int y=bl[e[j].to]; 58 if(x!=y) add2(x,y); 59 } 60 } 61 for(int i=1;i<=scc;i++) 62 if(!f[i]) solve(i); 63 for(int i=1;i<=n;i++) 64 printf("%d\n",f[bl[i]]); 65 return 0; 66 }