文心一言生成题解
2024-02-16 21:06:31
发布于:浙江
17阅读
0回复
0点赞
#include <iostream>
#include <stack>
#include <stdexcept>
class MinStack {
private:
std::stack<int> s;
std::stack<int> min_s;
public:
void push(int x) {
s.push(x);
if (min_s.empty() || x <= min_s.top()) {
min_s.push(x);
}
}
void pop() {
if (s.empty()) {
throw std::out_of_range("error");
}
if (s.top() == min_s.top()) {
min_s.pop();
}
s.pop();
}
int top() {
if (s.empty()) {
throw std::out_of_range("error");
}
return s.top();
}
int get_min() {
if (min_s.empty()) {
throw std::out_of_range("error");
}
return min_s.top();
}
};
int main() {
int n;
std::cin >> n;
MinStack ms;
for (int i = 0; i < n; ++i) {
std::string op;
std::cin >> op;
if (op == "push") {
int x;
std::cin >> x;
ms.push(x);
} else if (op == "pop") {
try {
ms.pop();
} catch (const std::out_of_range& e) {
std::cout << e.what() << std::endl;
}
} else if (op == "top") {
try {
std::cout << ms.top() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << e.what() << std::endl;
}
} else if (op == "get_min") {
try {
std::cout << ms.get_min() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << e.what() << std::endl;
}
} else {
std::cout << "error" << std::endl;
}
}
return 0;
}
这里空空如也
有帮助,赞一个