HDU 4347-the Closest M Points-[kdtree template title]

Source: Internet
Author: User

This article refers to:

Https://www.cnblogs.com/GerynOhenz/p/8727415.html

ACM Template for Kuangbin (new)

Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=4347

Problem Description

The course of software Design and development practice is objectionable. ZLC is facing a serious problem. There is many points in k-dimensional space. Given a point. ZLC need to find out the closest m

Points. Euclidean distance is used as the distance metric between and points. The Euclidean distance between points P and Q are the length of the line segment connecting them. In Cartesian coordinates, if p =

(P1, p2,..., pn) and q = (Q1, Q2,..., QN) is the points in Euclidean N-space, then the distance from p to Q, or from Q to P is given by:

$d \left ({{\bf{p}},{\bf{q}}} \right) = D\left ({{\bf{q}},{\bf{p}}} \right) = \sqrt {\sum\limits_{i = 1}^n {\left ({p_i-q _i} \right) ^2}}$

Can him solve this problem?

Input

In the first line of the text file. There is non-negative integers n and K. They denote respectively:the number of points, 1 <= n <= 50000, and the number of Dimensions, 1 <= K <= 5. In each of the following n lines there are written K integers, representing the coordinates of a point. This followed is a line with one positive integer t, representing the number of queries, 1 <= t <=10000.

Each query contains the lines. The k integers in the first line represent the given point. In the second line, there are one integer m, the number of closest points you should find,1 <= m <=10. The absolute value of all the coordinates is not being more than 10000. There is multiple test cases. Process to end of file.

Output

For each query, output m+1 lines:

The first line saying: "The closest m points was:" where M is the number of the points.

The following m lines representing m points, in accordance with the

It is guaranteed that the answer can are only being formed in one ways. The distances from the given point to all the nearest m+1 points is different. That means the input like this:

2 2
1 1
3 3
1
2 2
1

would not exist.

Sample Input
3 2
1 1
1 3
3 4
2
2 3
2
2 3
1

Sample Output
The closest 2 points are:
1 3
3 4
The closest 1 points are:
1 3

Test instructions

Given the points $n $ $K $, and the $t $ for each query, each query also gives a $K $ dimension point, which requires a query $n the nearest $M $ point in the distance from this point.

Exercises

Kdtree template questions.

Here's a little note about Kdtree:

1. Introduction

Kdtree (k-dimensional tree) is a data structure that supports multidimensional space, mainly divides the points in the space, and quickly maintains the operation of the space points, such as the farthest (near) point pair of space and the interval search.

The structure of the kdtree is similar to the segment tree, except that the segment tree is the operation of one-dimensional space, while the kdtree is multidimensional, which also leads to kdtree flexibility without the height of the segment tree.

Information maintained by each node on the tree:

    1. About two sons
    2. The space range represented by the point (super-box when the $K =2$ is a rectangle, $K =3$ is a box)
    3. Median point (coordinates, etc information)

2.1. Achievements

Let's say we already have a class point that describes the points in the $K $ dimension, and we already have a $a [0:n-1]$ array of type.

First, because it is a space division, the loop is progressively divided by the super-plane (or line, plane) perpendicular to each dimension axis.

For example, in the two-dimensional plane division, the vertical $x the axis of the straight line division, and then the vertical $y the axis of the straight line, and then the vertical $x the axis of the straight line to divide ...

Well, let's say that you now want to divide the lines in the vertical $x $ axis into those points on the $a [an integer interval $[l,r in the 0:n-1]$ array].

First initialize the spatial extent of the point, assuming $mid = \left\lfloor {\frac{{l + r}}{2}} \right\rfloor$, as $[l,r) $ by $x $ coordinates from small to large when sorting the median position,

Then use nth_element (st,st+n,ed) will $[l,r) $ into $[l,mid) $ and $[mid+1,r) $ two parts, the current node is stored $a [mid]$ this point,

And then recursive two intervals (as the left and right sons), of course, the two ranges are to be divided vertically $y the axis of the line, and so on.

(Wherein, the call nth_element (st,st+n,ed) method can be evaluated $[st,ed) in all elements within the section $n $ small element, and put it in the $n $ position. Note that the subscript is counted from the $st +0$, which means that the $0$ element is the smallest number, and the $0$ position is the first position. )

2.2, query $k $ nearest Neighbor

$k $ nearest neighbor is the point that finds the $k $ near, needs to maintain a large top heap, maintains the farthest distance from the current $k $ point, and if the current point is smaller than the maximum distance, update the large heap, and use the farthest distance to reduce the range that is not within the current $k $ distance.

AC Code:

#include <bits/stdc++.h>using namespacestd;Const intmaxn=5e4+Ten;Const intmaxdim=7;namespacekdtree{intK//Number of dimensionsInlineDoubleSqrDoublex) {returnx*x;} structPoint {intX[maxdim]; DoubleDistanceConstPoint &oth)Const        {            Doubleret=0;  for(intI=0; i<k;i++) Ret+=sqr (x[i]-Oth.x[i]); returnret; }        voidinput () { for(intI=0; i<k;i++) scanf ("%d",&X[i]); }        voidoutput () { for(intI=0; i<k;i++) printf ("%d%c", X[i], (i<k-1)?' ':'\ n');    }    }; structcmpx {intDiv; CMPX (Const int&_div) {div=_div;} BOOL operator()(ConstPoint &a,ConstPoint &b) { for(intI=0; i<k;i++)            {                intk= (div+i)%K; if(A.x[k]!=b.x[k])returna.x[k]<B.x[k]; }            return true;    }    }; InlineBOOLcmpConstPoint &a,ConstPoint &b,intDiv) {cmpx cp=cmpx (DIV); returnCP (A, b); }    structNode//node of the Kdtree{point E; Node*lc,*RC; intDiv; }POOL[MAXN],*tail,*Root; voidInit () {Tail=pool;}//Initialize Kdtreenode* Build (Point *a,intLintRintDiv//Achievements    {        if(L&GT;=R)returnNULL; Node*p=tail++; P->div=Div; intMid= (L+R)/2; Nth_element (A+l,a+mid,a+r,cmpx (div)); P->e=A[mid]; P->lc=build (A,l,mid, (div+1)%K); P->rc=build (a,mid+1, R, (div+1)%K); returnp; }    structQnode {point P; DoubleDist; Qnode () {} qnode (point _p,Double_dist) {p=_p; dist=_dist;} BOOL operator< (ConstQnode &oth)Const{returndist<Oth.dist;}    }; Priority_queue<Qnode>Q; voidSearch (ConstPoint &p,node *now,intDivintM//search for M neighbors of P points under now node pips tree    {        if(Now==null)return; if(CMP (p,now->e,div)) {Search (P,now-&GT;LC, (div+1)%k,m); if(Q.size () <m) {Q.push (Qnode ( now->e,p.distance (now->e))); Search (P,now-&GT;RC, (div+1)%k,m); }            Else            {                if(P.distance (Now->e) <q.top (). Dist)                    {Q.pop (); Q.push (Qnode ( now->e,p.distance (now->e))); }                if(Sqr ((Now->e.x[div))-(P.x[div]) < Q.top (). Dist) Search (P,NOW-&GT;RC, (div+1)%k,m); }        }        Else{Search (P,now-&GT;RC, (div+1)%k,m); if(Q.size () <m) {Q.push (Qnode ( now->e,p.distance (now->e))); Search (P,now-&GT;LC, (div+1)%k,m); }            Else            {                if(P.distance (Now->e) <q.top (). Dist)                    {Q.pop (); Q.push (Qnode ( now->e,p.distance (now->e))); }                if(Sqr ((Now->e.x[div))-(P.x[div]) < Q.top (). Dist) Search (P,NOW-&GT;LC, (div+1)%k,m); }        }    }    voidClosestmpoints (ConstPoint &p,intM//Search m nearest neighbor of P Point    {         while(!Q.empty ())        Q.pop (); Search (P,root,0, M); }};intn,k;intt,m; Kdtree::P oint p[maxn];vector<kdtree::P oint>ans;intMain () { while(cin>>n>>k) {kdtree::k=K;  for(intI=0; i<n;i++) P[i].input ();        Kdtree::init (); Kdtree::root=kdtree::build (P,0N0); CIN>>T;        Kdtree::P oint o;  for(intI=1; i<=t;i++) {o.input (); scanf ("%d",&m);            Kdtree::closestmpoints (O,M); printf ("The closest%d points are:\n", M);            Ans.clear ();  while(!Kdtree::q.empty ())                {Ans.push_back (Kdtree::q.top (). p);            Kdtree::q.pop (); }             for(intI=ans.size ()-1; i>=0; i--) Ans[i].output (); }    }}

HDU 4347-the Closest M Points-[kdtree template title]

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.