4860 置换选择 PAT1171
作者:
NikoNairre
,
2023-11-26 09:48:13
,
所有人可见
,
阅读 77
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
priority_queue<int, vector<int>, greater<int>> cu_hp, ne_hp; //small heap, ne_hp stores nums ordered in next block
int n, m;
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
int cur_top; //denote current heap top(smallest)
int cnt = 0; //control " " and endl in output
for (int i = 0; i < n; i++ ) {
int x; cin >> x; //cin n numbers
if (i < m) {
cu_hp.push(x); //directly put the first m numbers into heap
if (i == m - 1) { //currnt hp full for the first, record top value and print
cur_top = cu_hp.top(); cu_hp.pop();
if (cnt) cout << " ";
cnt++ ;
cout << cur_top;
}
}
else { //the next (n - m) values need to be judged which heap to put
if (x < cur_top) {ne_hp.push(x);} //x is smaller than current heap top, so it shoule be put into next block
else {
cu_hp.push(x); //x >= cur_top, so it can be put into current block
}
if (cu_hp.empty()) { //no more nums can put into current block, this block finished
swap(cu_hp, ne_hp); //it's time to focus on the next block, this meanwhile clear ne_hp at the same time
cout << endl;
cnt = 0; //refresh output flag
}
cur_top = cu_hp.top(); cu_hp.pop(); //after i >= m-1, top value need to be printed
if (cnt) cout << " ";
cnt++;
cout << cur_top;
}
}
while (!cu_hp.empty()) { //print remaining nums in current block(if exists)
if (cnt) cout << " ";
cnt++ ;
cur_top = cu_hp.top(); cu_hp.pop();
cout << cur_top;
}
cnt = 0;
if (!ne_hp.empty()) cout << endl; //print remaining nums in next block(if exists)
while (!ne_hp.empty()) {
if (cnt) cout << " ";
cnt++ ;
cur_top = ne_hp.top(); ne_hp.pop();
cout << cur_top;
}
return 0;
}