1. 程式人生 > >1057 Stack (30 分)【stack模擬+二分】

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;
}