Zenurik @ 2019-11-02 13:38:34
rt,写的主席树,没觉得会爆空间啊
#include <bits/stdc++.h>
using namespace std;
namespace IO {
#define gc getchar
#define int long long
const int N = 3e5+10;
const int INF = ~0U>>1;
template <typename T>
inline void read(T &x) {
x = 0; T flag = 1;
char c = gc();
for(; !isdigit(c); c = gc()) if(c == '-') flag = -1;
for(; isdigit(c); c = gc()) x = (x<<3) + (x<<1) + (c^48);
x *= flag;
}
template <typename T, typename ...Args>
inline void read(T &x, Args &...args) {
read(x); read(args...);
}
#undef gc
} using namespace IO;
int n, q;
vector<int> G[N];
int dep[N], siz[N], dfn[N], DFN, maxdep = 1;
int L[N*20], R[N*20], sum[N*20], root[N], cnt;
namespace HJT {
int build(int l, int r) {
int p = ++cnt;
sum[p] = 0;
if(l < r) {
int mid = (l+r)>>1;
L[p] = build(l, mid);
R[p] = build(mid+1, r);
}
return p;
}
int insert(int old, int l, int r, int val, int pos) {
int p = ++cnt;
L[p] = L[old], R[p] = R[old], sum[p] = sum[old]+val;
if(l < r) {
int mid = (l+r)>>1;
if(pos <= mid) L[p] = insert(L[old], l, mid, val, pos);
else R[p] = insert(R[old], mid+1, r, val, pos);
}
return p;
}
int query(int x, int y, int l, int r, int dl, int dr) {
if(l == dl && r == dr) return sum[y] - sum[x];
int mid = (l+r)>>1, res = 0;
if(dl <= mid) res += query(L[x], L[y], l, mid, dl, dr);
if(dr > mid) res += query(R[x], R[y], mid+1, r, dl, dr);
return res;
}
}
void dfs1(int x) {
siz[x] = 1;
for(int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
if(dep[y]) continue;
dep[y] = dep[x]+1;
maxdep = max(maxdep, dep[y]);
dfs1(y);
siz[x] += siz[y];
}
}
void dfs2(int x) {
dfn[x] = ++DFN;
root[DFN] = HJT::insert(root[DFN-1], 1, maxdep, siz[x]-1, dep[x]);
for(int i = 0; i < G[x].size(); i++) {
int y = G[x][i];
if(dep[y] < dep[x]) continue;
dfs2(y);
}
}
signed main() {
read(n, q);
for(int i = 1, x, y; i < n; i++) read(x, y), G[x].push_back(y), G[y].push_back(x);
dep[1] = 1;
dfs1(1);
HJT::build(1, maxdep);
dfs2(1);
while(q--) {
int p, k, ans;
read(p, k);
ans = (siz[p]-1)*min(dep[p]-1, k);
ans += HJT::query(root[dfn[p]-1], root[dfn[p]+siz[p]-1], 1, maxdep, dep[p]+1, min(maxdep, dep[p]+k));
printf("%lld\n", ans);
}
return 0;
}
by Mayuri @ 2019-11-02 15:50:09
%%%%%
by asd369 @ 2019-11-05 17:01:02
@Mayuri
by Mayuri @ 2019-11-05 19:18:32
@asd369 %%%the husband of eighteen