PAT 1057. Stack (30)

来源:互联网 发布:拉依达准则 c语言 编辑:程序博客网 时间:2024/05/21 19:27

1057. Stack (30)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
17PopPeekMedianPush 3PeekMedianPush 2PeekMedianPush 1PeekMedianPopPopPush 5Push 4PeekMedianPopPopPopPop
Sample Output:
InvalidInvalid322124453Invalid

乍一看挺简单的题,但是容易运行超时。主要问题就在于peekMedian时候如何快速搜索出中间值来。一开始用了一个vector来模拟vector,另一个vector来排序后选择出中间值,然而有三个点超时。然后选择用set来自动排序,然后选取中间值,依旧超时。然后想到可以用两个set,一个小的一个大,只要保证小的size和大的size要么相等要么小的比大的多1,那么小的set的末尾就是中间值了。(set隐含排序)

当然考虑到题目给的数值有可能是重复的,需要用Multiset,代码如下: 

#include <iostream>#include <vector>#include <algorithm>#include <cstring>#include <string>#include <set>using namespace std;multiset<int> small;multiset<int> big;void balance(){if(small.size()==0&&big.size()==0)return;if(small.size()<big.size()){multiset<int>::iterator it;it=big.begin();small.insert(*it);big.erase(it);}else if(small.size()-1>big.size()){multiset<int>::iterator it;it=small.end();it--;big.insert(*it);small.erase(it);}}int main(){int N,i,size;cin>>N;vector<int> mystack;getchar();while(N--){char raw[12];scanf("%s",raw);size=mystack.size();if(strcmp(raw,"Pop")==0){if(size<=0){printf("Invalid\n");continue;}else{printf("%d\n",mystack[size-1]);multiset<int>::iterator it=small.find(mystack[size-1]);if(it!=small.end())small.erase(it);else{it=big.find(mystack[size-1]);big.erase(it);}balance();mystack.pop_back();}}else if(strcmp(raw,"PeekMedian")==0){if(size<=0){printf("Invalid\n");continue;}else{multiset<int>::iterator it=small.end();it--;printf("%d\n",*it);}}else{int n;int size=small.size();scanf("%d",&n);mystack.push_back(n);if(size==0){small.insert(n);continue;}multiset<int>::iterator it=small.end();it--;if(n<=*it)small.insert(n);elsebig.insert(n);balance();}}}

 

0 0
原创粉丝点击