在2D平面中分割一组点

时间:2018-10-20 17:07:50

标签: algorithm computational-geometry partitioning

问题陈述是- “您得到了一组N点,其中N为偶数,N <=1000。您必须找到点对的数量,这样,如果您通过该对画一条线,则该线的每一侧将包含相等的点。点数(N / 2-1)。” 我不知道如何在O(n ^ 2)或更短的时间内解决这个问题? 这是我的暴力解决方案-

class Point{
public:
   int x, y;
   Point(){x = y = 0;}
   void make_point(int X, int Y){ x = X; y = Y; }
   int Point:: orientation (Point &p0, Point &p1){
     Point p2 = *this;
     Point a = p1 - p0;
     Point b = p2 - p0;
     int area = (a.x * b.y) - (b.x * a.y);
     if (area > 0)return 1;
     if (area < 0)return -1;
     return 0;
   }
};
int main() {
  Point p[4];
  p[0].make_point(0, 0);
  p[1].make_point(0, 1);
  p[2].make_point(1, 1);
  p[3].make_point(1, 0);
  int sz = sizeof(p) / sizeof(p[0]);
  int ans = 0;
  for (int i = 0; i < sz; i++){
    for (int j = i+1; j < sz; j++){
        int leftCnt = 0, rightCnt = 0;
        for (int k = 0; k < sz; k++){
            if (k == i || k == j)continue;
            if (p[k].orientation(p[i], p[j]) == 1)leftCnt++;
            if (p[k].orientation(p[i], p[j]) == -1)rightCnt++;
        }
        if (leftCnt == rightCnt && leftCnt == (sz/2-1))ans++;
    }
  }
  cout << ans << '\n';

  return 0;
}

有什么方法可以优化解决方案?

1 个答案:

答案 0 :(得分:1)

有一种简单的方法可以在O(n ^ 2 log n)时间内完成此操作。

for each point O in the set
   for each point A /= O
      calculate the slope of the ray OA 
   sort the points by the slope (this is the n log n limiting step) 
   for each point A /= O
      determine how many points are at either side of the line OA (this is an O(1) job)

也许可以减少排序时间,因为将极坐标转换为另一个原点时,排序后的斜率数组几乎可以排序(仅需要O(n)时间才能完全排序),但是我无法证明这一点此刻。