1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include "iostream" #include "algorithm" #include "cstring" #include "cstdio" #include "cmath" #include "vector" #include "map" #include "set" #include "queue" using namespace std; #define MAXN 600046
#define rep(i, a, b) for (int i = (a), i##end = (b); i <= i##end; ++i) #define per(i, a, b) for (int i = (a), i##end = (b); i >= i##end; --i) #define pii pair<int,int> #define fi first #define se second #define mp make_pair #define pb push_back #define eb emplace_back #define vi vector<int> #define all(x) (x).begin() , (x).end() #define mem( a ) memset( a , 0 , sizeof a ) typedef long long ll; int n , m; int A[MAXN];
vi G[MAXN]; int dfn[MAXN] , bc[MAXN] , clo; int g[MAXN][20] , dep[MAXN];
void dfs( int u ) { dfn[u] = ++ clo , bc[clo] = u; if( u == 1 ) dep[u] = 1; for( int v : G[u] ) { g[v][0] = u; dep[v] = dep[u] + 1; rep( k , 1 , 18 ) if( g[g[v][k - 1]][k - 1] ) g[v][k] = g[g[v][k - 1]][k - 1]; else break; dfs( v ); } }
int lca( int u , int v ) { if( dep[u] < dep[v] ) swap( u , v ); if( dep[u] != dep[v] ) per( k , 18 , 0 ) if( dep[g[u][k]] >= dep[v] ) u = g[u][k]; if( u == v ) return u; per( k , 18 , 0 ) if( g[u][k] != g[v][k] ) u = g[u][k] , v = g[v][k]; return g[u][0]; }
int dis( int u , int v ) { return dep[u] + dep[v] - 2 * dep[lca( u , v )]; }
set<int> S;
void solve() { cin >> n; ++ n; rep( i , 2 , n ) { int p; scanf("%d",&p); G[p].pb( i ); } dfs( 1 ); int s = 1 , t = 1 , lt = 0; auto wkr = [&]( int x ) { return max( dis( x , s ) , dis( x , t ) ); }; S.insert( 1 ); rep( i , 2 , n ) { int is = dis( i , s ) , it = dis( i , t ) , flg = 0; if( is >= lt && is >= it ) t = i , lt = is , flg = 1; else if( it >= lt && it >= is ) s = i , lt = it , flg = 1; if( !flg ) { printf("%d\n",(int)S.size()); continue; } auto tr = S.lower_bound( dfn[i] ) , st = tr; while( tr != S.end() ) { if( wkr( bc[*tr] ) < lt ) ++ tr; else break; } if( tr == S.end() ) { auto sr = S.begin(); while( sr != st ) { if( wkr( bc[*sr] ) < lt ) ++ sr; else break; } S.erase( S.begin() , sr ); } S.erase( st , tr ); tr = S.lower_bound( dfn[i] ) , st = tr; while( tr != S.begin() ) { -- tr; if( wkr( bc[*tr] ) >= lt ) { ++ tr; break; } } if( tr == S.begin() ) { auto sr = S.end(); while( sr != st ) { -- sr; if( wkr( bc[*sr] ) >= lt ) { ++ sr; break; } } S.erase( sr , S.end() ); } S.erase( tr , st ); S.insert( dfn[i] );
printf("%d\n",(int)S.size()); } }
signed main() {
solve(); }
|