PAT A1057: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

求解思路
  • 题意:给定n行命令,对于pop命令,表示弹出栈最顶端的元素并打印,如果栈为空则表示为非法操作;对于push命令,表示压栈操作,此时不打印任何元素;对于PeekMedian操作,表示返回栈的中位数。
  • 求解思路:用一个栈来存储元素,用一个哈希表hashTable来存储每个元素出现的次数,该哈希表的大小为100001;因为哈希表太大了会导致挨个查找会导致运行超时,此时采用分块的思想,定义一个数组block(大小大约为sqrt 100001,317),所以block[0]存储0~316出现的次数,block[316]存储100172 ~100048出现的次数,即大小为317的block数组完全能够存储10^5之内数字出现的次数。首先进行分块查找,每遍历一个块cnt就加上block[i],如果当前块使得cntk,则停止遍历,且往回退一块,即cnt-=block[i–],然后进入哈希表的遍历,从i*317遍历到(i+1)*317-1,每遍历一个,cnt就加上hashTable[i],如果当前cnt=k,则打印i,即当前的i为中位数
代码实现(AC)
#includecstdio
#includestack
#define MAX 100001
using namespace std;
int hashTable[MAX]={0};
int block[317]={0};
stackints;
void Pop()
{
	if(s.empty())	printf("Invalid\n");
	else
	{
		printf("%d\n",s.top());
		hashTable[s.top()]--;
		block[s.top()/317]--;
		s.pop();
	}
}
void Peekmedian()
{
	if(s.empty())	printf("Invalid\n");
	else
	{
		int blockIndex=0,cnt=0,index=0,k=(s.size()+1)/2;
		while(cntk)
			cnt+=block[blockIndex++];
		cnt-=block[--blockIndex];
		for(index=blockIndex*317;index(blockIndex+1)*317;index++)
		{
			cnt+=hashTable[index];
			if(cnt=k)	
			{
				printf("%d\n",index);
				break;
			}
		}
	}
}
void solve()
{
	int n;
	scanf("%d",n);
	while(n--)
	{
		char str[20];
		scanf("%s",str);
		if(str[1]=='o')	Pop();
		else if(str[1]=='e') Peekmedian();
		else
		{
			int num;
			scanf("%d",num);
			s.push(num);
			hashTable[num]++;
			block[num/317]++;
		}
	}
}
int main()
{
	solve();
	return 0;
}
最新回复(0)
/jishuPkt7TWSATmwyDybRLaTqM7p_2FhDMPW49CmKo6cbPrnM4_3D4794635
8 简首页