-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathFebruary-18.cpp
72 lines (63 loc) · 1.72 KB
/
February-18.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
nth_element(p.begin(), p.begin() + k, p.end(), [](auto&a, auto&b){
return a[0]*a[0] + a[1]*a[1] < b[0]*b[0] + b[1]*b[1];
});
return {p.begin(), p.begin()+k};
}
};
2)
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
priority_queue<pair<int, vector<int>>> pq;
for (auto& a : p) {
int d = a[0] * a[0] + a[1] * a[1];
pq.push({d, a});
if (pq.size() > k) pq.pop();
}
vector<vector<int>> res;
while (!pq.empty()) res.push_back(pq.top().second), pq.pop();
return res;
}
};
3)
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& p, int k) {
sort(p.begin(), p.end(), [](auto& a, auto& b) {
return a[0] * a[0] + a[1] * a[1] < b[0] * b[0] + b[1] * b[1];
});
return vector<vector<int>>(p.begin(), p.begin() + k);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int k;
cin >> k;
int n;
cin >> n;
vector<vector<int>> points(n, vector<int>(2));
for (int i = 0; i < n; i++) {
cin >> points[i][0] >> points[i][1];
}
Solution ob;
vector<vector<int>> ans = ob.kClosest(points, k);
sort(ans.begin(), ans.end());
for (const vector<int>& point : ans) {
cout << point[0] << " " << point[1] << endl;
}
cout << "~" << endl;
}
return 0;
}
// } Driver Code Ends