K points to origin
Given a bounch of points, ask to find K closest point to origin.
This question can be changed. For example, here is origin, but there might be another point.
Here is just a basic algorithm.
// main.cpp
// k points to origin
// Created by Xiaohe Huang on 10/19/15.
// Copyright © 2015 Xiaohe Huang. All rights reserved.
//
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct Cpoint
{
double x;
double y;
};
struct cmp
{
public:
bool operator()(Cpoint n1,Cpoint n2)
{
return (n1.x)*(n1.x)+(n1.y)*(n1.y)<(n2.x)*(n2.x)+(n2.y)*(n2.y);
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Cpoint points[5];
points[0]={9,9};
points[1]={8,8};
points[2]={7,7};
points[3]={6,6};
points[4]={5,5};
priority_queue<Cpoint,vector<Cpoint>,cmp> pq;
for(int i;i<5;i++)
{
if(i<3)
pq.push(points[i]);
else
{
if((points[i].x)*(points[i].x)+(points[i].y)+(points[i].y)<(pq.top().x+pq.top().x)+(pq.top().y+pq.top().y))
{
pq.pop();
pq.push(points[i]);
}
}
}
return 0;
}