E. Kth subtree
2016-2017 7th BSUIR Open Programming Contest. Semifinal
http://codeforces.com/gym/102134/problem/E
E. Kth subtree
time limit per test
2.0 s
memory limit per test
256 MB
input
standard input
output
standard output
Legends for tasks are different. There are long or short. There are boring or funny. There are understandable or not. You decide what this. Given a tree from n vertices. Also given are q queries. One query is a pair of numbers v and k. We choose v as a root and write down the sizes of the subtrees of each vertex of the tree in the nondecreasing order. The answer to the query is the k th number in this list.
Input
The first line of input contains two numbers - n and q (1 ≤ n ≤ 105, 1 ≤ q ≤ 105). Each of the following n - 1 rows contains a description of the edge of the tree - its ends ui and vi (1 ≤ ui, vi ≤ n) Each of the following q lines contains a description of the next query - the numbers vi and ki (1 ≤ vi, ki ≤ n)
Output
Output a response to each of the requests on a separate line.
Example
input
Copy
5 5 1 2 1 3 1 4 4 5 2 5 1 3 4 4 2 3 2 2
output
Copy
5 1 3 2 1
给你n个点 给你n-1条无向边,形成一棵树
在进行q次查询(q<=1e5)
问你以x为根节点,把所有节点的子数大小(包括自己)从小到大排列的第k大是多少
dfs预处理以1为根节点的每个节点的size,插入线段树中
因为发现每次换节点只有一个数实际改变了,就更新
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int tree[maxn*4],cnt[maxn],son[maxn];
vector <int> G[maxn],Id[maxn],k_th[maxn];
int n,q;
void update(int k,int c,int l,int r,int rt)
{
if(l==r)
{
tree[rt]+=c;
return;
}
int mid=(l+r)/2;
if(k<=mid) update(k,c,l,mid,2*rt);
else update(k,c,mid+1,r,2*rt+1);
tree[rt]=tree[rt*2]+tree[2*rt+1];
}
int query(int k,int l,int r,int rt)
{
if(l==r)
return l; //第k个大小是l
int mid=(l+r)/2;
if(k<=tree[2*rt]) query(k,l,mid,2*rt); //如果左子树有>=k个,那么就找左子树
else query(k-tree[2*rt],mid+1,r,2*rt+1); //不然减去整个左子树的大小,找右子树的第k-tree[2*rt]个
}
void dfs1(int u,int fa)
{
son[u]=1;
int sz=G[u].size();
for(int i=0;i<sz;i++)
{
int v=G[u][i];
if(v==fa) continue;
dfs1(v,u);
son[u]+=son[v];
}
update(son[u],1,1,n,1); //每确定一个点的子数个数,就建树
}
void dfs2(int u,int fa)
{
int sz=k_th[u].size();
for(int i=0;i<sz;i++)
{
int id=Id[u][i];
int k=k_th[u][i];
cnt[id]=query(k,1,n,1);
}
sz=G[u].size();
for(int i=0;i<sz;i++)
{
int v=G[u][i];
if(v==fa) continue;
update(son[v],-1,1,n,1); //先改掉 ,每次换根实际只会将一个数改变
update(n-son[v],1,1,n,1);
dfs2(v,u);
update(son[v],1,1,n,1); //再变回来
update(n-son[v],-1,1,n,1);
}
}
int main()
{
int u,v;
scanf("%d%d",&n,&q);
for(int i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=q;i++)
{
scanf("%d%d",&u,&v);
Id[u].push_back(i);
k_th[u].push_back(v);
}
dfs1(1,0);
dfs2(1,0);
for(int i=1;i<=q;i++)
printf("%d\n",cnt[i]);
return 0;
}