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 (≤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.

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

题目大意:有一种特殊的栈,除了原本的 pop 和 push 操作,还有一种 PeekMedian 操作,查询当前栈中所有元素的中位数。现给出 N 次操作,对于 pop 操作 和 PeekMedian 操作,如果栈不为空,输出对应的值,为空则输出 Invalid。

分析:用分块的思想解决。题目已知输入的所有数字都不超过 10 的 5 次方,可以把这 10 的 5 次方的空间划分为 317 个块,每个块共 317 个元素 (317*317>100000),并用一个数组,记录每个块存储了多少个元素;再建立一个栈模拟操作。每次 push 一个值 x,把对应位置的下标 num[x/317][x-x/317*317] 值+1,记录这个数出现的次数。每次 pop,也找到对应位置,把这个值-1. PeekMedian 操作时,遍历所有块,找到中位数即可。

#include
#include 
#include  
#include  
#include   
#include   
#include   
#include    
#include    
#include    
#include    
#include      
#include      
#define INF 0x3fffffff
#define db1(x) cout<<#x<<"="<<(x)<cnt_blocks[index])mid-=cnt_blocks[index];
                    else break;
                }
                for(int i=0;i<=blocks;++i)
                {
                    mid-=num_blocks[index][i];
                    if(mid<=0)
                    {
                        printf("%d\n",index*blocks+i);
                        break;
                    }
                }
            }
        }
    }

    #ifdef test
    clockid_t end=clock();
    double endtime=(double)(end-start)/CLOCKS_PER_SEC;
    printf("\n\n\n\n\n");
    cout<<"Total time:"<

你可能感兴趣的:(PAT刷题,pat考试)