题解:主席树裸题 查询第K小出现的下标
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <stack> #include <queue> #include <cmath> #include <set> #include <map> #define mp make_pair #define pb push_back #define pii pair<int,int> #define link(x) for(edge *j=h[x];j;j=j->next) #define inc(i,l,r) for(int i=l;i<=r;i++) #define dec(i,r,l) for(int i=r;i>=l;i--) const int MAXN=1e5+10; const int NM=2e3+10; const double eps=1e-8; #define ll long long using namespace std; struct edge{int t;edge*next;}e[MAXN<<1],*h[MAXN],*o=e; void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;} ll read(){ ll x=0,f=1;char ch=getchar(); while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); return x*f; } int p[MAXN],cnt,a[MAXN],fp[MAXN],num[MAXN],rt[MAXN]; vector<int>vec; int pos[MAXN]; void dfs(int x,int fa){ p[x]=++cnt;fp[p[x]]=x;num[x]=1; link(x){ if(j->t!=fa)dfs(j->t,x),num[x]+=num[j->t]; } } typedef struct node{ int l,r,sum; }node; node d[21*MAXN]; void update(int &x,int y,int l,int r,int t){ x=++cnt;d[x]=d[y];d[x].sum++; if(l==r)return ; int mid=(l+r)>>1; if(t<=mid)update(d[x].l,d[y].l,l,mid,t); else update(d[x].r,d[y].r,mid+1,r,t); } int ans; void querty(int x,int y,int l,int r,int k){ if(l==r){ans=l;return ;} int mid=(l+r)>>1; int t=d[d[y].l].sum-d[d[x].l].sum; if(k<=t)querty(d[x].l,d[y].l,l,mid,k); else querty(d[x].r,d[y].r,mid+1,r,k-t); } int main(){ int n;n=read(); inc(i,1,n)a[i]=read(),vec.pb(a[i]); sort(vec.begin(),vec.end()); int sz=unique(vec.begin(),vec.end())-vec.begin(); inc(i,1,n)a[i]=lower_bound(vec.begin(),vec.begin()+sz,a[i])-vec.begin()+1,pos[a[i]]=i; int u,v; inc(i,1,n-1)u=read(),v=read(),add(u,v),add(v,u); dfs(1,0); inc(i,1,n)update(rt[i],rt[i-1],1,sz,a[fp[i]]); int m=read(); while(m--){ u=read();v=read(); querty(rt[p[u]-1],rt[p[u]+num[u]-1],1,sz,v); printf("%d ",pos[ans]); } }
1803: Spoj1487 Query on a tree III
Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 760 Solved: 329
[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