问树上点对间的第k大。
对每个点维护到根的路径上的权值情况,分别建立权值线段树,为了压缩内存利用可持久化线段树即可。
#include <cstdio>
#include <algorithm>
using namespace std;
#define FOR(i,j,k) for(i=j;i<=k;++i)
const int N = 100005, M = N, K = 16;
struct Seg {
Seg *lc, *rc;
int s;
Seg() { lc = rc = this; s = 0; }
Seg(Seg *_l, Seg *_r, int _s) : lc(_l), rc(_r), s(_s) {}
void *operator new(size_t) {
static Seg pool[M * 60], *C = pool;
return C++;
}
Seg *put(int l, int r, int pos) {
int mid = l + r >> 1;
if (l == r) return new Seg(lc, rc, s + 1);
else if (pos <= mid) return new Seg(lc->put(l, mid, pos), rc, s + 1);
else return new Seg(lc, rc->put(mid + 1, r, pos), s + 1);
}
} *tree[M];
int dep[N], pos[N], fa[N][20], id[N], a[N], b[N], ts;
int h[N], p[M], v[M], cnt = 0;
void add(int a, int b) { p[++cnt] = h[a]; v[cnt] = b; h[a] = cnt; }
void dfs(int x, int f) {
int i;
pos[x] = ++ts; id[ts] = x; fa[x][0] = f; dep[x] = dep[f] + 1;
FOR(i,1,K) fa[x][i] = fa[fa[x][i - 1]][i - 1];
for (i = h[x]; i; i = p[i])
if (v[i] != f) dfs(v[i], x);
}
int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
int t = dep[x] - dep[y], i;
FOR(i,0,K) if ((1 << i) & t) x = fa[x][i];
for(i=K;i>=0;--i) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return x == y ? x : fa[x][0];
}
int main() {
int n, m, i, p, q, c, d, rk, l, r, uni, last = 0;
scanf("%d%d", &n, &m);
FOR(i,1,n) scanf("%d", &a[i]), b[i] = a[i];
sort(b + 1, b + n + 1); uni = unique(b + 1, b + n + 1) - (b + 1);
FOR(i,1,n) a[i] = lower_bound(b + 1, b + uni + 1, a[i]) - b;
FOR(i,2,n) scanf("%d%d", &p, &q), add(p, q), add(q, p);
dfs(1, 0);
tree[0] = new Seg();
FOR(i,1,n) tree[i] = tree[pos[fa[id[i]][0]]]->put(1, n, a[id[i]]);
FOR(i,1,m) {
scanf("%d%d%d", &p, &q, &rk);
//p ^= last;
c = lca(p, q); d = fa[c][0];
Seg *x = tree[pos[p]], *y = tree[pos[q]], *z = tree[pos[c]], *w = tree[pos[d]];
l = 1; r = uni;
while (l < r) {
int mid = l + r >> 1;
int t = x->lc->s + y->lc->s - z->lc->s - w->lc->s;
if (t >= rk) r = mid, x = x->lc, y = y->lc, z = z->lc, w = w->lc;
else rk -= t, l = mid + 1, x = x->rc, y = y->rc, z = z->rc, w = w->rc;
}
printf("%d", last = b[l]);
if (i != m) putchar('\n');
}
return 0;
}
COT - Count on a tree
no tags
You are given a tree with N nodes.The tree nodes are numbered from 1 to N.Each node has an integer weight.
We will ask you to perform the following operation:
u v k : ask for the kth minimum weight on the path from node u to node v
Input
In the first line there are two integers N and M.(N,M<=100000)
In the second line there are N integers.The ith integer denotes the weight of the ith node.
In the next N-1 lines,each line contains two integers u v,which describes an edge (u,v).
In the next M lines,each line contains three integers u v k,which means an operation asking for the kth minimum weight on the path from node u to node v.
Output
For each operation,print its result.
Example
Input:
8 58 5
105 2 9 3 8 5 7 7
1 2
1 3
1 4
3 5
3 6
3 7
4 8
2 5 1
2 5 2
2 5 3
2 5 4
7 8 2
Output:
2
8
9
105
7