Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. /*
  2. Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them.
  3.  
  4. The distance between two points on a plane is the Euclidean distance.
  5.  
  6. You may return the answer in any order.
  7.  
  8. Input format
  9. First line contains 2 integers N, K - Number of points and the integer K.
  10.  
  11. Next N lines contain 2 integers x, y - The coordinates of the points.
  12.  
  13. Output format
  14. Print K lines each containing the coordinates of the closest points.
  15.  
  16. Sample Input 1
  17. 5 3
  18.  
  19. 1 0
  20.  
  21. -4 2
  22.  
  23. 2 -3
  24.  
  25. 3 5
  26.  
  27. 0 2
  28.  
  29. Sample Output 1
  30. 1 0
  31.  
  32. 2 -3
  33.  
  34. 0 2
  35.  
  36. Explanation
  37. Distances of points are:
  38.  
  39. Point (1,0) = sqrt(1)
  40.  
  41. Point (-4,2) = sqrt(20)
  42.  
  43. Point (2,-3) = sqrt(13)
  44.  
  45. Point (3,5) = sqrt(34)
  46.  
  47. Point (0,2) = sqrt(4)
  48.  
  49. Points (1,0), (0,2) and (2,-3) have the least distance from the origin.
  50.  
  51. Constraints
  52. 1 <= N <= 10^5
  53.  
  54. 1 <= K <= N
  55.  
  56. -10^6 <= Xi, Yi <= 10^6
  57. */
  58.  
  59. unsigned long long getDistance(int x,int y){
  60.     // unsigned long long distance=(x*x+y*y);
  61.     long X=x;
  62.     long Y=y;
  63.     // long long distance = static_cast<long long>(x) * x + static_cast<long long>(y) * y;
  64.     unsigned long long distance=(X*X+Y*Y);
  65.     return distance;
  66. }
  67.  
  68. struct comparator{
  69.     bool operator()( pair<unsigned long long,pair<int,int>>& p1, pair<unsigned long long,pair<int,int>>& p2){
  70.     return p1.first<p2.first;
  71.     }
  72. };
  73. vector<vector<int>> kClosestPointsToOrigin(vector<vector<int>> points, int k){
  74.     vector<vector<int>> ans;
  75.     priority_queue< pair<unsigned long long,pair<int,int>> ,
  76.     vector< pair<unsigned long long,pair<int,int>> >,
  77.     comparator
  78.     >pq;
  79.     unsigned long long len=points.size();
  80.     for(int i=0;i<len;i++){
  81.         int x=points[i][0];
  82.         int y=points[i][1];
  83.         pair<int,int>p={x,y};
  84.         unsigned long long distance=getDistance(x,y);
  85.         pq.push({distance,p});
  86.         if(pq.size()>k)
  87.         pq.pop();
  88.     }
  89.     while(!pq.empty()){
  90.         auto tmp=pq.top();
  91.         vector<int>currentPoint={tmp.second.first,tmp.second.second};
  92.         ans.push_back(currentPoint);
  93.         pq.pop();
  94.     }
  95.  
  96.     return ans;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement