跳到正文

题解

题解 P6362 【平面欧几里得最小生成树】

Mr_Skirt约 34 分钟
原文
文章信息与版本

文章信息

发布
2021年1月17日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 34 分钟
获赞
9
题目
P6362

版本

  1. v1当前

提供一个 Bowyer-Watson 算法的期望O(nlog⁡n)O(n\log{n})实现方案。朴素的 Bowyer-Watson 算法求Delaunay三角剖分实现复杂度是O(n2)O(n^2)的,而我使用的这个算法基于的是随机增量方法,虽然时间复杂度看起来不对,但由于我们是随机的选择插入顺序,超过nlog⁡nn\log{n}的情况几乎不存在。

算法流程

整个算法的流程是这样的

  1. 一开始先构造一个极大三角形,然后打乱插入点集的顺序。
  2. 每次插入一个点 pp,确定这个点在哪个三角形,同时把这个三角形三个顶点连接插入点分成三份,分别命名为 a,b,ca,b,c。 确定三角形
  3. 对于 a,b,ca,b,c 三个三角形,我们把所有不包含 pp 的边标记为可疑边。
  4. 对于所有可疑边,我们选择与插入点 pp 根据可疑边对立的顶点 qq。设可疑边两个顶点为 x,yx, y。此时 p,x,q,yp,x,q,y 组成了一个四边形,如果 qq 在 p,x,yp, x, y 组成的圆里,那么我们要对四边形 p,x,q,yp,x,q,y 进行边翻转操作。 可疑边与对立顶点
  5. 如果进行了边翻转操作,我们要把 qxqx, qyqy 也标记为可疑边。
  6. 对所有可疑边都进行边翻转操作,当不存在任何可疑边的时候插入就结束了。 边翻转操作
  7. 插入完所有点后算法就结束了。

难点

这个算法本身包含几个难点:

  1. 如何高效的找到可疑边和对立点?
  2. 如果高效的进行点定位(Point Location)操作?即确定插入点落在哪个三角形内部?
  3. 如何判断点是否在某三个点的外接圆内部?

第三个问题在@Tweetuzki的题解里已经解释的非常详细了,我这里就直接引用他的方法了。

平面图表示方法

第一个问题可以使用一个叫做DCEL(doubly connected edge list,即双向链接边表)的结构实现,对于这个问题我进行了一点简化,使用的是单向链接边表。

这个数据结构是由三个基本结构组成的,我们知道在平面图中有三个重要组成元素:顶点,边,面。

顶点很好表示,我们只关心它的位置。

对于边和面来说,我们需要记录更多信息。为了能够知道这个边组成了哪个面,我们需要对边进行定向,如果某一些边逆时针可以组成一个面,那么就说这些边是这个面的组成边,这个面就成为这些边的组成面,如图所示 边链表 AA 面是由红色的边所组成的,BB 面是由蓝色的边组成的,注意 acac 和 caca 组成的面是不同的。

除此之外,为了能够遍历一个面的所有组成边,对于每一个边我们规定它的前驱指针指向构成这个面的逆时针下一条边。比如说,caca 这条边的前驱就是边 abab。

最后,为了能够获取对立顶点,我们需要由一个跨面的操作,即从面 AA 跨越到它的邻接面 BB,我们只需要知道 acac 边的孪生边 caca 即可。 caca 的组成面就是 BB。我们要对每条边都维护这么一个孪生边。

假设我们想要获得 bb 对于边 acac 的对立顶点,只需要先获得 acac 边,然后找到其孪生边的前驱即可。

至此,我们就完成了对于这么一个平面的图的表示,以下是这三个结构的抽象表示方法:

C++
struct Edge {
    // 边的起点
    Vertex* from;
    // 边的终点
    Vertex* to;
    // 孪生边
    Edge* twin;
    // 组成面
    Face* face;
    // 前驱边
    Edge* next;

    int id;
};

struct Face {
    int id;
    // 其中一个组成边
    Edge* edge;
};

struct Vertex {
    int id;
    Vector2 pos;
};

高效点定位

在线的点定位(Point Location)问题通常需要复杂的数据结构,比如Kirpatrick的算法和梯形图(Trapezoidal Map)算法。这些算法可以实现单点期望 O(log⁡n)O(\log{n}) 的查询效率,但是代码极其难写且边界条件众多。(当年上计算几何课写这个差点没把我送走QAQ

对于这道题来说,我们有个优势就是可以使用离线的算法,而且出乎意料的是,这个算法极其简单,复杂度和随即增量算法一样看起来很高,但是由于随机性,这个点定位可以在期望均摊 O(n)O(n) 的时间解决。

这个方法就是,对于所有三角形的面我们用一个列表记录哪些点在这个三角形内,每次三角形有变动的时候我们暴力重新分配这些点,仅此而已。看起来很暴力,但是效率奇高(并不是因为数据弱哦)。

这样我们对每个顶点维护一下它落在属于哪个面即可。

实现细节

输入点扰动

为了避免重点、三点共线、四点共圆等等的边界条件,我们要先对输入点进行微小扰动。

C++
static std::mt19937 mt;

void shake() {
    pos.x += (mt.max() / 2 - mt()) / (double)mt.max() * 2 * EPS;
    pos.y += (mt.max() / 2 - mt()) / (double)mt.max() * 2 * EPS;
}

遍历可疑边

每次插入一个点,我们确认了落在哪个三角形内部以后,分裂出来的三个三角形的向外的边都会被标记为可疑边,为了能够按照顺序处理,我们维护一个队列即可,进行边翻转以后加入新的可疑边进队列即可,伪代码:

C++
std::queue<Edge*> Q;
while (!Q.empty()) {
    auto curEdge = Q.front();
    Q.pop();

    // 如果没有孪生边就略过
    auto twin = curEdge->twin;
    if (!twin) continue;

    auto target = twin->next->to;
    // 判断对立顶点是否在外接圆内
    if (inCircumcircle(curEdge->from, curEdge->to, P, target)) {
        // 进行边翻转,同时加入新的可疑边
    }
}

边翻转

我们只需要把两个对立顶点的边翻转到另外两个对立顶点即可,注意在这个过程中我们并不需要增加和删除面,我们可以在原来的边和面上进行操作,首先把边的两个顶点换掉,然后对于这两个面,重新连接边,以及前驱。

在这个过程中也别忘了把之前两个面覆盖的顶点拿出来,并且在边翻转结束后重新更新每个顶点的所属面。 边翻转流程

C++
auto A = curEdge -> face;
auto B = twin -> face;
// 提取出覆盖了的顶点
std::vector<Vertex*> cover;
for (auto vs : A->owned) {
    cover.push_back(vs);
}
for (auto vs : B->owned) {
    cover.push_back(vs);
}


// 重组AB面
// ......
// 这部分代码略去留给读者自己思考 


for (auto vs : cover) {
    // 剔除掉没必要更新的点
    if (vs->id == P->id) continue;
    // 每个顶点重新判断所属面
    if (!vs->testInTriangle(A)) {
        vs->belong = B;
        B->owned.push_back(vs);
    }
}

打碎原三角形

与上面的边翻转一样,这里我们也没必要生成三个新的三角形,而是只生成两个,然后另一个使用原三角形。更新顶点所属面和上面一样暴力。

至此这个随机增量算法的大部分细节就都介绍完毕了,对于这题剩下的只要遍历所有边然后求最小生成树即可。截止目前,这个“纯暴力”算法是跑的最快的提交,我的代码还有很多地方没有优化,比如把指针替换为数组下标,以及比较优雅的判断点是否在面内的算法。

由此可以看出,随机化思想在计算几何中的重要性,它允许了我们用极其优雅和简单的方式解决困难的问题。

算法本身实现非常简单,但是时间复杂度直到1992年的论文Randomized Incremental Construction of Delaunay and Voronoi Diagrams才真正的确认为期望O(nlog⁡n)O(n\log{n})。

参考代码(很长,但是大部分代码都是数据结构的表示以及向量的板子,核心就是insert函数)

C++
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <vector>
typedef long long ll;
typedef unsigned long long ull;
typedef long double LD;
const int INF = 2147483647;
const int INF2 = 0x3f3f3f3f;
const ll INF64 = 1e18;
const double INFD = 1e30;
const double PI = acos(-1);
const int MOD = 1e9 + 7;
template <typename T>
inline T read() {
    T X = 0, w = 0;
    char ch = 0;
    while (!isdigit(ch)) {
        w |= ch == '-';
        ch = getchar();
    }
    while (isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}

int n, m;
int dr[4] = {1, 0, -1, 0};
int dc[4] = {0, 1, 0, -1};
int dr2[8] = {1, 1, 1, -1, -1, -1, 0, 0};
int dc2[8] = {1, 0, -1, 1, 0, -1, 1, -1};
int CASE = 1;

constexpr int MAXN = 100010;
constexpr double EPS = 1e-10;

static std::mt19937 mt;

int dcmp(double x) {
    if (fabs(x) < EPS) return 0;
    return x > 0 ? 1 : -1;
}

struct Vector2 {
    double x, y;
    Vector2() : x(0), y(0) {}
    Vector2(double x, double y) : x(x), y(y) {}
    Vector2(double rad) : x(cos(rad)), y(sin(rad)) {}

    static double dot(const Vector2& a, const Vector2& b) {
        return a.x * b.x + a.y * b.y;
    }
    static double angle(const Vector2& a, const Vector2& b) {
        return acos(dot(a, b) / a.length() / b.length());
    }
    static double cross(const Vector2& a, const Vector2& b) {
        return a.x * b.y - a.y * b.x;
    }
    static double area2(const Vector2& a, const Vector2& b, const Vector2& c) {
        return cross(b - a, c - a);
    }

    double length() const { return std::sqrt(x * x + y * y); }
    double lengthSq() const { return x * x + y * y; }
    double getRad() const { return atan2(y, x); }
    Vector2 rotate(double rad) const {
        return Vector2(x * cos(rad) - y * sin(rad),
                       x * sin(rad) + y * cos(rad));
    }
    Vector2 unit() const {
        double l = this->length();
        return Vector2(x / l, y / l);
    }
    Vector2 normal() const {
        double l = this->length();
        return Vector2(-y / l, x / l);
    }

    bool operator<(const Vector2& other) const {
        return x < other.x || (x == other.x && y < other.y);
    }
    bool operator==(const Vector2& other) const {
        return !dcmp(x - other.x) && !dcmp(y - other.y);
    }

    Vector2& operator+=(const Vector2& vec) {
        this->x += vec.x, this->y += vec.y;
        return *this;
    }
    Vector2 operator+(const Vector2& vec) const {
        return Vector2(this->x + vec.x, this->y + vec.y);
    }
    Vector2& operator-=(const Vector2& vec) {
        this->x -= vec.x, this->y -= vec.y;
        return *this;
    }
    Vector2 operator-(const Vector2& vec) const {
        return Vector2(this->x - vec.x, this->y - vec.y);
    }
    Vector2& operator*=(double v) {
        this->x *= v, this->y *= v;
        return *this;
    }
    Vector2& operator*=(const Vector2& v) {
        this->x *= v.x, this->y *= v.y;
        return *this;
    }
    Vector2 operator*(double v) const {
        return Vector2(this->x * v, this->y * v);
    }
    Vector2 operator*(const Vector2& vec) const {
        return Vector2(this->x * vec.x, this->y * vec.y);
    }
    Vector2& operator/=(double v) {
        this->x /= v, this->y /= v;
        return *this;
    }
    Vector2& operator/=(const Vector2& vec) {
        this->x /= vec.x, this->y /= vec.y;
        return *this;
    }
    Vector2 operator/(double v) const {
        return Vector2(this->x / v, this->y / v);
    }
    Vector2 operator/(const Vector2& vec) const {
        return Vector2(this->x / vec.x, this->y / vec.y);
    }
};

struct Face;
struct Vertex;
struct Edge;

struct Edge {
    Vertex* from;
    Vertex* to;
    Edge* twin;
    Face* face;
    Edge* next;

    int id;

    Edge()
        : from(nullptr),
          to(nullptr),
          twin(nullptr),
          face(nullptr),
          next(nullptr),
          id(0) {}
    Edge(Vertex* fr, Vertex* to)
        : from(fr),
          to(to),
          twin(nullptr),
          face(nullptr),
          next(nullptr),
          id(0) {}
};

struct Face {
    int id;
    Edge* edge;
    std::vector<Vertex*> owned;
    Face() : id(0), edge(nullptr) {}
    Face(int id, Edge* edge) : id(id), edge(edge) {}
};

struct Vertex {
    int id;
    Face* belong;
    Vector2 pos;

    Vertex() : id(0), belong(nullptr), pos() {}
    Vertex(int id, double x, double y) : id(id), belong(nullptr), pos(x, y) {}

    void shake() {
        pos.x += (mt.max() / 2 - mt()) / (double)mt.max() * 2 * EPS;
        pos.y += (mt.max() / 2 - mt()) / (double)mt.max() * 2 * EPS;
    }

    // 非常暴力地判断点是否在面内部
    bool testInTriangle(Face* face) {
        auto e = face->edge;
        for (int i = 0; i < 3; i++) {
            auto dir = e->to->pos - e->from->pos;
            auto p = pos - e->from->pos;
            if (Vector2::cross(dir, p) < 0) return false;
            e = e->next;
        }
        belong = face;
        face->owned.push_back(this);
        return true;
    }
};

Vertex vPool[MAXN];
int totV;

Face fPool[MAXN * 2];
int totF;

Edge ePool[MAXN * 6];
int totE;

typedef struct vec3_t {
    double x, y, z;
    vec3_t(double _x = 0, double _y = 0, double _z = 0) {
        x = _x, y = _y, z = _z;
    }
    inline friend vec3_t operator+(const vec3_t& a, const vec3_t& b) {
        return vec3_t(a.x + b.x, a.y + b.y, a.z + b.z);
    }
    inline friend vec3_t operator-(const vec3_t& a, const vec3_t& b) {
        return vec3_t(a.x - b.x, a.y - b.y, a.z - b.z);
    }
    inline friend vec3_t operator*(const vec3_t& a, double k) {
        return vec3_t(a.x * k, a.y * k, a.z * k);
    }
    inline friend vec3_t cross(const vec3_t& a, const vec3_t& b) {
        return vec3_t(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z,
                      a.x * b.y - a.y * b.x);
    }
    inline friend double dot(const vec3_t& a, const vec3_t& b) {
        return a.x * b.x + a.y * b.y + a.z * b.z;
    }
} node3_t;

bool inCircumcircle(Vertex* a, Vertex* b, Vertex* c, Vertex* d) {
    vec3_t A = vec3_t(a->pos.x, a->pos.y, Vector2::dot(a->pos, a->pos));
    vec3_t B = vec3_t(b->pos.x, b->pos.y, Vector2::dot(b->pos, b->pos));
    vec3_t C = vec3_t(c->pos.x, c->pos.y, Vector2::dot(c->pos, c->pos));
    vec3_t D = vec3_t(d->pos.x, d->pos.y, Vector2::dot(d->pos, d->pos));
    if (Vector2::cross(b->pos - a->pos, c->pos - a->pos) < 0) std::swap(B, C);

    node3_t normal = cross(B - A, C - A);
    if (dot(normal, D - A) > EPS)
        return false;
    else
        return true;
}

Vertex* newVertex(double x, double y) {
    ++totV;
    vPool[totV] = Vertex(totV, x, y);
    return &vPool[totV];
}

Edge* newEdge(Vertex* fr, Vertex* to) {
    ++totE;
    ePool[totE] = Edge(fr, to);
    ePool[totE].id = totE;
    return &ePool[totE];
}

// 创造一个以abc为逆时针顶点的三角形面
void constructNewFace(Face* face, Vertex* a, Vertex* b, Vertex* c) {
    Edge* edges[3];
    edges[0] = newEdge(a, b);
    edges[1] = newEdge(b, c);
    edges[2] = newEdge(c, a);

    for (int i = 0; i < 3; i++) {
        edges[i]->next = edges[(i + 1) % 3];
        edges[i]->face = face;
    }
    face->edge = edges[0];
}

// 创造一个以边abc为逆时针顺序的组成面
void constructFace(Face* face, Edge* a, Edge* b, Edge* c) {
    Edge* edges[3];
    edges[0] = a;
    edges[1] = b;
    edges[2] = c;
    for (int i = 0; i < 3; i++) {
        edges[i]->next = edges[(i + 1) % 3];
        edges[i]->face = face;
    }
    face->edge = a;
}

Face* newFace() {
    totF++;
    fPool[totF].id = totF;
    return &fPool[totF];
}
Vector2 PT[MAXN];
void insert(int x) {
    Vertex* v = &vPool[x];
    Face* face = v->belong;

    // 打碎原三角形,生成三个新的三角形

    auto fEdge = face->edge;
    Face* nFaces[3];
    nFaces[0] = face;
    nFaces[1] = newFace();
    nFaces[2] = newFace();

    // nEdges 是逆时针的第一条边,cEdges是组成面的逆时针最后一条边
    Edge* nEdges[3];
    Edge* cEdges[3];
    Edge* oEdges[3];

    for (int i = 0; i < 3; i++) {
        nEdges[i] = newEdge(v, fEdge->from);
        cEdges[i] = newEdge(fEdge->to, v);
        oEdges[i] = fEdge;
        fEdge = fEdge->next;
    }

    for (int i = 0; i < 3; i++) {
        constructFace(nFaces[i], nEdges[i], oEdges[i], cEdges[i]);
        nEdges[i]->twin = cEdges[(i + 2) % 3];
        cEdges[(i + 2) % 3]->twin = nEdges[i];
    }

    std::vector<Vertex*> children(nFaces[0]->owned.begin(),
                                  nFaces[0]->owned.end());
    for (int i = 0; i < 3; i++) {
        nFaces[i]->owned.clear();
    }

    for (auto vs : children) {
        if (vs->id == v->id) continue;
        for (int i = 0; i < 3; i++) {
            if (vs->testInTriangle(nFaces[i])) break;
        }
    }

    std::queue<Edge*> Q;
    for (int i = 0; i < 3; i++) {
        Q.push(oEdges[i]);
    }

    while (!Q.empty()) {
        auto curEdge = Q.front();
        Q.pop();

        auto twin = curEdge->twin;
        if (!twin) continue;

        auto targetV = twin->next->to;
        if (targetV == v) continue;

        if (inCircumcircle(curEdge->from, curEdge->to, v, targetV)) {
            auto nxt1 = twin->next;
            // 添加可疑边
            Q.push(nxt1), Q.push(nxt1->next);

            auto A = curEdge->face;
            auto B = twin->face;

            assert(A != B);
            children.clear();
            for (auto vs : A->owned) children.push_back(vs);
            for (auto vs : B->owned) children.push_back(vs);
            A->owned.clear();
            B->owned.clear();

            auto lastNxt = curEdge->next;
            auto lastPrev = lastNxt->next;

            // Do edge flip
            curEdge->from = v, curEdge->to = targetV;
            twin->from = targetV, twin->to = v;

            constructFace(A, curEdge, nxt1->next, lastNxt);
            constructFace(B, twin, lastPrev, nxt1);

            for (auto vs : children) {
                if (vs->id == v->id) continue;
                if (!vs->testInTriangle(A)) {
                    vs->belong = B;
                    B->owned.push_back(vs);
                }
            }
        }
    }
}

struct UnionFind {
    void clear(int n) {
        for (int i = 0; i <= n; i++) fa[i] = i;
    }
    void join(int x, int y) {
        int a = find(x), b = find(y);
        fa[a] = b;
    }
    int find(int x) { return (fa[x] == x) ? x : fa[x] = find(fa[x]); }
    int fa[MAXN];
};
UnionFind uf;

struct E2 {
    int x, y;
    double w;
    bool operator<(const E2& e) const { return w < e.w; }
};
std::vector<E2> edges;
int main() {
#ifdef LOCALLL
    freopen("in", "r", stdin);
    freopen("out", "w", stdout);
#endif
    mt.seed(19260817);
    scanf("%d", &n);
    uf.clear(n);
    for (int i = 1; i <= n; i++) {
        scanf("%lf %lf", &PT[i].x, &PT[i].y);
        vPool[++totV] = Vertex(i, PT[i].x, PT[i].y);
        vPool[totV].shake();
    }
    std::random_shuffle(vPool + 1, vPool + totV + 1,
                        [](int x) { return mt() % x; });
    auto a = newVertex(1e6, 1e6);
    auto b = newVertex(-1e6, 1e6);
    auto c = newVertex(-1e6, -1e6);
    auto d = newVertex(1e6, -1e6);

    auto f1 = newFace();
    auto f2 = newFace();
    constructNewFace(f1, a, b, d);
    constructNewFace(f2, d, b, c);

    f1->edge->next->twin = f2->edge;
    f2->edge->twin = f1->edge->next;

    for (int i = 1; i <= n; i++) {
        Vertex& v = vPool[i];
        if (!v.testInTriangle(f1)) {
            v.belong = f2;
            f2->owned.push_back(&vPool[i]);
        }
    }
    for (int i = 1; i <= n; i++) {
        insert(i);
    }
    for (int i = 1; i <= totF; i++) {
        auto e = fPool[i].edge;
        for (int j = 0; j < 3; j++) {
            int u = e->from->id, v = e->to->id;
            if (u <= n && v <= n) {
                edges.push_back({u, v, (PT[v] - PT[u]).length()});
            }
            e = e->next;
        }
    }
    std::sort(edges.begin(), edges.end());
    double ans = 0;
    for (auto& e : edges) {
        if (uf.find(e.x) != uf.find(e.y)) {
            ans += e.w;
            uf.join(e.x, e.y);
        }
    }
    printf("%.6lf\n", ans);
    return 0;
}

补充一个比较好玩的,如果要从Delaunay三角剖分求出其对偶Voronoi图,我们可以对于每个三角形面求出外心,然后连接其三个邻接面的外心即可,看图:

Voronoi图构造

原文
存档评论2 条抓取于