BOJ19542: 전단지 돌리기

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

  • 바운드 처리 잘하기. 아래에서부터 depth를 계산하는 문제.
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
#include <bits/stdc++.h>
using namespace std;

class Tree {
  int N, D, ans = 0;
  vector<vector<int>> adj;
public:
  Tree(int n, int d): N(n), D(d), adj(n+1) {}
  void input();
  int dfs(int u, int p);
  int getAns() { return ans; }
};

void Tree::input() {
  for(int i = 0; i < N - 1; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
}

int Tree::dfs(int u, int p) {
  int depth = 0;
  for (int v : adj[u])
    if(v != p)
      depth = max(depth, dfs(v, u) + 1);
  if (depth >= D)
    ans++;
  return depth;
}

int main() {
  int N, S, D;
  scanf("%d%d%d", &N, &S, &D);
  Tree tree(N, D);
  tree.input();
  tree.dfs(S, -1);
  int ans = tree.getAns();
  if(ans <= 1) ans = 1;
  cout << (2 * ans  - 2);
}