fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n, tar, root, a;
  4. vector<int> adj[51];
  5.  
  6. int dfs(int here){
  7. int ret = 0, child = 0;
  8. for(int there : adj[here]){
  9. if(there == tar) continue;
  10. ret += dfs(there);
  11. child++;
  12. }
  13. if(child == 0) return 1;
  14. return ret;
  15. }
  16.  
  17. int main(){
  18. cin >> n;
  19. for(int i = 0; i < n; i++){
  20. cin >> a;
  21. if(a == -1) root = i;
  22. else adj[a].push_back(i);
  23. }
  24. cin >> tar;
  25.  
  26. if(tar == root) cout << 0 << '\n';
  27. else cout << dfs(root) << '\n';
  28. }
Success #stdin #stdout 0s 5304KB
stdin
9
-1 0 0 2 2 4 4 6 6
4
stdout
2