[AGC002D] Stamp Rally
题意
给定一张无向图,\(q\) 次询问从 \(x, y\) 出发,经过 \(z\) 个点,可以重复经过每个点只算一次,求经过的边最大编号最小是多少。
\(n, q \le 10 ^ 5\)。
Sol
先建出瓶颈生成树,问题变成树上瓶颈连通块?
似乎除了可持久化并查集没有其他做法。
首先根号做法显然,维护 \(\sqrt n\) 个并查集,暴力枚举在哪个块,哪个位置。
考虑 \(\texttt{Kruskal}\) 重构树。
首先最小生成树就是最小瓶颈生成树的充分条件。
其次在连接 \((x, y, z)\) 时,考虑新建一个节点将 \(x\) 挂在左儿子,\(y\) 挂在右儿子。
这样瓶颈连通块就变为子树叶节点数,求个 \(\texttt{LCA}\),套一个二分答案就做完了。
注意事实上这样建出来的并不是完全二叉树,树高并不是 \(log\),并不像点分树这样优美。
赛场上实际可以手搓构造方式满足上述限制。
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#include <assert.h>
using namespace std;
#ifdef ONLINE_JUDGE
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;
#endif
int read() {
int p = 0, flg = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flg = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
p = p * 10 + c - '0';
c = getchar();
}
return p * flg;
}
void write(int x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9) {
write(x / 10);
}
putchar(x % 10 + '0');
}
bool _stmer;
const int N = 1e5 + 5, M = 2e5 + 5;
namespace Uni {
array <int, M> fa, siz;
int find(int x) {
if (x == fa[x]) return x;
return fa[x] = find(fa[x]);
}
void merge(int x, int y) {
int fx = find(x),
fy = find(y);
if (fx == fy) return;
siz[fy] += siz[fx], fa[fx] = fy;
}
void init(int n) {
for (int i = 1; i <= n; i++)
siz[fa[i] = i] = 1;
}
} //namespace Uni
namespace Kst {
array <array <int, 2>, M> ch;
array <int, M> len, siz;
int cnt;
array <array <int, 21>, M> fa;
void add(int x, int y, int z) {
if (Uni::find(x) == Uni::find(y)) return;
int fx = Uni::find(x), fy = Uni::find(y);
cnt++, Uni::fa[cnt] = cnt;
ch[cnt][0] = fx, ch[cnt][1] = fy;
fa[fx][0] = fa[fy][0] = cnt;
Uni::merge(x, y), Uni::merge(y, cnt);
len[cnt] = z, siz[cnt] = Uni::siz[cnt];
}
void init() {
for (int j = 1; j <= 20; j++)
for (int i = 1; i <= cnt; i++)
fa[i][j] = fa[fa[i][j - 1]][j - 1];
len[0] = 1e9;
}
int check(int x, int y, int k) {
for (int i = 20; ~i; i--) {
if (len[fa[x][i]] <= k) x = fa[x][i];
if (len[fa[y][i]] <= k) y = fa[y][i];
}
return (siz[x] + siz[y]) / (1 + (x == y));
}
} //namespace Kst
bool _edmer;
int main() {
cerr << (&_stmer - &_edmer) / 1024.0 / 1024.0 << "MB\n";
int n = read(), m = read();
Uni::init(n), Kst::cnt = n;
for (int i = 1; i <= n; i++) Kst::siz[i] = 1;
for (int i = 1; i <= m; i++) {
int x = read(), y = read();
Kst::add(x, y, i);
}
Kst::init();
/* cerr << Kst::check(2, 4, 2) << endl; */
int q = read();
while (q--) {
int x = read(), y = read(), k = read();
int l = 1, r = m, ans = -1;
while (l <= r) {
int mid = (l + r) >> 1;
if (Kst::check(x, y, mid) >= k)
r = mid - 1, ans = mid;
else l = mid + 1;
}
assert(~ans);
write(ans), puts("");
}
return 0;
}