BOJ14267: 내리 칭찬

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

  • Tree 기반 DP의 출발선 같은 느낌. 그냥 쉬웠음
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
#include <bits/stdc++.h>
using namespace std;

class Tree {
  int N, M;
  vector<int> boss;
  vector<int> score;
  vector<vector<int>> adj;
public:
  Tree(int n, int m): N(n), M(m), adj(n+1), boss(n+1), score(n+1) {}
  void input();
  void dfs(int n);
  void print();
};

void Tree::input() {
  for(int i = 1; i <= N; i++) {
    cin >> boss[i];
    if(i != 1) adj[boss[i]].push_back(i);
  }
  for(int i = 1; i <= M; i++) {
    int n, s;
    cin >> n >> s;
    score[n] += s;
  }
}

void Tree::dfs(int n) {
  if(n != 1)
    score[n] += score[boss[n]];
  for(int near: adj[n])
    dfs(near);
}

void Tree::print() {
  for(int i = 1; i <= N; i++)
    printf("%d ", score[i]);
}

int main() {
  ios::sync_with_stdio(false);
  int N, M;
  cin >> N >> M;
  Tree tree(N, M);
  tree.input();
  tree.dfs(1);
  tree.print();
}