Hướng dẫn giải của Subtree Queries
Chỉ dùng lời giải này khi không có ý tưởng, và đừng copy-paste code từ lời giải này. Hãy tôn trọng người ra đề và người viết lời giải.
Nộp một lời giải chính thức trước khi tự giải là một hành động có thể bị ban.
Nộp một lời giải chính thức trước khi tự giải là một hành động có thể bị ban.
#include <bits/stdc++.h> using namespace std; template<class A, class B> bool maximize(A& x, B y) {if (x < y) return x = y, true; else return false;} template<class A, class B> bool minimize(A& x, B y) {if (x > y) return x = y, true; else return false;} #define all(a) a.begin(), a.end() #define pb push_back #define pf push_front #define fi first #define se second typedef long long ll; typedef unsigned long long ull; typedef double db; typedef long double ld; typedef pair<db, db> pdb; typedef pair<ld, ld> pld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<ll, int> plli; typedef pair<int, ll> pill; const int MAX_N = 2e5 + 5; int n, numQ; int a[MAX_N]; vector<int> adj[MAX_N]; int timeIn[MAX_N], timeOut[MAX_N], dfsTime; ll BIT[MAX_N]; void update(int id, int val) { while (id <= n) { BIT[id] += val; id += id & -id; } } ll get(int id) { ll ans = 0; while (id > 0) { ans += BIT[id]; id -= id & -id; } return ans; } ll getRange(const int& l, const int& r) { return get(r) - get(l - 1); } void prepare(int u, int pr = 0) { timeIn[u] = ++dfsTime; update(timeIn[u], a[u]); for (int v : adj[u]) { if (v == pr) continue; prepare(v, u); } timeOut[u] = dfsTime; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> numQ; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].pb(v); adj[v].pb(u); } prepare(1); while (numQ--) { char type; cin >> type; int s; cin >> s; if (type == '2') { cout << getRange(timeIn[s], timeOut[s]) << '\n'; continue; } int x; cin >> x; update(timeIn[s], -a[s] + x); a[s] = x; } return 0; } /* Saturday, 24 February 2024 21:33:45 */
Bình luận