[BOJ] 14268 회사 문화2

회사 문화2

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
55
56
57
58
59
60
61
62
63
#include <bits/stdc++.h>

#define MAX_N 100001
using namespace std;

int fenwick[MAX_N + 1];
int p[MAX_N + 1], sub[MAX_N + 1], treeNo[MAX_N + 1];
vector<int> adj[MAX_N + 1];
int n, m, op, root;

void update(int u, int val) {
while(u <= n + 1) {
fenwick[u] += val;
u += u & -u;
}
}

int qry(int u) {
int res = 0;
while(u > 0) {
res += fenwick[u];
u -= u & -u;
}
return res;
}

int dfs(int u, int& no) {
sub[u] = 1;
treeNo[u] = no;
for(auto& v : adj[u])
sub[u] += dfs(v, ++no);

return sub[u];
}

void ott() {
for(int i = 1; i <= n; i++) {
if(p[i] == -1) root = i;
else adj[p[i]].push_back(i);
}
int no = 1;
dfs(root, no);
}

int main() {
cin>>n>>m;
for(int i = 1; i <= n; i++) cin>>p[i];
ott();
int u, val;
while(m--) {
cin>>op;
if(op == 1) {
cin>>u>>val;
update(treeNo[u], val);
update(treeNo[u] + sub[u], -val);
} else {
cin>>u;
cout<<qry(treeNo[u])<<endl;
}
}

return 0;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/19/PS/BOJ/14268/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.