fork(2) download
  1. #include<bits/stdc++.h>
  2. #define pb(x) push_back(x)
  3. #define all(x) x.begin(), x.end()
  4. #define ones(x) __builtin_popcount(x)
  5. #define cout2(x, y) cout << x << " " << y << endl
  6. #define cout3(x, y, z) cout << x << " " << y << " " << z << endl
  7. #define N 200005
  8.  
  9. using namespace std;
  10.  
  11. int level[N], deg[N], P[N];
  12. vector<int>L[N];
  13.  
  14. int DFS(int u, int pd, int l){
  15.  
  16. level[u] = l;
  17. for(int i = 0, v; i < L[u].size(); i++){
  18.  
  19. v = L[u][i];
  20. if(v != pd)DFS(v, u, l + 1);
  21. }
  22. }
  23.  
  24. int main(){
  25.  
  26. int n, u, v;
  27. scanf("%d", &n);
  28.  
  29.  
  30. for(int i = 0; i <= n; i++)L[i].clear(), deg[i] = 0;
  31. P[1] = -1;
  32.  
  33. for(int i = 2; i <= n; i++){
  34.  
  35. scanf("%d", &P[i]);
  36. deg[P[i]]++;
  37.  
  38. L[i].pb(P[i]);
  39. L[P[i]].pb(i);
  40. }
  41.  
  42. DFS(1, -1, 0);
  43.  
  44. set<pair<int, int> >E;
  45. for(int i = 2; i <= n; i++)E.insert(make_pair(-level[i], i));
  46.  
  47. pair<int, int> e, aux;
  48. int ans = 0;
  49.  
  50. while(E.size() > 0){
  51.  
  52. e = (*E.begin());
  53. E.erase(E.begin());
  54.  
  55. u = e.second;
  56. v = P[u];
  57. //printf("%d %d %d %d\n", u, v, deg[u], deg[v]);
  58. aux = make_pair(-level[v], v);
  59. if(deg[u] >= 2 && deg[v] >= 3 && v != 1 && E.find(aux) != E.end())E.erase(aux), deg[P[v]]--, ans++;
  60. }
  61.  
  62. printf("%d\n", ans);
  63. }
  64.  
Success #stdin #stdout 0s 22688KB
stdin
Standard input is empty
stdout
0