-
Notifications
You must be signed in to change notification settings - Fork 1
/
6A2.cpp
153 lines (118 loc) · 1.77 KB
/
6A2.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <bits/stdc++.h>
using namespace std;
#define MOD 10000
class HeapY
{
vector<int> v;
bool m;
void swap(int x, int y)
{
int temp = v[x];
v[x] = v[y];
v[y] = temp;
}
void siftDown(int i)
{
if(i >= v.size())
return;
int l = i*2;
int r = i*2 + 1;
int optimal= i;
if(l < v.size() && ((m && v[l] > v[optimal]) || (!m && v[l] < v[optimal])) )
optimal = l;
if(r < v.size() && ((m && v[r] > v[optimal]) || (!m && v[r] < v[optimal])) )
optimal = r;
if(optimal != i)
{
swap(optimal, i);
siftDown(optimal);
}
}
void siftUp(int i)
{
if(i == 0)
return;
int par = i/2;
if((m && v[i] > v[par]) || (!m && v[i] < v[par]))
{
swap(i, par);
siftUp(par);
}
}
public:
void setMode(bool mode)
{
m = mode;
}
bool empty(void)
{
return v.empty();
}
int peekRoot(void)
{
return v[0];
}
int extractRoot(void)
{
int x = v[0];
v[0] = v[v.size()-1];
v.pop_back();
siftDown(0);
return x;
}
void insert(int x)
{
v.push_back(x);
siftUp(v.size()-1);
}
int size(void)
{
return v.size();
}
};
int main()
{
freopen("Median.txt", "r", stdin);
int N = 10000;
HeapY maxx;
HeapY minn;
maxx.setMode(1);
minn.setMode(0);
int rMedian = 0;
int x;
for(int i=0;i<N;i++)
{
cin>>x;
if(maxx.empty())
maxx.insert(x);
else
{
int maxL = maxx.peekRoot();
if(x <= maxL)
{
if(maxx.size() == minn.size())
maxx.insert(x);
else
{
int z = maxx.extractRoot();
minn.insert(z);
maxx.insert(x);
}
}
else
{
minn.insert(x);
if(maxx.size() == minn.size())
;
else
{
int z = minn.extractRoot();
maxx.insert(z);
}
}
}
rMedian = (rMedian + maxx.peekRoot()%MOD) % MOD;
}
cout<<rMedian<<endl;
return 0;
}