[BOJ] 18227 성대나라의 물탱크

성대나라의 물탱크

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
64
#include <bits/stdc++.h>
#define MAX_N 200001

using namespace std;
int n, m, no = 0;

int in[MAX_N], out[MAX_N];
int level[MAX_N];
int fenwick[MAX_N + 1];
bool vis[MAX_N];
vector<int> adj[MAX_N];

void dfs(int u, int lvl) {
level[u] = lvl;
in[u] = ++no;
vis[u] = true;
for(auto& v : adj[u]) {
if(!vis[v])
dfs(v, lvl + 1);
}
out[u] = no;
}

void ott(int root) {
dfs(root, 1);
}

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

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

int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int op, u, v, root;
scanf("%d%d",&n,&root);
for(int i = 1; i < n; i++) {
scanf("%d%d",&u,&v);
adj[u].push_back(v);
adj[v].push_back(u);
}

ott(root);
scanf("%d",&m);
while(m--) {
scanf("%d%d",&op,&u);
if(op == 1) {
update(in[u], 1);
} else {
printf("%lld\n",1ll * level[u] * (query(out[u]) - query(in[u] - 1)));
}
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/20/PS/BOJ/18227/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.