Skip to content

Commit 507b5ca

Browse files
committed
max stack with std::pair
1 parent a846105 commit 507b5ca

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

1/stack_max1.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
#include <utility>
5+
6+
/* std::pair(val, max)*/
7+
struct MaxStack
8+
{
9+
void pushv(int val) {
10+
_st.empty() ? _st.push(std::make_pair(val, val))
11+
: _st.push(std::make_pair(val, std::max(val, _st.top().second)));
12+
}
13+
14+
void popv() {
15+
if (!_st.empty())
16+
_st.pop();
17+
}
18+
19+
int max() {
20+
if (!_st.empty())
21+
return _st.top().second;
22+
else
23+
return -1;
24+
}
25+
26+
private:
27+
std::stack <std::pair<int, int>> _st;
28+
};
29+
30+
void read_commands(int n)
31+
{
32+
std::string command;
33+
int val;
34+
MaxStack st;
35+
int ret;
36+
37+
std::vector<int> log;
38+
while (n != 0)
39+
{
40+
std::cin >> command;
41+
if (command == "max")
42+
{
43+
ret = st.max();
44+
if (ret >= 0)
45+
log.push_back(ret);
46+
}
47+
else if (command == "pop")
48+
st.popv();
49+
else if (command == "push")
50+
{
51+
std::cin >> val;
52+
st.pushv(val);
53+
}
54+
--n;
55+
}
56+
for (int i = 0; i < log.size(); ++i)
57+
std::cout << log[i] << std::endl;
58+
}
59+
60+
int main(void)
61+
{
62+
int n = 0;
63+
std::cin >> n;
64+
65+
if (n)
66+
read_commands(n);
67+
return 0;
68+
}

0 commit comments

Comments
 (0)