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
65
66
67
68
69
70
71
72
73
74
| // 더 많은 정보는 42jerrykim.github.io 에서 확인하세요.
#include <bits/stdc++.h>
using namespace std;
struct Fenwick {
vector<long long> bit;
int n;
Fenwick(int n) : n(n) { bit.assign(n + 1, 0); }
void add(int idx, long long delta) {
for (; idx <= n; idx += idx & -idx) bit[idx] += delta;
}
long long sumPrefix(int idx) const {
long long res = 0;
for (; idx > 0; idx -= idx & -idx) res += bit[idx];
return res;
}
long long sumRange(int l, int r) const {
if (l > r) return 0;
return sumPrefix(r) - sumPrefix(l - 1);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int numCities, capital;
if (!(cin >> numCities >> capital)) return 0;
vector<vector<int>> adjacency(numCities + 1);
for (int i = 0; i < numCities - 1; ++i) {
int x, y; cin >> x >> y;
adjacency[x].push_back(y);
adjacency[y].push_back(x);
}
vector<int> tin(numCities + 1), tout(numCities + 1), depth(numCities + 1, 0), parent(numCities + 1, 0);
int timer = 0;
// Iterative DFS for Euler tour and depths
stack<tuple<int, int, int>> dfsStack; // node, parent, state(0=enter,1=exit)
dfsStack.emplace(capital, 0, 0);
while (!dfsStack.empty()) {
auto [node, par, state] = dfsStack.top();
dfsStack.pop();
if (state == 0) {
parent[node] = par;
tin[node] = ++timer;
dfsStack.emplace(node, par, 1);
for (int neighbor : adjacency[node]) {
if (neighbor == par) continue;
depth[neighbor] = depth[node] + 1;
dfsStack.emplace(neighbor, node, 0);
}
} else {
tout[node] = timer;
}
}
Fenwick fenwick(numCities + 2);
int numQueries; cin >> numQueries;
for (int i = 0; i < numQueries; ++i) {
int queryType, city; cin >> queryType >> city;
if (queryType == 1) {
fenwick.add(tin[city], 1);
} else {
long long countInSubtree = fenwick.sumRange(tin[city], tout[city]);
long long answer = countInSubtree * (static_cast<long long>(depth[city]) + 1LL);
cout << answer << '\n';
}
}
return 0;
}
|