CSES - Shared codeLink to this code:
https://cses.fi/paste/ad1580aed1b978c44f3cbd/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ar array
const ll mod=1e9+7;
const ll mxN=2e5;
class segTree{
ll N;
vector<ll> st;
public: segTree(ll n){
N=n;
st.resize(4*N+5);
}
void Build(vector<ll> a,ll node, ll L, ll R)
{
if (L == R)
{
st[node] = a[L];
return;
}
ll M = (L + R) / 2;
Build(a,node * 2 + 1, L, M);
Build(a,node * 2 + 2, M + 1, R);
st[node] = st[node * 2 + 1] + st[node * 2 + 2];
}
void Update(ll node, ll L, ll R, ll pos, ll val)
{
if (L == R)
{
st[node]= val;
return;
}
ll M = (L + R) / 2;
if (pos <= M)
Update(node * 2+1, L, M, pos, val);
else
Update(node * 2 + 2, M + 1, R, pos, val);
st[node] = st[node * 2+1]+st[node * 2 + 2];
}
ll Query(ll node, ll L, ll R, ll i, ll j)
{
if (j < L || i > R)
return 0;
if (i <= L && R <= j)
return st[node];
ll M = (L + R) / 2;
return Query(node * 2+1, L, M, i, j) + Query(node * 2 + 2, M + 1, R, i, j);
}
};
//tree
vector<ll> adj[mxN];
//weight of each node
ll val[mxN];
//dp[i][0] -> will store the in-time of ith node
//dp[i][1] -> will store the out-time of ith node
ll dp[mxN][2];
//time
ll t;
//flattened tree
vector<ll> a;
void dfs(ll u=0,ll p=-1){
dp[u][0]=t;
a.push_back(val[u]);
for(auto v:adj[u]){
if(v==p)continue;
t++;
dfs(v,u);
}
dp[u][1]=t;
}
void solve()
{
ll n,q;cin>>n,cin>>q;
for(ll i=0;i<n;i++)
cin>>val[i];
for(ll i=0;i<n-1;i++){
ll p,q;cin>>p>>q,--p,--q;
adj[p].push_back(q);
adj[q].push_back(p);
}
t=0;
dfs();
segTree st1(a.size());
st1.Build(a,0,0,n-1);
while(q--){
ll x;cin>>x;
if(x==1){
ll node,value;cin>>node>>value;
--node;
st1.Update(0,0,n-1,dp[node][0],value);
}
else{
ll node;cin>>node;
--node;
cout<<st1.Query(0,0,n-1,dp[node][0],dp[node][1])<<"\n";
}
}
}
int main()
{
solve();
return 0;
}