Stack (30)

Stack (30)
难度: ⭐⭐⭐⭐

题目连接
题目描述
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.

输入描述:
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.

输出描述:
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.

输入例子:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

输出例子:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

大意
给出三种操作:在栈的基础功能上再增加一个要求,能在任何时候够高效地取出栈里面大小排在中间的那个数。

分析
主要的难点是做一个能够随时取出中位数的数据结构,可以维护两个堆,使得任何时候第一个堆的大小不比第二个多于一,那么第一个堆的最大元素就是所需要的中位数。

MYCODE

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<string>
#include<set>
#include<stack>
using namespace std;
class Myset{
	multiset<int> s1, s2;
public:
	void balance(){
		if (s1.size() > s2.size() + 1){
			s2.insert(*s1.rbegin());
			s1.erase(s1.find(*s1.rbegin()));
		}
		else if (s1.size() < s2.size()){
			s1.insert(*s2.begin());
			s2.erase(s2.begin());
		}
	}
	void insert(int x) {
		if (s1.size() == s2.size()) {		
			s2.insert(x);		
		}
		else {
			s1.insert(x);	
		}
		balance();
	}
	void remove(int i){	//因为i从stack中取出,所以比然在堆中
		multiset<int>::iterator t1 = s1.find(i), t2 = s2.find(i);
		if (t2 != s2.end())		s2.erase(t2);
		else 	s1.erase(t1);
		balance();
	}
	int getMid() {
		return *s1.rbegin();
	}
};
	
int main(){
	int n;
	Myset myset;
	stack<int> mystck;
	cin >> n;
	while (n--){
		string ope;
		cin >> ope;
		//myset.test();
		if (ope == "Push"){
			int t;
			scanf("%d", &t);
			mystck.push(t);
			myset.insert(t);
		}
		else if (mystck.empty()){
			cout << "Invalid\n";
		}else if( ope=="Pop" ){
			int top = mystck.top();
			cout << top << endl;
			myset.remove(top);
			mystck.pop();
		}
		else{
			cout << myset.getMid() << endl;;
		}
	}
	return 0;
}

备忘录

代码中某些细节或者规律没有把握好久会造成很难发现的bug:在insert()中,当两个堆大小相等时,必须要将数插入到第二个,否则不会调用balance(), balance()的作用不仅是维护两个堆的大小关系,还必须维护左边堆的数全部小于等于右边的数。

myset.begin() 对应堆中最小的那个数,myset.rbegin()则是最大的那个数,不是end(),需要区分开。而且注意rbegin()返回的迭代器与begin()不同,不能用在erase()上,这时可以用find(*rbegin())的方式来找到删除堆中最大那个数。

发布了90 篇原创文章 · 获赞 31 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/95672737