求连接2N个点的线段的最小总长度

And*_*Lay 5 c++ algorithm optimization performance brute-force

我试图通过暴力破解这个问题,但是当给定 7 (即 2*7 点)时,它似乎运行得很慢。

注意:我只需要运行到最大2*8点

问题陈述:

给定 2d 平面上的 2*N 个点,将它们成对连接以形成 N 条线段。最小化所有线段的总长度。

例子:

输入:5 10 10 20 10 5 5 1 1 120 3 6 6 50 60 3 24 6 9 0 0

输出:118.4

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;

class point{
public:
    double x, y;
};

double getLength(point a, point b){
    return hypot((a.x - b.x), (a.y - b.y));
}

static double mini = INT_MAX;

void solve(vector <point> vec, double sum){
    double prevSum = sum;
    if(sum > mini){
        return;
    }
    if(vec.size() == 2){
        sum += getLength(vec[0], vec[1]);
        mini = min(mini, sum);
        return;
    }
    for(int i = 0; i < vec.size() - 1; i++){
        for(int j = i + 1; j < vec.size(); j++){
            sum = prevSum;
            vector <point> temp = vec;
            sum += getLength(temp[i], temp[j]);
            temp.erase(temp.begin() + j);
            temp.erase(temp.begin() + i);
            solve(temp, sum);
        }
    }
}

int main(){
    point temp;
    int input;
    double sum = 0;
    cin >> input;
    vector<point> vec;
    for(int i = 0; i < 2 * input; i++){
        cin >> temp.x >> temp.y;
        vec.push_back(temp);
    }
    solve(vec, sum);
    cout << fixed << setprecision(2) << mini << endl;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能加快这段代码的速度?

小智 2

您可以通过使用 next_permutation() 逐一遍历所有排列来迭代解决此问题。对混乱的代码表示歉意,但这应该告诉您如何做到这一点:

struct Point {

    Point(int x, int y) : x(x), y(y) {
    }


    bool operator< (const Point& rhs) {
        const int key1 = y * 1000 + x;
        const int key2 = rhs.y * 1000 + rhs.x;
        return  key1 < key2;
    }

    double dist(const Point& next) {

        const double h = (double)(next.x - x);
        const double v = (double)(next.y - y);
        return sqrt(h*h + v*v);
    }

    int x, y;

};
Run Code Online (Sandbox Code Playgroud)

您需要运算符,以便您的点有某种排序键,因此 next_permutation 可以按字典递增顺序遍历它们。双 getShortestDist(std::向量 p) {

    double min = 200000;

    std::sort(p.begin(), p.end());

    while(std::next_permutation(p.begin(), p.end())) {

        double sum = 0.0;
        for (int i = 0; i < p.size(); i+= 2) {
            sum += p[i].dist(p[i+1]);
        }
        if (sum < min) {
            min = sum;
        }
    }

    return min;


}


int main(int argc, char*argv[]) {

    static const int arr[] = {
        10, 10, 20, 10, 5, 5, 1, 1, 120, 3, 6, 6, 50, 60, 3, 24, 6, 9, 0, 0
    };
    std::vector<Point> test;

    for (int i = 0; i < 20; i += 2) {
        test.push_back(Point(arr[i], arr[i+1]));
        printf("%d %d\n", arr[i], arr[i+1]);
    }

    printf("Output: %d, %f", test.size(), getShortestDist(test));
}
Run Code Online (Sandbox Code Playgroud)