मान लीजिए, हमें एक खाली अनुक्रम और n प्रश्न दिए गए हैं जिन्हें हमें संसाधित करना है। प्रश्न सरणी प्रश्नों में दिए गए हैं और वे प्रारूप {क्वेरी, डेटा} में हैं। प्रश्न निम्नलिखित तीन प्रकार के हो सकते हैं-
-
क्वेरी =1:आपूर्ति किए गए डेटा को अनुक्रम के अंत में जोड़ें।
-
क्वेरी =2:अनुक्रम की शुरुआत में तत्व को प्रिंट करें। उसके बाद तत्व को हटा दें।
-
क्वेरी =3:अनुक्रम को आरोही क्रम में क्रमबद्ध करें।
ध्यान दें, क्वेरी प्रकार 2 और 3 में हमेशा डेटा =0 होता है।
इसलिए, यदि इनपुट n =9 की तरह है, तो क्वेरीज़ ={{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}, तो आउटपुट 5 और 1 होगा।
प्रत्येक प्रश्न के बाद का क्रम नीचे दिया गया है -
- 1:{5}
- 2:{5, 4}
- 3:{5, 4, 3}
- 4:{5, 4, 3, 2}
- 5:{5, 4, 3, 2, 1}
- 6:{4, 3, 2, 1} , प्रिंट 5.
- 7:{1, 2, 3, 4}
- 8:{2, 3, 4}, प्रिंट 1.
- 9:{2, 3, 4}
इसे हल करने के लिए, हम इन चरणों का पालन करेंगे -
priority_queue<int> priq
Define one queue q
for initialize i := 0, when i < n, update (increase i by 1), do:
operation := first value of queries[i]
if operation is same as 1, then:
x := second value of queries[i]
insert x into q
otherwise when operation is same as 2, then:
if priq is empty, then:
print first element of q
delete first element from q
else:
print -(top element of priq)
delete top element from priq
otherwise when operation is same as 3, then:
while (not q is empty), do:
insert (-first element of q) into priq and sort
delete element from q उदाहरण
आइए बेहतर समझ पाने के लिए निम्नलिखित कार्यान्वयन देखें -
#include <bits/stdc++.h>
using namespace std;
void solve(int n, vector<pair<int, int>> queries){
priority_queue<int> priq;
queue<int> q;
for(int i = 0; i < n; i++) {
int operation = queries[i].first;
if(operation == 1) {
int x;
x = queries[i].second;
q.push(x);
} else if(operation == 2) {
if(priq.empty()) {
cout << q.front() << endl;
q.pop();
} else {
cout << -priq.top() << endl;
priq.pop();
}
} else if(operation == 3) {
while(!q.empty()) {
priq.push(-q.front());
q.pop();
}
}
}
}
int main() {
int n = 9; vector<pair<int, int>> queries = {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}};
solve(n, queries);
return 0;
} इनपुट
9, {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}
आउटपुट
5 1