让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
问题:请解释上述代码的功能,并且给出一个示例。
回答:上述代码实现了一个数据结构,支持Push、Pop和PeekMedian操作。Push操作将元素压入栈中,并在一个有序集合中记录元素顺序;Pop操作将栈顶元素弹出,并从有序集合中删除对应元素;PeekMedian操作返回栈中位数元素。如果栈为空或者操作无效,则输出"Invalid"。
示例:
输入:
7
Push 3
Push 2
Push 1
PeekMedian
Pop
PeekMedian
Pop
输出:
2
2
1
代码示例:
#include <cstdio>
#include <string>
#include <iostream>
#include <stack>
#include <set>
using namespace std;
int n;
int main(){
cin >> n;
stack<int> s;
multiset<int> order;
int key;
for(int i = 0; i < n; i++)
{
string ope;
cin >> ope;
if(ope == "Push")
{
cin >> key;
s.push(key);
order.insert(key);
}
else if(ope == "Pop" && !s.empty())
{
int val = s.top();
cout << val << endl;
s.pop();
order.erase(val);
}
else if(ope == "PeekMedian")
{
if(order.empty())
cout << "Invalid" << endl;
else
{
int num = s.size();
num = (num % 2 == 0) ? num / 2 : (num + 1) / 2;
auto it = order.begin();
cout << (*it + num - 1) << endl;
}
}
else
{
cout << "Invalid" << endl;
}
}
return 0;
}