Set SZ as the subtree size, the root depth is 1.
Obviously the answer is min (Dep[p]-1, k) * (Sz[p]-1) + sigma (Sz[u], u in sub-tree of P, Dep[u]-dep[p] <= k)
For the right side of the plus sign, the two-interval constraint asks for information, which can be considered to persist the segment tree, but the information between different versions must satisfy the interval subtraction.
Specifically, the DFS sequence is outside or deep in the outside no matter (depth maximum <=n, so with the depth constant will be small?) )
1#include <cstdio>2#include <cstdlib>3#include <algorithm>4#include <iostream>5#include <cstring>6#include <string>7 8 using namespacestd;9 Ten voidSetio (Const string&a) { OneFreopen ((A +". in"). C_STR (),"R", stdin); AFreopen ((A +". out"). C_STR (),"W", stdout); - } - thetypedefLong LongLL; - Const intN =300000+Ten, Logn = -; - - structNode *pis, *NULL; + - structNode { + LL S; Anode* ch[2]; at -Node (LL s =0): s (s) { -ch[0] = ch[1] =NULL; - } - - void*operator New(size_t) { in returnpis++; - } to}*root[n], Pool[n *Logn]; + - #defineMid (L + ((r-l) >> 1)) the #defineLS x->ch[0], y->ch[0], L, mid * #defineRS x->ch[1], y->ch[1], mid + 1, r $ Panax Notoginseng voidBuild (node*& x, Node *y,intLintRintKeyintval) { -x =NewNode (*y), x->s + =Val; the if(L = = r)return; + if(Key <= mid) build (LS, key, Val);ElseBuild (RS, Key, Val); A } the +LL Query (node *x, node *y,intLintRintLfTintRGT) { - if(LfT <= l && R <= RGT)returnY->s-x->s; $LL res =0; $ if(LfT <= mid) res + =query (LS, LFT, RGT); - if(Mid < RGT) Res + =query (RS, LFT, RGT); - returnRes; the } - Wuyi #undefMid the #undefLs - #undefRs Wu - intDfs_seq[n], pre[n], end[n], sz[n], dep[n], DFS_CLK, MAX_DEP; About $#include <vector> -vector<int>G[n]; - voidAddedge (intUintv) { - G[u].push_back (v); A g[v].push_back (u); + } the - voidDfsintu) { $MAX_DEP =Max (MAX_DEP, Dep[u]); theDFS_SEQ[++DFS_CLK] =u; thePre[u] =DFS_CLK; theSz[u] =1; the for(Unsigned i =0; I < g[u].size (); ++i) { - intv =G[u][i]; in if(Dep[v])Continue; theDEP[V] = Dep[u] +1; the Dfs (v); AboutSz[u] + =Sz[v]; the } theEnd[u] =DFS_CLK; the } + - intMain () { the #ifdef DEBUGBayiFreopen ("In.txt","R", stdin); theFreopen ("OUT.txt","W", stdout); the #endif - -PiS =Pool; the intN, M; thescanf"%d%d", &n, &m); the for(inti =1; I < n; i++) { the intu, v; -scanf"%d%d", &u, &v); the Addedge (U, v); the } the 94dep[1] =1, DFS (1); the the //cerr << max_dep << Endl; the 98root[0] =NULL=NewNode (0); About NULL->ch[0] =NULL->ch[1] =NULL; - 101 for(inti =1; I <= N; i++) {102Build (Root[i], root[i-1],1, MAX_DEP, Dep[dfs_seq[i]], Sz[dfs_seq[i]-1);103 }104 the for(inti =1; I <= m; i++) {106 intp, K;107scanf"%d%d", &p, &k);108ll res = (ll) min (Dep[p]-1, k) * (Sz[p]-1);109Res + = query (Root[pre[p], root[end[p]],1, MAX_DEP, Dep[p] +1, Min (Dep[p] +K, MAX_DEP)); theprintf"%lld\n", res);111 } the 113 return 0; the}
bzoj3653: Laughing