The Dean of NIT Silchar is going to visit the Hostels of NIT Silchar. As you know that he is a very busy person so he decided to visit only the first "K" nearest Hostels. Hostels are situated in the 2D plane. You are given the coordinates of hostels and you have to answer the Rocket distance of Kth nearest hostel from the origin ( Dean's place ).
Example:
Input: q = 9, k = 3, queries = {{1, 10, 10}, {1, 9, 9}, {1, -8, -8}, {2}, {1, 7, 7}, {2}, {1, 6, 6}, {1, 5, 5}, {2}}
Output:
200 162 98
Approach:
C++
#include <bits/stdc++.h>using namespace std;void solve(long long int q, long long int k,vector<vector<long long int>> &queries){long long int x, y;vector<long long int> values;for (long long int i = 0; i < k; i++){long long int ch = queries[i][0];x = queries[i][1];y = queries[i][2];long long int dist = x * x + y * y;values.push_back(dist);}sort(values.begin(), values.end());long long int greatest = values.back();for (long long int i = k; i < q; i++){long long int ch = queries[i][0];if (ch == 1){x = queries[i][1];y = queries[i][2];long long int dist = x * x + y * y;if (dist < values.back()){long long int i = 0;for (auto b : values){if (dist <= b){values.insert(values.begin() + i, dist);break;}i++;}values.pop_back();}}else{cout << values.back() << "\n";}}}int main(){long long int q = 9, k = 3;vector<vector<long long int>> queries = {{1, 10, 10},{1, 9, 9},{1, -8, -8},{2},{1, 7, 7},{2},{1, 6, 6},{1, 5, 5},{2}};solve(q, k, queries);}
No comments:
Post a Comment