第1
2026-02-01 15:58:07
发布于:浙江
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
struct Fenwick {
int n;
vector<long long> bit;
Fenwick(int n_) : n(n_), bit(n_ + 2, 0) {}
void add(int i, long long delta) {
for (; i <= n; i += i & -i) {
bit[i] += delta;
}
}
long long sum(int i) {
long long s = 0;
for (; i > 0; i -= i & -i) {
s += bit[i];
}
return s;
}
void range_add(int l, int r, long long x) {
add(l, x);
add(r + 1, -x);
}
long long point_query(int i) {
return sum(i);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
int q;
cin >> q;
// Maximum nodes: 1 + number of type-1 operations <= q + 1
int maxn = q + 2;
vector<vector<int>> children(maxn);
vector<int> create_time(maxn, -1);
create_time[1] = 0; // node 1 exists before any operation
int n = 1;
// Record all type-2 operations: (time, v, x)
vector<tuple<int, int, long long>> adds;
for (int op_idx = 1; op_idx <= q; op_idx++) {
int t, v;
cin >> t >> v;
if (t == 1) {
n++;
children[v].push_back(n);
create_time[n] = op_idx;
} else {
long long x;
cin >> x;
adds.emplace_back(op_idx, v, x);
}
}
// DFS to get in[] and out[]
vector<int> in(maxn), out(maxn);
int timer = 0;
function<void(int)> dfs = [&](int u) {
in[u] = ++timer;
for (int v : children[u]) {
dfs(v);
}
out[u] = timer;
};
dfs(1);
// Prepare queries: each node u is a query
vector<int> nodes;
for (int i = 1; i <= n; i++) {
nodes.push_back(i);
}
// Sort nodes by create_time DESCENDING
sort(nodes.begin(), nodes.end(), [&](int a, int b) {
return create_time[a] > create_time[b];
});
// Sort add operations by time DESCENDING
sort(adds.begin(), adds.end(), [](const auto& A, const auto& B) {
return get<0>(A) > get<0>(B);
});
// Offline processing with Fenwick tree over DFS order
Fenwick fenw(timer);
vector<long long> ans(n + 1, 0);
size_t j = 0;
for (int u : nodes) {
int ct = create_time[u];
// Add all operations that happened AFTER u was created (time > ct)
while (j < adds.size() && get<0>(adds[j]) > ct) {
auto [time, v, x] = adds[j];
fenw.range_add(in[v], out[v], x);
j++;
}
ans[u] = fenw.point_query(in[u]);
}
// Output
for (int i = 1; i <= n; i++) {
cout << ans[i];
if (i < n) cout << ' ';
else cout << '\n';
}
}
return 0;
}
这里空空如也







有帮助,赞一个