MCPcopy Create free account
hub / github.com/SuprDewd/CompetitiveProgramming / naive_kd_tree

Class naive_kd_tree

code/data-structures/kd_tree.test.cpp:2–59  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1template <int K>
2struct naive_kd_tree {
3
4 struct point {
5 double coord[K];
6 point() {}
7 point(double c[K]) {
8 for (int i = 0; i < K; i++)
9 coord[i] = c[i];
10 }
11
12 double dist_to(const point &other) const {
13 double sum = 0.0;
14 for (int i = 0; i < K; i++)
15 sum += pow(coord[i] - other.coord[i], 2.0);
16 return sqrt(sum);
17 }
18
19 bool operator <(const point &other) const {
20 for (int i = 0; i < K; i++)
21 if (abs(coord[i] - other.coord[i]) > EPS)
22 return coord[i] < other.coord[i];
23 return false;
24 }
25 };
26
27 set<point> pts;
28
29 naive_kd_tree() { }
30 naive_kd_tree(vector<point> _pts) {
31 for (int i = 0; i < size(_pts); i++) {
32 pts.insert(_pts[i]);
33 }
34 }
35
36 bool contains(const point &p) {
37 return pts.find(p) != pts.end();
38 }
39
40 void insert(const point &p) {
41 pts.insert(p);
42 }
43
44 pair<point, bool> nearest_neighbour(const point &p, bool allow_same = true) {
45 double mn = INFINITY;
46 point res;
47 bool found = false;
48 for (typename set<point>::const_iterator it = pts.begin(); it != pts.end(); ++it) {
49 double dist = p.dist_to(*it);
50 if (abs(dist) < EPS && !allow_same) continue;
51 if (dist < mn) {
52 mn = dist;
53 res = *it;
54 found = true;
55 }
56 }
57 return make_pair(res, found);
58 }
59};
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected