1803: Spoj1487 Query on a tree III
Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 537 Solved: 241
[ Submit][ Status][ Discuss]
Description
You are given a node-labeled rooted tree with n nodes. Define the query (x, k): Find the node whose label is k-th largest in the subtree of the node x. Assume no two nodes have the same labels.
Input
The first line contains one integer n (1 <= n <= 10^5). The next line contains n integers li (0 <= li <= 109) which denotes the label of the i-th node. Each line of the following n - 1 lines contains two integers u, v. They denote there is an edge between node u and node v. Node 1 is the root of the tree. The next line contains one integer m (1 <= m <= 10^4) which denotes the number of the queries. Each line of the next m contains two integers x, k. (k <= the total node number in the subtree of x)
Output
For each query (x, k), output the index of the node whose label is the k-th largest in the subtree of the node x.
Sample Input
5
1 3 5 2 7
1 2
2 3
1 4
3 5
4
2 3
4 1
3 2
3 2
1 3 5 2 7
1 2
2 3
1 4
3 5
4
2 3
4 1
3 2
3 2
Sample Output
5
4
5
5
HINT
Amber的play with tree系列的题....
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define N 200003
using namespace std;
int point[N],next[N],v[N],tot,n,num[N],m,cnt;
int root[N],val[N],a[N],l[N],q[N],r[N],sz,pos[N],b[N];
struct data
{
int l,r,w;
}tree[N*20];
void add(int x,int y)
{
tot++; next[tot]=point[x]; point[x]=tot; v[tot]=y;
tot++; next[tot]=point[y]; point[y]=tot; v[tot]=x;
}
int cmp(int x,int y)
{
return a[x]<a[y];
}
void dfs(int x,int fa)
{
q[++sz]=x; pos[x]=sz; l[x]=sz;
for (int i=point[x];i;i=next[i]){
if (v[i]==fa) continue;
dfs(v[i],x);
}
r[x]=sz;
}
void insert(int &i,int l,int r,int v)
{
tree[++sz]=tree[i]; i=sz;
tree[i].w++;
if (l==r) return;
int mid=(l+r)/2;
if (v<=mid) insert(tree[i].l,l,mid,v);
else insert(tree[i].r,mid+1,r,v);
}
int query(int i,int j,int l,int r,int k)
{
if (l==r) return l;
int t=tree[tree[j].l].w-tree[tree[i].l].w;
int mid=(l+r)/2;
if (t>=k) return query(tree[i].l,tree[j].l,l,mid,k);
else return query(tree[i].r,tree[j].r,mid+1,r,k-t);
}
int main()
{
freopen("a.in","r",stdin);
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=i;
sort(b+1,b+n+1,cmp);
val[b[1]]=++cnt; num[cnt]=b[1];
for (int i=2;i<=n;i++)
if (a[b[i]]!=a[b[i-1]])
val[b[i]]=++cnt,num[cnt]=b[i];
else val[b[i]]=cnt;
for (int i=1;i<n;i++){
int x,y; scanf("%d%d",&x,&y);
add(x,y);
}
dfs(1,0);
sz=0;
for (int i=1;i<=n;i++) {
root[i]=root[i-1];
insert(root[i],1,n,val[q[i]]);
}
scanf("%d",&m);
for (int i=1;i<=m;i++) {
int x,k; scanf("%d%d",&x,&k);
int t=query(root[l[x]-1],root[r[x]],1,n,k);
printf("%d\n",num[t]);
}
}