简体   繁体   中英

minimum distance between 2 points in c++

I'm given m places (x,y coordinates).

I have n requests of finding the closest place to a given point P(x,y); (The minimum Euclidian distance)

How can i solve this problem below O(n*m) where n is the number of requests and m the number of places? I could use squared Euclidian distances but it's still n*m.

Try a kd-tree . A high performance library implementation can be found here .

Note: I'm pointing you to an approximate nearest-neighbors search which is optimized for high dimensions. This may be slightly overkill for your application.

Edit:

For a 2d kd-tree, the build time would be O(m*log(m)) and the query time would be O(n*sqrt(m)). This should end up being a net win over the naive solution if your number of queries n, exceeds log(m).

The library means you don't have to implement it so the complexity shouldn't be an issue.

If you want to generalize to high dimension extremely fast querying, check out locality sensitive hashing .

Interesting. To reduce the effect of n, I wonder if perhaps it would help to save the result of each request as you encounter and handle it. A clever result table might shortcut the need to calculate sqrt( x 2 + y 2 ) in solving subsequent requests.

The Nearest-Neighbor-Problem , eh? I found Robert Sedgewick Std Book very useful in these cases. He describes Nearest Neighbour Search , too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM