Count number of points inside a circle fast

前端 未结 6 1863
长发绾君心
长发绾君心 2020-12-23 23:35

Given a set of n points on plane, I want to preprocess these points somehow faster than O(n^2) (O(nlog(n)) preferably), and then be able to answer on queries of the followi

6条回答
  •  情话喂你
    2020-12-24 00:16

    Build a KD-tree of the points, this should give you much better complexity than O(n), on average O(log(n)) I think.

    You can use a 2D tree since the points are constrained to a plane.

    Assuming that we have transformed the problem into 2D, we'll have something like this for the points:

     struct Node {
         Pos2 point;
         enum {
            X,
            Y
         } splitaxis;
         Node* greater;
         Node* less;
     };
    

    greater and less contains points with greater and lesser coordinates respectively along the splitaxis.

     void
     findPoints(Node* node, std::vector& result, const Pos2& origin, float radius) {
         if (squareDist(origin - node->point) < radius * radius) {
             result.push_back(node->point);
         }
         if (!node->greater) { //No children
              return;
         }
         if (node->splitaxis == X) {
             if (node->point.x - origin.x > radius) {
                 findPoints(node->greater, result, origin radius);
                 return;
             }
             if (node->point.x - origin.x < -radius) {
                 findPoints(node->less, result, origin radius);
                 return;
             }
             findPoints(node->greater, result, origin radius);
             findPoints(node->less, result, origin radius);
         } else {
             //Same for Y
         }
     }
    

    Then you call this function with the root of the KD-tree

提交回复
热议问题