a874困難

114 全國資訊學科能力競賽(2025)|G. 神聖的連線儀式 (Connections)

結合平面最近點對與參數化匹配。

解題思路

先忽略不交叉條件,求大小k的最小總長匹配;若最優兩線交叉或共線重疊,改配同四端點的另一組邊,由三角不等式可嚴格縮短。因此最小匹配自然滿足不相交。

由大小r的最小匹配M增加一條最小代價的簡單增廣路,可得到大小r+1最小匹配:與任何更好匹配的對稱差拆成交錯鏈與環,等基數部分不能改進M,剩下至少一條更好的增廣鏈,會與最小增廣假設矛盾。

增廣路長1時是未匹配點的平面最近點對,以分治O(n log n)求。其他情況只會穿過r條舊匹配邊的子集合。DP[mask][t]維護走完mask邊、停在已配對端點t的最小交錯路,保留兩個不同未匹配起點的最佳紀錄,確保最後可選與起點不同的終點。每次加入一條未使用匹配邊,代價為新連線長減掉舊匹配邊長。

每個已匹配端點只需考慮最近兩個未匹配端點作起終點,較遠者至少有一個較近替代不會撞起點。DP保留來源與前驅,找到最佳增廣後回溯翻轉路上的匹配邊。重複k次。若已取得每條邊都等於全圖最短距離的下界解,可直接加入另一條達下界的最近點對,省去DP。演算法依官方增廣原理:https://github.com/twpca/nhspc-2025/blob/main/editorial/editorial.md 。

本實作每輪掃描未匹配點找各舊端點最近兩點,總O(nk²+nk log n+k²2^k)時間;DP以定長陣列存成本與單位元組來源、前驅,O(n+k2^k)空間。Python最大k常數較大。 Python一次讀入另佔O(輸入文字長度)空間。

Step-by-step animation

示例:第一條最短邊連2到3,長1。

回報動畫錯誤
步驟 1 / 3

直線點0,2,3,5

第一條最短邊連2到3,長1。

0
2—3
5
r
1
總長
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
struct Pt {
    long long x, y;
};
struct Close {
    long long d;
    int a, b;
};
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, K;
    cin >> n >> K;
    vector<Pt> p(n);
    for (auto &a : p)
        cin >> a.x >> a.y;
    auto sq = [&](int a, int b) {
        long long x = p[a].x - p[b].x, y = p[a].y - p[b].y;
        return x * x + y * y;
    };
    auto dist = [&](int a, int b) { return sqrt((double)sq(a, b)); };
    vector<int> sorted(n);
    iota(sorted.begin(), sorted.end(), 0);
    sort(sorted.begin(), sorted.end(),
         [&](int a, int b) { return tie(p[a].x, p[a].y) < tie(p[b].x, p[b].y); });
    auto closest = [&](vector<int> ids) {
        function<Close(int, int)> rec = [&](int l, int r) {
            Close ans{LLONG_MAX, -1, -1};
            if (r - l <= 3) {
                for (int i = l; i < r; i++)
                    for (int j = i + 1; j < r; j++) {
                        long long d = sq(ids[i], ids[j]);
                        if (d < ans.d)
                            ans = {d, ids[i], ids[j]};
                    }
                sort(ids.begin() + l, ids.begin() + r,
                     [&](int a, int b) { return p[a].y < p[b].y; });
                return ans;
            }
            int m = (l + r) / 2;
            long long x = p[ids[m]].x;
            auto A = rec(l, m), B = rec(m, r);
            ans = A.d < B.d ? A : B;
            inplace_merge(ids.begin() + l, ids.begin() + m, ids.begin() + r,
                          [&](int a, int b) { return p[a].y < p[b].y; });
            vector<int> s;
            for (int i = l; i < r; i++) {
                int u = ids[i];
                long long dx = p[u].x - x;
                if (dx * dx >= ans.d)
                    continue;
                for (int j = (int)s.size() - 1; j >= 0; j--) {
                    long long dy = p[u].y - p[s[j]].y;
                    if (dy * dy >= ans.d)
                        break;
                    long long d = sq(u, s[j]);
                    if (d < ans.d)
                        ans = {d, u, s[j]};
                }
                s.push_back(u);
            }
            return ans;
        };
        return rec(0, ids.size());
    };
    vector<pair<int, int>> matching;
    double total = 0, global = 0;
    for (int round = 0; round < K; round++) {
        vector<char> used(n);
        for (auto [a, b] : matching)
            used[a] = used[b] = 1;
        vector<int> free;
        for (int u : sorted)
            if (!used[u])
                free.push_back(u);
        auto direct = closest(free);
        double directCost = sqrt((double)direct.d);
        if (round == 0)
            global = directCost;
        if (round == 0 || total + directCost <= (round + 1) * global + 1e-10) {
            matching.push_back({direct.a, direct.b});
            total += directCost;
            continue;
        }
        int r = matching.size(), V = 2 * r;
        vector<int> end;
        vector<double> len(r);
        for (int j = 0; j < r; j++) {
            end.push_back(matching[j].first);
            end.push_back(matching[j].second);
            len[j] = dist(end[2 * j], end[2 * j + 1]);
        }
        vector<vector<pair<int, double>>> near(V);
        vector<int> pool;
        for (int t = 0; t < V; t++) {
            pair<long long, int> a = {LLONG_MAX, -1}, b = a;
            for (int u : free) {
                pair<long long, int> z = {sq(end[t], u), u};
                if (z < a) {
                    b = a;
                    a = z;
                } else if (z < b)
                    b = z;
            }
            for (auto z : {a, b})
                if (z.second >= 0) {
                    auto it = find(pool.begin(), pool.end(), z.second);
                    int id = it == pool.end() ? pool.size() : it - pool.begin();
                    if (it == pool.end())
                        pool.push_back(z.second);
                    near[t].push_back({id, sqrt((double)z.first)});
                }
        }
        vector<vector<double>> D(V, vector<double>(V));
        for (int i = 0; i < V; i++)
            for (int j = 0; j < V; j++)
                D[i][j] = dist(end[i], end[j]);
        int states = 1 << r;
        size_t size = (size_t)states * V * 2;
        vector<double> dp(size, numeric_limits<double>::infinity());
        vector<unsigned char> origin(size, 255), prev(size, 255);
        auto insert = [&](size_t base, double value, int src, int parent) {
            if (origin[base] == src) {
                if (value < dp[base]) {
                    dp[base] = value;
                    prev[base] = parent;
                }
                return;
            }
            if (origin[base + 1] == src) {
                if (value >= dp[base + 1])
                    return;
                dp[base + 1] = value;
                prev[base + 1] = parent;
                if (dp[base + 1] < dp[base]) {
                    swap(dp[base], dp[base + 1]);
                    swap(origin[base], origin[base + 1]);
                    swap(prev[base], prev[base + 1]);
                }
                return;
            }
            if (value < dp[base]) {
                dp[base + 1] = dp[base];
                origin[base + 1] = origin[base];
                prev[base + 1] = prev[base];
                dp[base] = value;
                origin[base] = src;
                prev[base] = parent;
            } else if (value < dp[base + 1]) {
                dp[base + 1] = value;
                origin[base + 1] = src;
                prev[base + 1] = parent;
            }
        };
        for (int a = 0; a < V; a++)
            for (auto [src, d] : near[a])
                insert(((size_t)(1 << (a / 2)) * V + (a ^ 1)) * 2, d - len[a / 2], src,
                       255);
        double best = directCost;
        int bm = 0, bt = 0, bs = 0, finish = -1;
        for (int mask = 1; mask < states; mask++) {
            int bits = mask;
            while (bits) {
                int j = __builtin_ctz((unsigned)bits);
                bits &= bits - 1;
                for (int t : {2 * j, 2 * j + 1})
                    for (int slot = 0; slot < 2; slot++) {
                        size_t at = ((size_t)mask * V + t) * 2 + slot;
                        if (origin[at] == 255)
                            continue;
                        double value = dp[at];
                        int src = origin[at];
                        for (auto [dest, d] : near[t])
                            if (dest != src && value + d < best) {
                                best = value + d;
                                bm = mask;
                                bt = t;
                                bs = slot;
                                finish = dest;
                            }
                        int left = (states - 1) ^ mask;
                        while (left) {
                            int h = __builtin_ctz((unsigned)left);
                            left &= left - 1;
                            int next = mask | (1 << h);
                            for (int a : {2 * h, 2 * h + 1})
                                insert(((size_t)next * V + (a ^ 1)) * 2,
                                       value + D[t][a] - len[h], src, t * 2 + slot);
                        }
                    }
            }
        }
        if (!bm)
            matching.push_back({direct.a, direct.b});
        else {
            vector<int> path = {pool[finish], end[bt]};
            int mask = bm, t = bt, slot = bs;
            while (mask) {
                size_t at = ((size_t)mask * V + t) * 2 + slot;
                path.push_back(end[t ^ 1]);
                int par = prev[at], src = origin[at];
                mask ^= 1 << (t / 2);
                if (par == 255) {
                    path.push_back(pool[src]);
                    break;
                }
                t = par / 2;
                slot = par % 2;
                path.push_back(end[t]);
            }
            vector<pair<int, int>> next;
            for (int j = 0; j < r; j++)
                if (!(bm >> j & 1))
                    next.push_back(matching[j]);
            for (int i = 0; i + 1 < (int)path.size(); i += 2)
                next.push_back({path[i], path[i + 1]});
            matching.swap(next);
        }
        total = 0;
        for (auto [a, b] : matching)
            total += dist(a, b);
    }
    cout << fixed << setprecision(10) << total << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多