思路:
dfs序+树状数组+分块
先dfs处理好每个节点的时间戳
对于每一层,如果这一层的节点数小于sqrt(n),那么直接按照时间戳在树状数组上更新
如果这一层节点个数大于sqrt(n),那么直接存一下这一层每个节点的大小(都是一样的),这样的层数不会超过sqrt(n)层
然后查询的时候先在树状数组查询答案,然后再遍历第二种层数,加到答案中
复杂度:n*sqrt(n)*log(n)
代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pii pair<int, int>
#define piii pair<pii, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
//head const int N = 1e5 + ;
vector<int>g[N];
int in[N], out[N], deep[N], n, tot = ;
LL val[N], bit[N];
vector<int>dfn[N];
vector<int>big;
void add(int x, int v) {
while(x <= n) bit[x] += v, x += x&-x;
}
LL query(int x) {
LL ans = ;
while(x) ans += bit[x], x -= x&-x;
return ans;
}
void dfs(int o, int u, int d) {
deep[u] = d;
in[u] = ++tot;
dfn[d].pb(tot);
for (int v:g[u]) {
if(v != o) dfs(u, v, d+);
}
out[u] = tot;
}
int main() {
int q, u, v, blo, ty, l, x;
scanf("%d %d", &n, &q);
blo = sqrt(n);
for (int i = ; i < n; i++) {
scanf("%d %d", &u, &v);
g[u].pb(v);
g[v].pb(u);
}
dfs(, , );
for(int i = ; i < n; i++) {
if(dfn[i].size() > blo) big.pb(i);
}
while(q--) {
scanf("%d", &ty);
if(ty == ) {
scanf("%d %d", &l, &x);
if(dfn[l].size() <= blo) {
for (int i = ; i < dfn[l].size(); i++) {
add(dfn[l][i], x);
}
}
else val[l] += x;
}
else {
scanf("%d", &x);
LL ans = query(out[x]) - query(in[x]-);
for (int i = ; i < big.size(); i++) {
int d = big[i];
int t = upper_bound(dfn[d].begin(), dfn[d].end(), out[x]) - lower_bound(dfn[d].begin(), dfn[d].end(), in[x]);
ans += 1LL * t * val[d];
}
printf("%lld\n", ans);
}
}
return ;
}