BOJ9489: 사촌

https://www.acmicpc.net/problem/9489

  • Tree’s data structure
    • every nodes’ parent
    • adj list = ever nodes’ children
  • Don’t need to save every children, just size of children is enough to solve
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;

class Tree {
  int N, tmp;
  vector<int> nodes;
  unordered_map<int, int> parent;
  unordered_map<int, vector<int>> adj;
public:
  Tree(int n): N(n) {}
  void input();
  void makeGraph();
  void printCousin(int k);
};

void Tree::input() {
  nodes.push_back(0);
  for(int i = 0; i < N; i++) {
    cin >> tmp;
    nodes.push_back(tmp);
  }
}

void Tree::makeGraph() {
  int pp = 0, cp = 1;
  while(cp <= N) {
    parent[nodes[cp]] = nodes[pp];
    adj[nodes[pp]].push_back(nodes[cp]);
    if(nodes[cp+1] == nodes[cp]+1) cp++;
    else pp++, cp++;
  }
}

void Tree::printCousin(int k) {
  int gp = parent[parent[k]];
  vector<int> sons = adj[gp];
  int ans = 0;
  for(int son: sons)
    if(son != parent[k])
      ans += adj[son].size();
  printf("%d\n", ans);
}

int main() {
  int N, K;
  while(1) {
    cin >> N >> K;
    if (!N && !K) return 0;
    Tree tree(N);
    tree.input();
    tree.makeGraph();
    tree.printCousin(K);
  }
}