// implement 9min #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const double EPS = 1e-9; static const double PI = acos(-1.0); #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define FOREQ(i, s, n) for (int i = (s); i <= (int)(n); i++) #define FORIT(it, c) for (__typeof((c).begin())it = (c).begin(); it != (c).end(); it++) #define MEMSET(v, h) memset((v), h, sizeof(v)) typedef int Weight; struct Edge { int src; int dest; Weight weight; Edge(int src, int dest, Weight weight) : src(src), dest(dest), weight(weight) {;} bool operator<(const Edge &rhs) const { if (weight != rhs.weight) { return weight > rhs.weight; } if (src != rhs.src) { return src < rhs.src; } return dest < rhs.dest; } }; typedef vector Edges; typedef vector Graph; typedef vector Array; typedef vector Matrix; void PrintMatrix(const Matrix &matrix) { for (int y = 0; y < (int)matrix.size(); y++) { for (int x = 0; x < (int)matrix[y].size(); x++) { printf("%d ", matrix[y][x]); } puts(""); } } struct LCA { static const int LOG_SIZE = 17; static const int SIZE = 1 << LOG_SIZE; int parent[SIZE][LOG_SIZE]; int depth[SIZE]; LCA() {;} LCA(const Graph &g, int root) { init(g, root); } void init(const Graph &g, int root) { int n = g.size(); assert(n <= SIZE); bfs(g, root); for (int iter = 0; iter < LOG_SIZE - 1; iter++) { for (int i = 0; i < n; i++) { parent[i][iter + 1] = parent[parent[i][iter]][iter]; } } } int lca(int u, int v) { if (depth[u] > depth[v]) { swap(u, v); } for (int i = 0; i < LOG_SIZE; i++) { if (((depth[v] ^ depth[u]) >> i) & 1) { v = parent[v][i]; } } if (u == v) { return u; } for (int i = LOG_SIZE - 1; i >= 0; i--) { if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } } return parent[u][0]; } private: void bfs(const Graph &g, int root) { depth[root] = 0; parent[root][0] = root; queue que; que.push(root); while (!que.empty()) { int node = que.front(); que.pop(); for (Edges::const_iterator it = g[node].begin(); it != g[node].end(); it++) { int next = it->dest; if (next == parent[node][0]) { continue; } parent[next][0] = node; depth[next] = depth[node] + 1; que.push(next); } } } }; LCA lca; int main() { int n; while (scanf("%d", &n) > 0 && n > 0) { Graph g(n); REP(i, n - 1) { int p; int v = scanf("%d", &p); assert(v == 1); p--; g[p].push_back(Edge(p, i + 1, 0)); } REP(i, n) { REP(j, g[i].size() - 1) { assert(g[i][j].dest < g[i][j + 1].dest); } } lca.init(g, 0); queue que; que.push(0); int prev = 0; ll ans = 0; while (!que.empty()) { int node = que.front(); que.pop(); int r = lca.lca(prev, node); ans += abs(lca.depth[prev] - lca.depth[r]) + abs(lca.depth[node] - lca.depth[r]); FORIT(it, g[node]) { que.push(it->dest); } prev = node; } printf("%lld\n", ans); } }