一棵树,每次询问某个点与他距离第k小的点。
询问数,点数1e5.
#include
#include
#include
#include
#include
using namespace std;
const int N = 5e4 + 10;
int n,m;
int final[N],nex[N*2],to[N*2],w[N*2],tot;
void link(int a,int b,int ww){
to[++tot] = b, nex[tot] = final[a], final[a] = tot;
w[tot] = ww;
}
int fa[N],bz[N],size[N],dtf[N],ds[N][20];
vector<int> dis[N],dis2[N],T,T2;
int allsize,mxsz;
void getsize(int x,int from) {
size[x] = 1;
for (int i = final[x]; i; i=nex[i]) {
int y = to[i];
if (!bz[y] && y != from) {
getsize(y,x);
size[x] += size[y];
}
}
}
void findHeavy(int x,int from,int &hvy) {
int mx = 0;
for (int i = final[x]; i; i=nex[i]) {
int y = to[i];
if (!bz[y] && y != from) {
findHeavy(y,x,hvy);
mx=max(size[y],mx);
}
}
if (max(allsize-size[x],mx) < mxsz) {
hvy = x;
mxsz = max(allsize-size[x],mx);
}
}
int DEP;
void dfs(int x,int from,int d) {
T.push_back(d); T2.push_back(ds[x][DEP-1]);
ds[x][DEP] = d;
for (int i = final[x]; i; i=nex[i]) {
int y = to[i];
if (!bz[y] && y != from) {
dfs(y,x,d+w[i]);
}
}
}
int ddep[N];
void solve(int x,int last) {
// printf("%d\n",x);
getsize(x,0);
int hvy = 0; allsize = size[x]; mxsz = 1e9;
findHeavy(x,0,hvy);
fa[hvy] = last;
ddep[hvy] = ddep[last] + 1;
DEP = ddep[hvy];
T.clear(); T2.clear();
dfs(hvy,0,0);
sort(T.begin(),T.end()); sort(T2.begin(),T2.end());
dis[hvy] = T;
dis2[hvy] = T2; bz[hvy] = 1;
for (int i = final[hvy]; i; i=nex[i]){
int y = to[i];
if (!bz[y]) {
solve(y,hvy);
}
}
}
int U,K;
#define DEBUG 0
bool can(int mid) {
int ret = -1;
int a = U;
for (int i = ddep[U]; ~i; i--,a=fa[a]) {
int zd = mid - ds[U][i];
if (DEBUG) {
for (int i = 0; i < dis[a].size(); i++)
printf("%d ",dis[a][i]);
putchar('\n');
}
ret += upper_bound(dis[a].begin(),dis[a].end(),zd) - dis[a].begin();
if (i!=0) {
zd = mid - ds[U][i-1];
if (DEBUG) {
for (int i = 0; i < dis2[a].size(); i++)
printf("%d ",dis2[a][i]);
putchar('\n');
}
ret -= upper_bound(dis2[a].begin(),dis2[a].end(),zd) - dis2[a].begin();
}
}
return ret < K;
}
int main() {
freopen("tree.in","r",stdin);
// freopen("tree.out","w",stdout);
cin>>n>>m;
for (int i = 1; i < n; i++) {
int u,v,c;
scanf("%d %d %d",&u,&v,&c);
link(u,v,c), link(v,u,c);
}
ddep[0] = -1;
solve(1,0);
for (int i = 1; i <= m; i++) {
scanf("%d %d",&U,&K);
int ans = 0;
for (int c = (1<<29); c; c>>=1)
if (can(ans+c))
ans += c;
printf("%d\n",ans+1);
}
}