-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest41.cpp
77 lines (67 loc) · 1.15 KB
/
test41.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<exception>
using namespace std;
class Mid
{
public:
void insert(int num);
double GetMid();
private:
vector<int> max;
vector<int> min;
};
void Mid::insert(int 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<int>());
num=min[0];
pop_heap(min.begin(),min.end(),greater<int>());
min.pop_back();
}
max.push_back(num);
push_heap(max.begin(),max.end());
}
else
{
if(max.size()>0 && num<max[0])
{
max.push_back(num);
push_heap(max.begin(),max.end());
num=max[0];
pop_heap(max.begin(),max.end());
max.pop_back();
}
min.push_back(num);
push_heap(min.begin(),min.end(),greater<int>());
}
}
double Mid::GetMid()
{
if(max.size()+min.size()==0)
{
throw exception();
}
if(((max.size()+min.size())&1)==0)
return (double)(min[0]+max[0])/2;
else
return max[0];
}
int main()
{
Mid m;
int a[]={6,1,2,9,3,20,14,12};
int len=sizeof(a)/sizeof(a[0]);
for(int i=0;i<len;++i)
{
m.insert(a[i]);
cout<<m.GetMid()<<endl;
}
return 0;
}