Skip to content

Instantly share code, notes, and snippets.

@surinoel
Created July 9, 2019 10:15
Show Gist options
  • Save surinoel/8d0aa30bfdcceea88ce469a9e97e249b to your computer and use it in GitHub Desktop.
Save surinoel/8d0aa30bfdcceea88ce469a9e97e249b to your computer and use it in GitHub Desktop.
#include <queue>
#include <vector>
#include <cstring>
#include <iostream>
using namespace std;
vector<int> tree[50];
int dist[50];
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, root;
cin >> n;
memset(dist, -1, sizeof(dist));
queue<int> q;
for (int i = 0; i < n; i++) {
int x; cin >> x;
if (x == -1) { // 루트 정보라면
root = i;
q.push(i);
dist[i] = 0; // queue에 바로 넣는다
}
else {
tree[x].push_back(i);
}
}
int m;
cin >> m;
if (root == m) { // 루트가 바로 지우는 정보라면 0을 출력
cout << 0 << '\n';
return 0;
}
int range = -1; // m이 지워지면서 그 조상 노드가 하나만 자식노드를 가지고 있다면 세야 한다
for (int i = 0; i < n; i++) {
for (int j = 0; j < tree[i].size(); j++) {
if (tree[i][j] == m && tree[i].size() == 1) {
range = i;
}
}
}
int ans = 0;
dist[m] = 1e5;
while (!q.empty()) {
int x = q.front();
q.pop();
for (int k = 0; k < tree[x].size(); k++) {
int y = tree[x][k];
if (dist[y] != -1) continue;
dist[y] = dist[x] + 1;
q.push(y);
}
}
for (int i = 0; i < n; i++) {
if ((tree[i].size() == 0 && dist[i] != -1 && i != m) || (i == range)) {
ans += 1;
}
}
cout << ans << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment