-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path41-middle.cpp
43 lines (36 loc) · 1.16 KB
/
41-middle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include"stdio.h"
#include"heap"
vector<int> max,min;
template<typename T>class DynamicArray
{
public:
void insert(T num)
{
if((max.size()+min.size())&1==0)//总数是奇数时插入最大堆
{
if(min.size()>0&&num>min[0])
{
min.push_back(num);
push_heap(min.begin(),min.end(),greater<T>());
num = min[0];
pop_heap(min.begin,min.end(),greater<T>());
min.pop_back();
}
max.push_back(num);
push_head(max.begin(),max.end(),less<T>());
}
else//偶数时插入最小堆
{
if(max.size()>0&&num<max[0])
{
max.push_back(num);
push_heap(max.begin(),max.end(),greater<int>());
num = max[0];
pop_head(max.begin(),max.end(),greater<int>());
max.pop_back(num);
}
min.push_back(num);
push_heap(min.begin(),min.end(),less<int>());
}
}
}