1057 Stack (30 分)【stack模拟+二分】

1057 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.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤10​5​​). 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 10​5​​.

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

题意:就是模拟堆栈,不同的是我们还要打印出中间值

解题思路:中间值用二分法处理,要不然会超时~~~,其他模拟的部分可以用stack或者vector,我这里没有直接用stack,用的是vector,一开始是超时的,后面百度了大部分都没有用柳婼学姐的树状数组,我也看不懂,还是用二分法维持一下简单点。首先是用mutilset<int>s1,s2,这个set默认是按照从小到大的排序,我们将小于等于mid的值放在s1中,大于放在s2中,然后我们做每一次的插入和删除都要调整s1,s2,也就是要保证s1的size等于s2的size或者s2size加1;遇到要取中间值就直接打印出mid值

#include<bits/stdc++.h>
using namespace std;
//char p[15];
string p;
vector<int>v,v1;
multiset<int>s1,s2;
int mid;
void adjust()
{
	multiset<int>::iterator it;
	if(s1.size()<s2.size())
	{
		it=s2.begin();
		s1.insert(*it);
		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(void)
{
	int n,va;
	scanf("%d",&n);getchar();
    while(n--)
	{
		//scanf("%s",p);
		cin>>p;
		if(p=="Pop")
		{
			int len=v.size();
			if(len==0) printf("Invalid\n");
			else 
			{
				int a=v[len-1];
				printf("%d\n",a);
				v.pop_back();
				if(a<=mid)
				{
					s1.erase(s1.find(a));
				}
				else s2.erase(s2.find(a));
				adjust();
			}
		}
		else if(p=="PeekMedian")	
		{
			int len=v.size();
			if(len==0) printf("Invalid\n");
			else 
			{
				printf("%d\n",mid);
			}
		}
		else 
		{
			getchar();
			scanf("%d",&va);
			v.push_back(va);
			if(s1.empty()) s1.insert(va);
			else if(va<=mid) s1.insert(va);
			else s2.insert(va);
			adjust();
		 }
		 
	}	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Imagirl1/article/details/83989206