PTA_PAT甲級_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上界爲10^5,暴力算法必然超時,採用分塊思想,在元素存入時即把元素映射如對應塊,則每次查詢複雜度爲O(√N),N次查詢總複雜度爲O(N√N)

代碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;

#define MAXN 100010
#define sqrN 316//sqrt(1000001),表示塊內元素
stack<int> st;//棧
int block[sqrN];//記錄每一塊中存在的元素個數
int table[MAXN];//hash數組,記錄元素當前存在個數 

void peekMedia(int K){
	int sum = 0;//sum存放當前累計存在的數的個數
	int idx = 0;//塊號
	while(sum+block[idx]<K)//找到第K大的數所在塊號 
		sum += block[idx++]; 
	int num = idx*sqrN;//idx號塊的第一個數
	while(sum+table[num]<K)//從此塊中第一個元素起不斷加上每個元素的個數 
		sum += table[num++];//累加塊內元素個數,直到sum達到K 
	cout<<num<<endl; 
} 

void Push(int x){
	st.push(x);
	block[x/sqrN]++;//x所在塊的元素個數加1
	table[x]++;//x的存在個數加1 
} 

void Pop(){
	int x = st.top();
	st.pop();
	block[x/sqrN]--;//x所在塊的元素個數減1
	table[x]--; //x的存在個數減1
	cout<<x<<endl; 
} 

int main()
{
    int x, query;
    memset(block, 0, sizeof(block));
	memset(table, 0, sizeof(table));
	char cmd[20];//命令
	cin>>query;//查詢數目
	for(int i=0;i<query;i++){
		cin>>cmd;
		if(strcmp(cmd,"Push")==0){//Push x
			cin>>x;
			Push(x);
		}else if(strcmp(cmd,"Pop")==0){//Pop 
			if(st.empty()) cout<<"Invalid"<<endl;
			else Pop();
		}else{//PeekMedia
			if(st.empty()) cout<<"Invalid"<<endl;
			else{
				int K = st.size();
				K = (K%2==0) ? K/2 : (K+1)/2;
				peekMedia(K);
			}
		}
	} 
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章