a687困難枚舉圓順序與所有前圓的幾何限制

CPE:How Big Is It? (UVa 10012)

用相切圓心水平距離求每種排列的最緊密擺法。

前往題目練習 →回報教學錯誤最壞時間 O(m!·m²),遞迴與距離表空間 O(m²)。

解題思路

半徑 r、s 的圓都碰底邊,圓心高度差是 r−s。不重疊需要中心距離至少 r+s,因此水平距離至少 sqrt((r+s)²−(r−s)²)=2√(rs)。固定由左至右的圓心順序後,新圓中心 x 取 max(r, max_j(xj+2√(rj·r))),第一項防止超過盒子左邊。

檢查所有先前圓,因為中間小圓可能無法隔開兩個大圓。每個圓都往左擺到限制最緊的位置不會妨礙後續圓,故對固定排列此法最優。枚舉最多8!個排列,寬度為 max(xi+ri),取最小;若目前寬度已不小於已知答案可剪枝,相同半徑同層只選一次。輸出三位小數。

Step-by-step animation

示意:固定順序半徑 2,1,2

回報動畫錯誤
步驟 1 / 3

第一圓

中心 x=2,右界4。

r=2,x=2
寬
4

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
    int tests;
    cin >> tests;
    while (tests--) {
        int n;
        cin >> n;
        vector<double> r(n);
        double best = 0;
        for (double &v : r) {
            cin >> v;
            best += 2 * v;
        }
        sort(r.begin(), r.end());
        vector<vector<double>> gap(n, vector<double>(n));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                gap[i][j] = 2 * sqrt(r[i] * r[j]);
        vector<int> order;
        vector<double> x;
        vector<bool> used(n);
        function<void(double)> dfs = [&](double width) {
            if (order.size() == r.size()) {
                best = min(best, width);
                return;
            }
            for (int i = 0; i < n; i++)
                if (!used[i]) {
                    if (i && r[i] == r[i - 1] && !used[i - 1])
                        continue;
                    double center = r[i];
                    for (int j = 0; j < (int)order.size(); j++)
                        center = max(center, x[j] + gap[order[j]][i]);
                    double next = max(width, center + r[i]);
                    if (next >= best)
                        continue;
                    used[i] = true;
                    order.push_back(i);
                    x.push_back(center);
                    dfs(next);
                    x.pop_back();
                    order.pop_back();
                    used[i] = false;
                }
        };
        dfs(0);
        cout << fixed << setprecision(3) << best << '\n';
    }
}

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

更多