備戰NOIP——模板複習15
阿新 • • 發佈:2018-12-19
這裡只有模板,並不作講解,僅為路過的各位做一個參考以及用做自己複習的資料,轉載註明出處。
對頂堆
(動態計算中位數)
/*Copyright: Copyright (c) 2018 *Created on 2018-11-04 *Author: 十甫 *Version 1.0 *Title: 對頂堆 *Time: ?? mins */ // 題目來源:洛谷SP15376 RMID - Running Median #include<iostream> #include<cstdio> #include<queue> #include<vector> using namespace std; priority_queue <int> big; // 大根堆存小於中位數的數 priority_queue <int, vector <int>, greater <int> > sma; // 小根堆存大於中位數的數 inline void balance() { while(big.size() > sma.size()) { sma.push(big.top()); big.pop(); } while(sma.size() > big.size()) { big.push(sma.top()); sma.pop(); } } int main() { int k; while(scanf("%d", &k) != EOF) { big.push(k); while(1) { scanf("%d", &k); if(k != -1 && k != 0) { if(k > big.top()) sma.push(k); else big.push(k); balance(); } else if(k == -1) { printf("%d\n", big.top()); big.pop(); balance(); } else { printf("\n"); break; } //printf("%d %d\n", sma.top(), big.top()); } while(!sma.empty()) { sma.pop(); } while(!big.empty()) { big.pop(); } } return 0; }