题目链接 SP1487 PT07J - Query on a tree III
因为是查询子树信息,查询子树第K小问题,首先,想到的是用主席树来维护一下,然后,在子树内的话,那么可以根据dfs序来维护这个性质,要求子树内的第K小,直接dfs扫过去,然后相当于是一个子树差分来解决这个问题了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define eps 1e-4
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, Q, head[maxN], cnt, a[maxN], Lsan[maxN], _UP, rid[maxN];
struct Eddge
{
int nex, to;
Eddge(int a=-1, int b=0):nex(a), to(b) {}
}edge[maxN << 1];
inline void addEddge(int u, int v)
{
edge[cnt] = Eddge(head[u], v);
head[u] = cnt++;
}
inline void _add(int u, int v) { addEddge(u, v); addEddge(v, u); }
struct Tree
{
int ch[2], siz;
Tree() { ch[0] = ch[1] = 0; siz = 0; }
} t[maxN * 30];
int root[maxN], tot;
void Insert(int &rt, int old, int l, int r, int qx)
{
rt = ++tot;
t[rt] = t[old]; t[rt].siz++;
if(l == r) return;
int mid = HalF;
if(qx <= mid) Insert(t[rt].ch[0], t[old].ch[0], l, mid, qx);
else Insert(t[rt].ch[1], t[old].ch[1], mid + 1, r, qx);
}
int query(int tl, int tr, int l, int r, int kth)
{
if(l == r) return l;
int num = t[t[tr].ch[0]].siz - t[t[tl].ch[0]].siz;
int mid = HalF;
if(kth <= num) return query(t[tl].ch[0], t[tr].ch[0], l, mid, kth);
else return query(t[tl].ch[1], t[tr].ch[1], mid + 1, r, kth - num);
}
int st[maxN], _id, ed[maxN];
void dfs(int u, int fa)
{
st[u] = ++_id;
Insert(root[_id], root[_id - 1], 1, _UP, a[u]);
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
if(v == fa) continue;
dfs(v, u);
}
ed[u] = _id;
}
inline void init()
{
cnt = 0; tot = 0; _id = 0;
for(int i=1; i<=N; i++) head[i] = -1;
}
int main()
{
scanf("%d", &N);
init();
for(int i=1; i<=N; i++) { scanf("%d", &a[i]); Lsan[i] = a[i]; }
sort(Lsan + 1, Lsan + N + 1);
_UP = (int)(unique(Lsan + 1, Lsan + N + 1) - Lsan - 1);
for(int i=1; i<=N; i++) { a[i] = (int)(lower_bound(Lsan + 1, Lsan + _UP + 1, a[i]) - Lsan); rid[a[i]] = i; }
for(int i=1, u, v; i<N; i++)
{
scanf("%d%d", &u, &v);
_add(u, v);
}
dfs(1, 0);
scanf("%d", &Q);
int u, kth;
while(Q--)
{
scanf("%d%d", &u, &kth);
printf("%d\n", rid[query(root[st[u] - 1], root[ed[u]], 1, _UP, kth)]);
}
return 0;
}