fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n, tar, a, root;
  4. vector<int> adj[51];
  5.  
  6. int dfs(int here){
  7. if(adj[here].size() == 0) return 1;
  8. int cnt = 0;
  9. for(int i = 0; i < adj[here].size(); i++){
  10. int there = adj[here][i];
  11. if(there == tar) continue;
  12. cnt += dfs(there);
  13. }
  14. return cnt;
  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. cout << dfs(root) << '\n';
  27. }
Success #stdin #stdout 0s 5312KB
stdin
9
-1 0 0 2 2 4 4 6 6
4
stdout
2