//
// main.cpp
// K nearest neighbors
//
// Created by Himanshu on 18/08/21.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
int const N = 5;
bool cmp( const vector<float>& p,
const vector<float>& q ) {
return p[1] > q[1];
}
void solve (int points[][2], int point[], int k) {
vector< vector<float> > minHeap;
for (int i=0; i<N; i++) {
float d = sqrt((pow((point[0] - points[i][0]), 2)) + (pow((point[1] - points[i][1]), 2)));
float pos = i;
minHeap.push_back({pos, d});
push_heap(minHeap.begin(), minHeap.end(), &cmp);
}
cout<<"K nearest neighbors:"<<endl;
for (int i=0; i<k; i++) {
vector<float> nearestPoints = minHeap.front();
pop_heap(minHeap.begin(), minHeap.end(), &cmp);
minHeap.pop_back();
cout<<nearestPoints[0]<<" - distance: "<<nearestPoints[1]<<endl;
}
}
int main () {
int points[N][2] = {{1, 1}, {3, 4}, {2, 3}, {7, 8}, {2, 5}};
int point[2] = {0, 0};
int k = 2;
solve(points, point, k);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBLIG5lYXJlc3QgbmVpZ2hib3JzCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDE4LzA4LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8bWF0aC5oPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwppbnQgY29uc3QgTiA9IDU7Cgpib29sIGNtcCggY29uc3QgdmVjdG9yPGZsb2F0PiYgcCwKICAgICAgICAgICAgICAgY29uc3QgdmVjdG9yPGZsb2F0PiYgcSApIHsKICAgIHJldHVybiBwWzFdID4gcVsxXTsKfQoKdm9pZCBzb2x2ZSAoaW50IHBvaW50c1tdWzJdLCBpbnQgcG9pbnRbXSwgaW50IGspIHsKICAgIHZlY3RvcjwgdmVjdG9yPGZsb2F0PiA+IG1pbkhlYXA7CiAgICAKICAgIGZvciAoaW50IGk9MDsgaTxOOyBpKyspIHsKICAgICAgICBmbG9hdCBkID0gc3FydCgocG93KChwb2ludFswXSAtIHBvaW50c1tpXVswXSksIDIpKSArIChwb3coKHBvaW50WzFdIC0gcG9pbnRzW2ldWzFdKSwgMikpKTsKICAgICAgICBmbG9hdCBwb3MgPSBpOwogICAgICAgIG1pbkhlYXAucHVzaF9iYWNrKHtwb3MsIGR9KTsKICAgICAgICBwdXNoX2hlYXAobWluSGVhcC5iZWdpbigpLCBtaW5IZWFwLmVuZCgpLCAmY21wKTsKICAgIH0KICAgIAogICAgY291dDw8IksgbmVhcmVzdCBuZWlnaGJvcnM6Ijw8ZW5kbDsKICAgIGZvciAoaW50IGk9MDsgaTxrOyBpKyspIHsKICAgICAgICB2ZWN0b3I8ZmxvYXQ+IG5lYXJlc3RQb2ludHMgPSBtaW5IZWFwLmZyb250KCk7CiAgICAgICAgcG9wX2hlYXAobWluSGVhcC5iZWdpbigpLCBtaW5IZWFwLmVuZCgpLCAmY21wKTsKICAgICAgICBtaW5IZWFwLnBvcF9iYWNrKCk7CiAgICAgICAgY291dDw8bmVhcmVzdFBvaW50c1swXTw8IiAtIGRpc3RhbmNlOiAiPDxuZWFyZXN0UG9pbnRzWzFdPDxlbmRsOwogICAgfQogICAgCn0KCmludCBtYWluICgpIHsKICAgIGludCBwb2ludHNbTl1bMl0gPSB7ezEsIDF9LCB7MywgNH0sIHsyLCAzfSwgezcsIDh9LCB7MiwgNX19OwogICAgaW50IHBvaW50WzJdID0gezAsIDB9OwogICAgaW50IGsgPSAyOwogICAgc29sdmUocG9pbnRzLCBwb2ludCwgayk7CiAgICByZXR1cm4gMDsKfQo=