PTA-甲级 1057 Stack (超时)
Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤105). Then N lines follow, each contains a command in one of the following 3 formats:
Push key
Pop
PeekMedian
where key
is a positive integer no more than 105.
Output Specification:
For each Push
command, insert key
into the stack and output nothing. For each Pop
or PeekMedian
command, print in a line the corresponding returned value. If the command is invalid, print Invalid
instead.
Sample Input:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
注意点:
排序问题: 用系统自带的sort排序会超时,这里参考大佬的想法使用二分法。
知识点:
-
用multiset实现二分法
-
vector的常用用法
(1)
empty()
判断是否为空,为空返回1;(2)
size()
判断vector的大小,返回元素个数;(3)
pop_back()
删除vector中的最后一个元素,无返回值;(4)
push_back(elem)
在vector的最后添加元素;(5)
sort(vec.begin(),vec.end())
vector的简单排序方式(从大到小);
参考:
大佬的AC代码
https://blog.csdn.net/Imagirl1/article/details/83989206
multiset用法总结
C++ vector 容器浅析
https://www.runoob.com/w3cnote/cpp-vector-container-analysis.html
代码
#include<iostream>
#include<vector>
#include<set>
using namespace std;
int mid;
// 自动将元素进行排序(允许元素重复)
multiset<int>s1,s2;
void adjust(){
multiset<int>::iterator it; // 迭代器
if(s1.size()<s2.size()){
// 返回一个随机存取迭代器,指向第一个元素
it=s2.begin();
// 插入一个elem副本,返回新元素位置,无论插入成功与否
s1.insert(*it);
// 移除迭代器pos所指位置元素,无返回值
s2.erase(it);
}
if(s1.size()>s2.size()+1){
// 返回一个随机存取迭代器,指向最后一个元素的下一个位置
it=s1.end();
it--;
s2.insert(*it);
s1.erase(it);
}
if(!s1.empty()){
it=s1.end();
it--;
mid=*it;
}
}
int main(){
int n;
vector<int> vec;
string str;
int length;
cin>>n;
for(int i=0; i<n; i++){
cin>>str;
if(str=="Pop"){
length=vec.size();
if(vec.empty()){
cout<<"Invalid\n";
}
else{
int po=vec[length-1];
vec.pop_back();
cout<<po<<'\n';
if(po<=mid){
// 返回元素值为elem的第一个元素,如果没有返回end()
s1.erase(s1.find(po));
}
else{
s2.erase(s2.find(po));
}
adjust();
}
}
else if(str=="PeekMedian"){
if(vec.empty()){
cout<<"Invalid\n";
}
else{
cout<<mid<<'\n';
}
}
else if(str=="Push"){
int newdata;
cin>>newdata;
vec.push_back(newdata);
if(s1.empty()||newdata<=mid){
s1.insert(newdata);
}
else{
s2.insert(newdata);
}
adjust();
}
}
}