#include <iostream>
#include <vector>
#include <queue>
#include <utility> // std::pair
using namespace std;
struct point{
int x;
int y;
int dis;
};
//order of priority queue
//put this outside of class
bool operator<(const point& a, const point& b) {
return a.dis > b.dis; // '>' is mini heap; '<' is max heap (max the most important one)
};
class solution{
public:
vector<pair<int, int>> topkPoints(vector<pair<int,int>> &pairs, int k){
//using priority queue
priority_queue<point> pq;
//build the queue with k ele.
for(int i=0;i<pairs.size();i++){
int dis=pairs[i].first*pairs[i].first + pairs[i].second*pairs[i].second;
point pTmp;
pTmp.x=pairs[i].first;
pTmp.y=pairs[i].second;
pTmp.dis=dis;
pq.push(pTmp);
if(pq.size()>k)pq.pop();
}
//find the k top points
vector<pair<int, int>> res;
for(int i=0;i<k;i++){
pair<int, int> tmp =make_pair(pq.top().x, pq.top().y);
pq.pop();
res.push_back(tmp);
}
return res;
}
};
// To execute C++, please define "int main()"
int main() {
vector<pair<int, int>> test;
for(int i=0;i<10;i++){
pair<int, int> p=make_pair(i,i);
test.push_back(p);
}
solution s;
vector<pair<int,int>> res=s.topkPoints(test, 2);
for(int i=0;i<res.size();i++){
cout<<res[i].first<<' '<<res[i].second;
}
return 0;
}
No comments:
Post a Comment