gpt4 book ai didi

c++ - 打印最近的一对点

转载 作者:行者123 更新时间:2023-11-28 06:08:54 25 4
gpt4 key购买 nike

我正在编写这段代码来查找 2 点之间的最小距离。我编写的代码正确地给出了最小距离,但没有给出计算最小距离的正确坐标。请帮助我根据对我来说,这是打印点以及最小距离的正确方法。

#include<bits/stdc++.h>
#define FOR(i,N) for(int i=0;i<(N);i++)
#define rep(i,a,n) for(int i=(a);i<(n);i++)
using namespace std;
struct point {
int x;
int y;
};

typedef struct point point;
void printarr(point arr[], int n) {for(int i = 0; i < n; i++) cout <<
arr[i].x << " " << arr[i].y << endl; cout << endl;
bool comparex(const point& X, const point& Y) { return X.x < Y.x; }
bool comparey(const point& X, const point& Y) { return X.y < Y.y; }

float getdis(point X, point Y) { return sqrt((X.x - Y.x)*(X.x - Y.x) + (X.y
- Y.y)*(X.y - Y.y)); }
float brutedis(point P[], int n, point A[]) {
float d = INT_MAX;
float temp;
FOR(i, n) {
rep(j, i+1, n) {
temp = getdis(P[i],P[j]);
if(temp < d) {
d = temp;
A[0].x = P[i].x; A[0].y = P[i].y;
A[1].x = P[j].x ; A[1].y = P[j].y;
}
}
}
return d;
}

float stripdis(point P[], int n, float d, point A[]) {
float temp = d;
float dis;
sort(P, P + n, comparey);
FOR(i, n) {
rep(j,i+1,n) {
if(abs(P[j].y - P[i].y) < d) {
dis = getdis(P[j], P[i]);
if(dis < temp) {
temp = dis;
A[0].x = P[i].x; A[0].y = P[i].y;
A[1].x = P[j].x ; A[1].y = P[j].y;
}
}
}
}
return temp;
}

float solve(point P[], int n, point A[]) {

if(n <= 3) return brutedis(P, n, A);

int mid = n/2;
point M = P[mid];
float d = min(solve(P, mid, A), solve(P+mid, n-mid, A));
point strip[n];
int j = 0;
int i = 0;
while(i < n) {
if(abs(P[i].x - M.x) < d) strip[j++] = P[i];
i++;
}

return min(d, stripdis(strip, j, d, A));
}

int main() {

point P[] = {{0, 0}, {-4,1}, {-7, -2}, {4, 5}, {1, 1}};
int n = sizeof(P) / sizeof(P[0]);
sort(P, P+n, comparex);
point A[2];
cout << "Minimum Distance = " << solve(P, n, A) << "\n";
printarr(A, 2);
//printarr(P, n);
return 0;
}

最佳答案

在某种程度上我可以遵循你格式错误的代码,brutedis 无条件修改 A[] 并在你找到正确答案后再次调用它(但不知道你找到了正确答案)。

因此,如果第一次调用在 min(solve(P, mid, A), solve(P+mid, n-mid, A)); 中最好,第二次仍然可以调用 brutedis 和销毁A[]

关于c++ - 打印最近的一对点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31707987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com