Skip to content

Commit 8f79273

Browse files
committed
max queue
1 parent c79d2da commit 8f79273

1 file changed

Lines changed: 124 additions & 0 deletions

File tree

1/window.c

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
#include <utility>
5+
6+
/* std::pair(val, max)*/
7+
struct MaxStack
8+
{
9+
void push(int val) {
10+
11+
_st.empty() ? _st.push(std::make_pair(val, val))
12+
: _st.push(std::make_pair(val, std::max(val, _st.top().second)));
13+
}
14+
15+
void pop() {
16+
if (!_st.empty())
17+
_st.pop();
18+
}
19+
20+
int max() {
21+
if (!_st.empty())
22+
return _st.top().second;
23+
else
24+
return -1;
25+
}
26+
27+
int top() {
28+
if (!_st.empty())
29+
return _st.top().first;
30+
else
31+
return -1;
32+
}
33+
34+
bool empty() { return _st.empty(); }
35+
36+
int size() { return _st.size(); }
37+
38+
private:
39+
std::stack <std::pair<int, int>> _st;
40+
};
41+
42+
struct MaxQueue
43+
{
44+
void push(int val) { _left.push(val); }
45+
46+
void pop() {
47+
if (_right.empty())
48+
{
49+
int size = _left.size();
50+
for (int i = 0; i < size; ++i)
51+
{
52+
int tmp = _left.top();
53+
_left.pop();
54+
_right.push(tmp);
55+
}
56+
}
57+
_right.pop();
58+
}
59+
60+
int max() {
61+
if (_right.empty())
62+
{
63+
int size = _left.size();
64+
for (int i = 0; i < size; ++i)
65+
{
66+
int tmp = _left.top();
67+
_left.pop();
68+
//std::cout << "push right " << tmp << std::endl;
69+
_right.push(tmp);
70+
}
71+
}
72+
return std::max(_right.max(), _left.max());
73+
}
74+
75+
int size() {
76+
return _left.size() + _right.size();
77+
}
78+
79+
private:
80+
MaxStack _left;
81+
MaxStack _right;
82+
};
83+
84+
int main(void)
85+
{
86+
int n, win;
87+
88+
std::cin >> n;
89+
90+
std::vector<int> input(n);
91+
92+
93+
for (int i = 0; i < n; ++i)
94+
std::cin >> input[i];
95+
96+
std::cin >> win;
97+
int outsize = n - win + 1;
98+
std::vector<int> output (outsize);
99+
100+
MaxQueue q;
101+
int i = 0;
102+
int j = 0;
103+
104+
while (i < win)
105+
{
106+
q.push(input[i]);
107+
++i;
108+
}
109+
output[j] = q.max();
110+
++j;
111+
112+
while (i < n)
113+
{
114+
q.pop();
115+
q.push(input[i]);
116+
output[j] = q.max();
117+
++j;
118+
++i;
119+
}
120+
121+
for (int i = 0; i < output.size(); ++i)
122+
std::cout << output[i] << " ";
123+
return 0;
124+
}

0 commit comments

Comments
 (0)