/
manhattan_mst.hpp
45 lines (41 loc) · 1.14 KB
/
manhattan_mst.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "graph/base.hpp"
#include "ds/unionfind/unionfind.hpp"
// 最小全域木を作るので、特に各点からの最近点をとる目的で使うこともできる
template <typename T>
Graph<T, 0> manhattan_mst(vc<pair<T, T>>& XY) {
int N = XY.size();
vc<tuple<T, int, int>> dat;
dat.reserve(4 * N);
vc<int> idx(N);
iota(all(idx), 0);
FOR(a, 2) {
for (auto&& [x, y]: XY) x = -x;
FOR(b, 2) {
for (auto&& [x, y]: XY) swap(x, y);
sort(all(idx), [&](const int& i, const int& j) -> bool {
return XY[i].fi + XY[i].se < XY[j].fi + XY[j].se;
});
map<T, int> MP;
for (const int i: idx) {
auto& [x, y] = XY[i];
for (auto it = MP.lower_bound(-y); it != MP.end(); it = MP.erase(it)) {
const int j = it->se;
auto& [xj, yj] = XY[j];
const int dx = x - xj;
const int dy = y - yj;
if (dy > dx) break;
dat.eb(dx + dy, i, j);
}
MP[-y] = i;
}
}
}
sort(all(dat));
Graph<T, 0> G(N);
UnionFind uf(N);
for (auto&& [cost, i, j]: dat) {
if (uf.merge(i, j)) G.add(i, j, cost);
}
G.build();
return G;
}