How can we solve this efficiently can we do this without popping and pushing that i'm doing

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {

ll n,k;
cin>>n>>k;

priority_queue<ll, vector<ll> , greater<ll>>pq;

for(ll i=0;i<n;i++){
	ll t;
	cin>>t;
	if(t==1){
		ll x,y;
		cin>>x>>y;
		pq.push(x*x + y*y);
	}
	else{
		vector<ll>v;
		for(ll i=0;i<k;i++){
			v.push_back(pq.top());
			pq.pop();
		}
		cout<<v[k-1]<<endl;
		for(ll i=0;i<k;i++){
			pq.push(v[i]);
		}
	}
}

return 0;

}

hello @talhashamim001

use max heap to answer this query efficiently.

For every query of type 1, insert elements until the size of the heap becomes ‘k’.
Then for every query of type 1 after reaching the size k for heap(max-heap) we will check if the current element is smaller than the root of the heap or not. If it is not smaller then we ignore it else we remove the root of the heap and push the new element in the heap. (What this will do is maintain a heap of size k which will contain k nearest coordinates for the dean) .
For every query of type 2 just print the root of the heap.

#include <bits/stdc++.h>
using namespace std;

#define int long long 

int32_t main () {
	int n, k; cin >> n >> k;
	priority_queue <int> pq;
	for (int i = 0; i < n; i++) {
		int qtype; cin >> qtype;
		if (qtype == 1) {
			int x, y; cin >> x >> y;
			pq.push(x*x + y*y);
		} else {
			while (pq.size() != k) {
				pq.pop();
			}
			cout << pq.top() << "\n";
		}
	}
	return 0;
}

#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { priority_queuepq; ll n,k; cin>>n>>k; while(n–){ ll a,x,y; cin>>a; if(a==1){ cin>>x>>y; if(pq.size()<k){ pq.push(xx+yy); }else{ pq.pop(); pq.push(xx+yy); } } else{ cout<<pq.top()<<endl; } } return 0; }

checck now->

got it thanks…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.