题解:AT_abc409_f [ABC409F] Connecting Points
wizard_Marshall · · 题解
题意
维护若干个集合,每个集合里是一堆二维数点。两个集合
维护以下三个操作:
-
1 a b在一个新的集合中加入点对(a,b) -
2输出两个集合间的最小距离,并将这样的两个集合合并(不唯一,如d(S_1,S_3)=d(S_1,S_2) 则三个集合一起合并) -
3 x y判断x 和y 在不在一个集合里
思路
首先看到集合合并、询问这种就把并查集扔上去了,并查集可以做到操作 1 和 3,以及 2 的合并部分。这个过程中简单维护联通块个数。
然后思考如何找到最小距离。由于
合并的时候,不能简单取队头,而是要先把已经在同一集合的点对 pop 出去,因为它们之前已经合并过了。然后把队头几个最小距离的点对所属的集合用并查集合并即可。
这样就做完了。
代码
听说使用 set 会被卡。
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, r, l) for (int i = r; i >= l; i--)
pair <int, int> p[3005];
int fa[3005];
int find(int x) {
if (fa[x] == x)return x;
return fa[x] = find(fa[x]);
}
signed main() {
int n, q;
cin >> n >> q;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &p[i].first, &p[i].second);
fa[i] = i;
}
priority_queue <pair <int, pair <int, int> > > que;
rep(i, 1, n) {
rep(j, i + 1, n) {
que.push({-abs(p[i].first - p[j].first) - abs(p[i].second - p[j].second), {i, j}});
}
}
int bcnt = n;//联通块个数
while (q--) {
int op;
scanf("%d", &op);
if (op == 1) {
int x, y;scanf("%d%d", &x, &y);
p[++n] = {x, y};
fa[n] = n;
bcnt++;
rep(i, 1, n - 1) {
que.push({-abs(p[n].first - p[i].first) - abs(p[n].second - p[i].second), {n, i}});
}
}else if (op == 2) {
if (bcnt == 1) {
printf("-1\n");continue;
}
while (find(que.top().second.first) == find(que.top().second.second)) {//相同的点对pop掉
que.pop();
}
int tp = -que.top().first;
while (!que.empty() && que.top().first == -tp) {
int x = que.top().second.first, y = que.top().second.second;
int fx = find(x), fy = find(y);
if (fx != fy) {
fa[fx] = fy;
bcnt--;
}
que.pop();
}
printf("%d\n", tp);
}else {
int x, y;
scanf("%d%d", &x, &y);
int fx = find(x), fy = find(y);
if (fx == fy) {
printf("Yes\n");
}else {
printf("No\n");
}
}
}
return 0;
}