c++ - 找到连接 2N 个点的线段的最小总长度
问题描述
我正在尝试通过蛮力解决这个问题,但是当给定 7(即 2*7 点)时,它似乎运行得很慢。
注意:我只需要将它运行到最大 2*8 点
问题陈述:
给定二维平面中的 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;
}
我怎样才能加快这段代码?
解决方案
推荐阅读
- html - 过渡问题:将鼠标悬停在图像 CSS / HTML 上
- php - Elementor Pro 表单验证
- python - 带条件的斜线后删除字符串
- python - 如何解决 traceroute 收到的包错误?
- php - PHP 多字节 preg_split() 与 PREG_SPLIT_OFFSET_CAPTURE
- r - 我将删除 58000 多行的行。如果超过 5% 的变量为 NA,则删除行
- .net - 添加后立即在字典中出现 KeyNotFound 异常
- java - (Java)有没有办法在方法中创建变量并每次更改变量的名称?
- java - JavaFXML创建不扩展节点的自定义标签元素
- javascript - 像 Postman 一样使用 Javascript 使用 OAuth 2 Token 获取值