题意 : 给定一颗 N 个点的树,每条边都有一个边权 w ,然后是 Q 个询问,每个询问包含 一组 (Ai,Bi) ,问点 Ai 到点 Bi 的所有边权的中位数。
其中 2≤N≤5∗104,1≤Q≤105
分析:求中位数就相当于求区间第 K 大。考虑主席树,每个节点根据他的父节点的信息建树。每次根据 Ai,Bi,lca(Ai,Bi) 三颗树的信息求第 K 大。
以下是代码:
#include
using namespace std;
#define ll long long
#define ull unsigned long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
#define lll __int128;
typedef pair<int, int> pii;
typedef pair pll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int maxn = 50010;
const int MAXM = 100005;
const ll MOD = 998244353;
const double eps = 1e-8;
struct {
int lc, rc, sum;
}st[maxn * 40];
int rt[maxn], a[maxn], n, m = 100000, x, y, z, k, cnt;
int f[maxn][20];
int dep[maxn];
struct edge {
int v, cost;
edge(int _v = 0, int _cost = 0) :v(_v), cost(_cost) {}
};
vector vec[maxn];
void update(int l, int r, int &x, int y, int pos) {
st[++cnt] = st[y], st[cnt].sum++, x = cnt;
if (l == r)return;
int mid = (l + r) / 2;
if (pos <= mid)update(l, mid, st[x].lc, st[y].lc, pos);
else update(mid + 1, r, st[x].rc, st[y].rc, pos);
}
int query(int l, int r, int x, int y, int z, int k) {
if (l == r)return l;
int mid = (l + r) / 2;
int sum = st[st[y].lc].sum + st[st[x].lc].sum - 2 * st[st[z].lc].sum;
if (k <= sum)return query(l, mid, st[x].lc, st[y].lc, st[z].lc, k);
else return query(mid + 1, r, st[x].rc, st[y].rc, st[z].rc, k - sum);
}
void dfs(int u, int fa, int cur,int cost) {
dep[u] = cur;
f[u][0] = fa;
if (fa != 0) {
update(1, m, rt[u], rt[fa], cost);
}
for (int i = 0; i < vec[u].size(); ++i) {
int v = vec[u][i].v;
if (v == fa)continue;
dfs(v, u, cur + 1, vec[u][i].cost);
}
}
int getlca(int x, int y) {
if (dep[x] < dep[y])swap(x, y);
for (int i = 19; i >= 0; --i) {
if (dep[f[x][i]] >= dep[y]) {
x = f[x][i];
}
}
if (x == y)return x;
for (int i = 19; i >= 0; --i) {
if (f[x][i] != f[y][i]) {
x = f[x][i];
y = f[y][i];
}
}
return f[x][0];
}
int main() {
int T; scanf("%d", &T);
while (T--) {
memset(f, 0, sizeof(f));
scanf("%d", &n);
for (int i = 1; i <= n; ++i)vec[i].clear();
cnt = 0;
for (int i = 0; i < n - 1; ++i) {
scanf("%d%d%d", &x, &y, &z);
vec[x].push_back(edge(y, z));
vec[y].push_back(edge(x, z));
}
dfs(1, 0, 0, 0);
for (int i = 1; i <= 19; ++i) {
for (int j = 1; j <= n; ++j) {
f[j][i] = f[f[j][i - 1]][i - 1];
}
}
int q; scanf("%d", &q);
while (q--) {
scanf("%d%d", &x, &y);
int lca = getlca(x, y);
int len = dep[x] + dep[y] - 2 * dep[lca];
if (len & 1) {
printf("%d.0\n", query(1, m, rt[x], rt[y], rt[lca], len / 2 + 1));
}
else {
int res = query(1, m, rt[x], rt[y], rt[lca], len / 2) + query(1, m, rt[x], rt[y], rt[lca], len / 2 + 1);
printf("%.1f\n", res*1.0 / 2.0);
}
}
}
}