Descriptionevery Halloween, Wisconsin cows dress up and go out in the farm's N (1≤n≤100000) barn to collect sweets. Each of them went to an untouched barn and collected 1 candies from the shed. The farm is not big, so John has to try to make the cows happy. He set up a "follow-up barn" for each barn. The successor barn of the barn I is XI. He told the cows that after they had reached a barn, they could gather a lot of sweets as soon as they went to the next barn. In fact it's a bit of a deceptive means to save his candy. The first cow starts her journey from the barn I. Please calculate how many candies each cow can collect. Inputline 1th enters N, and then an integer line indicates the successor of the barn I to the following Barn XI, a total of n rows. Outputa total of n rows, an integer representing the number of candies a cow can collect. Sample Input4//with four points
1//1 has one side pointing to 1
3//2 has one side pointing to 3
2//3 has one side pointing to 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
HINT
Cow 1:start at 1, next is 1. Total stalls visited:1 Cow 2:start at 2, Next was 3, next is 2. Total stalls Visited:2 Cow 3:start at 3, Next was 2, next is 3. Total stalls visited:2 Cow 4:start at 4, Next was 3, Next was 2, next is 3. Total Stalls visited:3.
The general practice is to Trajan the ring, but given that there is only one successor to each point, there is no point in the ring that points outside the ring (the base ring tree).
So if we turn the side back, from the loop to the inverse topology, each one step up the answer +1 can be.
Code:
1#include <cstdio>2#include <cstring>3#include <queue>4#include <algorithm>5 #defineMem (a,p) memset (A,p,sizeof (a))6 Const intn=1e5+Ten;7 intN,dfn[n],first[n],sz,dd[n],a[n];8 intcc[n],ne[n],q[n],t=0, h=1, an[n];9 BOOLOk[n];Ten intRead () { One intans=0, f=1;CharC=GetChar (); A while(c<'0'|| C>'9'){if(c=='-') f=-1; c=GetChar ();} - while(c>='0'&&c<='9') {ans=ans*Ten+c- -; c=GetChar ();} - returnans*F; the } - intMain () { - intN=read (), tot=0; - for(intI=1; i<=n;i++){ +A[i]=read (); ne[i]=first[a[i]];first[a[i]]=i;cc[i]++; - } + for(intI=1; i<=n;i++){ A if(Ok[i])Continue; atok[i]=1;d fn[i]=++tot;dd[tot]=i;intto=A[i]; - while(!Ok[to]) { -dfn[to]=++tot;dd[tot]=to ; -ok[to]=1; to=A[to]; - } -sz=tot-dfn[to]+1; in for(inti=tot;i>=dfn[to];i--){ - intli=dd[i];cc[li]=0; an[li]=sz; to for(intJ=FIRST[LI];J;J=NE[J])if(Dfn[j]<dfn[to]) q[++t]=j,an[j]=sz+1; + } - while(h<=t) { the intx=q[h];h++;ok[x]=1; * for(intI=first[x];i;i=Ne[i]) { $an[i]+=an[x]+1;Panax Notoginsengcc[i]--;if(!cc[i]) q[++t]=i; - } the } + } A for(intI=1; i<=n;i++) printf ("%d\n", An[i]); the return 0; +}
bzoj1589
"Bzoj1589/usaco2008 Dec" Trick or Treat on the Farm collection candy--topological sort