점 집합이 있다고 가정합니다. 우리의 임무는 원점에 가장 가까운 K 포인트를 찾는 것입니다. 점이 (3, 3), (5, -1) 및 (-2, 4)라고 가정합니다. 그런 다음 가장 가까운 두 점(K =2)은 (3, 3), (-2, 4)입니다.
이 문제를 해결하기 위해 유클리드 거리를 기반으로 포인트 목록을 정렬한 다음 정렬된 목록에서 가장 높은 K 요소를 가져옵니다. K개의 가장 가까운 점입니다.
예시
#include<iostream>
#include<algorithm>
using namespace std;
class Point{
private:
int x, y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
void display(){
cout << "("<<x<<", "<<y<<")";
}
friend bool comparePoints(Point &p1, Point &p2);
};
bool comparePoints(Point &p1, Point &p2){
float dist1 = (p1.x * p1.x) + (p1.y * p1.y);
float dist2 = (p2.x * p2.x) + (p2.y * p2.y);
return dist1 < dist2;
}
void closestKPoints(Point points[], int n, int k){
sort(points, points+n, comparePoints);
for(int i = 0; i<k; i++){
points[i].display();
cout << endl;
}
}
int main() {
Point points[] = {{3, 3},{5, -1},{-2, 4}};
int n = sizeof(points)/sizeof(points[0]);
int k = 2;
closestKPoints(points, n, k);
} 출력
(3, 3) (-2, 4)