与平面上的点和一些技术错误有关的问题[C++]

Problem related to points on a plane and some technical errors [C++]

本文关键字:问题 C++ 错误 平面 技术      更新时间:2024-04-28

问题陈述:给定平面上的n个点(n为偶数(。求一对点的数量,使通过它们的直线两侧的点数量相等。

我正在尝试使用蛮力(~O(n^3((,任何关于改进解决方案的建议都将不胜感激。对于同样的问题,我也找到了这个答案,但无法实现


主要技术问题:我已经用// HERE标记了导致错误的部分。更准确地说,错误是:

error: no matching function for call to 'sign'
if(sign(A, B, M) == 1) right++;
error: no matching function for call to 'sign'
if(sign(A, B, M) == -1) left++;

我想我的错误可能是在定义ABC时使用了&。我该怎么修?


我的代码:

#include <iostream>
using namespace std;
// check which side of the line AB does the point M lie on
int sign(float A[2], float B[2], float M[2]) {
float det = (A[0] - M[0]) * (B[1] - M[1]) - (B[0] - M[0]) * (A[1] - M[1]);
if(det > 0) return 1;
if(det < 0) return -1;
else return 0;
}
int main() {
int n, res = 0;
cin >> n;
float points[n][2]; // array of points
// enter points via coordiantes
for(int i = 0; i < n; i++) {
for(int j = 0; j < 2; j++) {
cin >> points[i][j];
}      
}

// brute force :(
for(int i = 0; i < n; i++) {
int left = 0, right = 0;
float &A = *points[i];
for(int j = 0; i < n; i++) {
if(j == i) continue;
float &B = *points[j];
for(int k = 0; k < n; k++) {
if(k == j || k == i) continue;
float &M = *points[k];
if(sign(A, B, M) == 1) right++; // HERE
if(sign(A, B, M) == -1) left++; // HERE
}
}
if(left == right) res++;
}
cout << res << endl;
return 0;
}

我认为你不需要暴力,至少n^2logn应该比n^3更好。我不会用c++编写代码,但我会解释算法:

  1. 将每个点视为集线器的中心,通过线连接到所有其他点。然后,具有该中心的每对点与x轴形成一定的角度,您可以简单地使用arctan(deltay/deltax(来找到该角度。

  2. 对于每个中心,您可以对角度进行排序(nlogn(,在O(1)中很容易知道该组角度的中间角度是多少,从而知道要添加到列表中的对。这是一个角落的情况,可能有几个共线对,所以不要忘记这一点。

  3. 因此,如果你对n个点这样做,对nlogn次排序,你就会得到n^2logn中的解决方案