백준 1068 트리
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N;
cin >> N;
vector<int> parent(N, -1);
vector<int> valid(N, 1);
for (int i = 0; i < N; ++i) {
int input;
cin >> input;
parent[i] = input;
}
int rm;
cin >> rm;
queue<int> q;
q.push(rm);
while (!q.empty()) {
int node = q.front();
q.pop();
valid[node] = 0;
for (int i = 0; i < N; ++i) {
if (parent[i] == node) {
q.push(i);
}
}
}
int leafCnt = 0;
for (int i = 0; i < N; ++i) {
if (!valid[i]) continue;
bool haveChild = false;
for (int j = 0; j < N; ++j) {
if (!valid[j]) continue;
if (parent[j] == i) {
haveChild = true;
break;
}
}
if (!haveChild) leafCnt++;
}
cout << leafCnt;
return 0;
}