A479.最小栈
2025-11-09 08:48:38
发布于:江苏
0阅读
0回复
0点赞
用空间换时间——维护栈中最小值
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class int_stack {
//stk:维护栈里元素
//minv:维护进栈后最小元素
stack<int> stk, minv;
public:
void push(int x) {
stk.push(x);
if (minv.empty()) minv.push(x);
else minv.push(min(minv.top(), x));
}
void pop(void) {
if (stk.empty()) {
cout << "error\n";
return;
}
stk.pop();
minv.pop();
}
void top(void) {
if (stk.empty()) {
cout << "error\n";
return;
}
cout << stk.top() << '\n';
}
void getmin(void) {
if (minv.empty()) {
cout << "error\n";
return;
}
cout << minv.top() << '\n';
}
} stk;
int n;
string op; int x;
int main() {
cin >> n;
while (n--) {
cin >> op;
if (op == "push") {
cin >> x;
stk.push(x);
}
if (op == "pop") {
stk.pop();
}
if (op == "top") {
stk.top();
}
if (op == "get_min") {
stk.getmin();
}
}
return 0;
}
这里空空如也


有帮助,赞一个