有一些岛屿,一开始由一些无向边连接。后来也有不断的无向边加入,每一个岛屿有个一独一无二的重要度,问任意时刻的与一个岛屿联通的所有岛中重要度第k大的岛的编号是什么。
线段树合并裸题。
用并查集维护岛屿之间的连通性,对一个联通块内的岛屿建一棵权值线段树,合并联通块的同时合并两棵线段树。
抄了 学习了一发黄学长的线段树合并的板子。
#include
using namespace std;
const int Maxn = 100100;
int fa[Maxn], v[Maxn], id[Maxn];
inline char get(void) {
static char buf[1000000], *p1 = buf, *p2 = buf;
if (p1 == p2) {
p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);
if (p1 == p2) return EOF;
}
return *p1++;
}
inline void read(int &x) {
x = 0; static char c; bool minus = false;
for (; !(c >= '0' && c <= '9'); c = get()) if (c == '-') minus = true;
for (; c >= '0' && c <= '9'; x = x * 10 + c - '0', c = get()); if (minus) x = -x;
}
inline void read(char &x) {
x = get();
while (!(x >= 'A' && x <= 'Z')) x = get();
}
inline int getf(int x) {
return fa[x] = (x == fa[x] ? x : getf(fa[x]));
}
int root[Maxn * 20], ls[Maxn * 20], rs[Maxn * 20], sum[Maxn * 20], sz;
inline void insert(int &o, int l, int r, int val) {
if (!o) o = ++sz;
if (l == r) return (void)(sum[o] = 1);
int mid = (l + r) >> 1;
if (mid >= val) insert(ls[o], l, mid, val);
else insert(rs[o], mid + 1, r, val);
sum[o] = sum[ls[o]] + sum[rs[o]];
}
inline int query(int o, int l, int r, int rank) {
if (l >= r) return l;
int mid = (l + r) >> 1;
if (sum[ls[o]] >= rank) return query(ls[o], l, mid, rank);
else return query(rs[o], mid + 1, r, rank - sum[ls[o]]);
}
inline int merge(int x, int y) {
if (!x) return y;
if (!y) return x;
ls[x] = merge(ls[x], ls[y]);
rs[x] = merge(rs[x], rs[y]);
sum[x] = sum[ls[x]] + sum[rs[x]];
return x;
}
int n, m, k;
int main(void) {
// freopen("in.txt", "r", stdin);
read(n), read(m);
for (int i = 1; i <= n; i++) read(v[i]);
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1, x, y; i <= m; i++) {
read(x), read(y);
x = getf(x), y = getf(y);
fa[x] = y;
}
for (int i = 1; i <= n; i++) {
insert(root[getf(i)], 1, n, v[i]);
id[v[i]] = i;
}
read(k); char op; int x, y, p, q;
while (k--) {
read(op); read(x), read(y);
if (op == 'Q') {
p = getf(x);
if (sum[root[p]] < y) {
puts("-1");
continue;
}
printf("%d\n", id[query(root[p], 1, n, y)]);
} else {
p = getf(x), q = getf(y);
if (p == q) continue;
fa[p] = q;
root[q]= merge(root[p], root[q]);
}
}
return 0;
}
完。
By g1n0st