1
1 #include <bits/stdc++.h> 2 #define up(i,l,r) for(register int i = (l); i <= (r); i++) 3 #define dn(i,l,r) for(register int i = (l); i >= (r); i--) 4 #define ll long long 5 using namespace std; 6 template <typename T>void in(T &x){ 7 x = 0; T f = 1; char ch = getchar(); 8 while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();} 9 while( isdigit(ch)) {x = 10 * x + ch - 48; ch = getchar();} 10 x *= f; 11 } 12 template <typename T>void put(T x){ 13 //if(x < 0) x = -x,putchar('-'); 14 if(x > 9) put(x/10); 15 putchar(x%10 + 48); 16 } 17 const int N = 100005; 18 int n; 19 20 struct edge{ 21 int v,nxt; 22 }e[N]; int tot,head[N]; 23 24 void add(int u,int v){ e[++tot] = (edge){v,head[u]}; head[u] = tot;} 25 26 int dfn[N],low[N],sn,cnt,size[N],belong[N],f[N],maxn[N]; 27 bool instack[N],vis[N]; 28 29 stack<int>s; 30 31 void debug(){ 32 int t; 33 while(!s.empty()){ 34 t = s.top(); put(t); putchar(' '); 35 s.pop(); 36 } 37 } 38 39 void tarjan(int u){ 40 41 dfn[u] = low[u] = ++sn; 42 s.push(u); 43 instack[u] = 1; 44 //if(u == 3) debug(); 45 for(int i = head[u]; i; i = e[i].nxt){ 46 int v = e[i].v; 47 if(!dfn[v]){ 48 tarjan(v); 49 low[u] = min(low[u],low[v]); 50 } 51 else if(instack[v]) low[u] = min(low[u],dfn[v]); 52 } 53 int t = -1; 54 if(low[u] == dfn[u]){ 55 ++cnt; 56 while(t != u){ 57 t = s.top(); 58 s.pop(); 59 instack[t] = 0; 60 belong[t] = cnt; 61 ++size[cnt]; 62 } 63 } 64 } 65 66 void dfs(int u){ 67 if(f[belong[u]]) return; 68 f[belong[u]] = size[belong[u]]; 69 for(int i = head[u]; i; i = e[i].nxt){ 70 int v = e[i].v; 71 //if(vis[belong[v]]) continue; 72 if(belong[u] == belong[v]) continue; 73 dfs(v); //vis[belong[v]] = 1; 74 f[belong[u]] += f[belong[v]]; 75 } 76 } 77 78 int main(){ 79 int v; 80 in(n); 81 up(i,1,n){ 82 in(v); 83 add(i,v); 84 } 85 up(i,1,n) if(!dfn[i]) tarjan(i); 86 up(i,1,n) if(!vis[i]) dfs(i); 87 up(i,1,n){ 88 put(f[belong[i]]); 89 putchar('\n'); 90 } 91 return 0; 92 }