传送门
题目描述:给你一个树,每个点有权值,多次询问两点之间的链的第k小权值
掉入的坑:必须离散化,不离散化过不了,(第一反应用的二分答案,发现没有题目上没给数据范围,不离散化,会RE到死。。。)
解题思路:我们每次儿子的状态室友父亲更新过来,我们要如何得到这条链的信息呢?首先LCA我们肯定是会用到的,这和我们求树上一条链上的距离类似,这条链上的信息, 如果 a 和 b 为这条链的两个端点,那么这条链的信息:
附上代码:
///#include<bits/stdc++.h>
///#include<unordered_map>
///#include<unordered_set>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<bitset>
#include<set>
#include<stack>
#include<map>
#include<list>
#include<new>
#include<vector>
#define MT(a, b) memset(a,b,sizeof(a));
#define lowbit(x) (x&(-x));
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai = acos(-1.0);
const double E = 2.718281828459;
const ll mod = 20071027;
const ll INF = 0x3f3f3f3f3f3f;
const int maxn = 1e5 + 5;
struct node {
int ls, rs, cnt;
} p[maxn * 40];
int root[maxn], times;
void insert(int &now, int old, int l, int r, int x) {
now = ++times;
p[now] = p[old], p[now].cnt++;
if (l == r)
return;
int mid = (l + r) >> 1;
if (x <= mid)
insert(p[now].ls, p[old].ls, l, mid, x);
else
insert(p[now].rs, p[old].rs, mid + 1, r, x);
}
int query(int s, int e, int g, int fg, int l, int r, int k) {
if (l == r)
return l;
int mid = (l + r) >> 1;
int sub = p[p[s].ls].cnt + p[p[e].ls].cnt - p[p[g].ls].cnt - p[p[fg].ls].cnt;
if (k <= sub)
return query(p[s].ls, p[e].ls, p[g].ls, p[fg].ls, l, mid, k);
else
return query(p[s].rs, p[e].rs, p[g].rs, p[fg].rs, mid + 1, r, k - sub);
}
vector<int> q[maxn];
int value[maxn], grand[maxn][30], depth[maxn], N;
int ranks[maxn], d;
void dfs(int s, int pre) {
for (int i = 1; i <= N; i++) {
grand[s][i] = grand[grand[s][i - 1]][i - 1];
}
depth[s] = depth[pre] + 1;
insert(root[s], root[pre], 1, d, value[s]);
for (int i = 0, e; i < q[s].size(); i++) {
e = q[s][i];
if (e ^ pre) {
grand[e][0] = s;
dfs(e, s);
}
}
}
int get_lca(int a, int b) {
if (depth[a] > depth[b])
swap(a, b);
for (int i = N; i >= 0; i--)
if (depth[b] >= depth[a] && depth[grand[b][i]] >= depth[a])
b = grand[b][i];
for (int i = N; i >= 0; i--)
if (grand[a][i] ^ grand[b][i]) {
a = grand[a][i], b = grand[b][i];
}
return a == b ? a : grand[b][0];
}
void init(int n) {
N = log2(n);
memset(grand, 0, sizeof(grand));
times = 0;
depth[0] = -1;
}
int main() {
int n, op, s, e, c, k;
scanf("%d %d", &n, &op);
init(n);
for (int i = 1; i <= n; i++) {
scanf("%d", &value[i]), ranks[i] = value[i];
}
sort(ranks + 1, ranks + 1 + n);
d = unique(ranks + 1, ranks + 1 + n) - (ranks + 1);
for (int i = 1; i <= n; i++)
value[i] = lower_bound(ranks + 1, ranks + 1 + d, value[i]) - ranks;
for (int i = 1; i < n; i++) {
scanf("%d %d", &s, &e);
q[s].push_back(e);
q[e].push_back(s);
}
dfs(1, 0);
while (op--) {
scanf("%d %d %d", &s, &e, &k);
int x = get_lca(s, e);
printf("%d\n", ranks[query(root[s], root[e], root[x], root[grand[x][0]], 1, d, k)]);
}
}
/*
Iput:
7 7
4 10 2 2 5 5 4
1 2
2 3
3 4
4 5
5 6
6 7
1 7 1
1 7 2
1 7 3
1 7 4
1 7 5
1 7 6
1 7 7
Output:
2
2
4
4
5
5
10
*/