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 keyPop
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 PopSample Output:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
采用树状数组以及scanf和printf
1 #include <cstdio> 2 #include <stack> 3 #include <string> 4 #include <cstring> 5 6 using namespace std; 7 8 #define MAXSIZE 100001 9 class BinaryIndexTree 10 { 11 private: 12 int numbers[MAXSIZE]; 13 int size; 14 int lowbit(int x){ return x&(-x); } 15 public: 16 BinaryIndexTree(int size){ memset(numbers, 0, (size + 1)*sizeof(int)); this->size = size; } 17 void Update(int x, int num); 18 int GetSum(int x); 19 int Find(int value, int left, int right); 20 }; 21 22 void BinaryIndexTree::Update(int x, int num) 23 { 24 while (x <= size) 25 { 26 numbers[x] += num; 27 x += lowbit(x); 28 } 29 } 30 31 int BinaryIndexTree::GetSum(int x) 32 { 33 int sum = 0; 34 while (x > 0) 35 { 36 sum += numbers[x]; 37 x -= lowbit(x); 38 } 39 return sum; 40 } 41 42 int BinaryIndexTree::Find(int value, int left=0, int right = MAXSIZE-1) 43 { 44 if (left == right) 45 return left; 46 int mid = (left + right) / 2; 47 if (GetSum(mid) < value) 48 return Find(value, mid + 1, right); 49 else 50 return Find(value, left, mid); 51 } 52 53 int main() 54 { 55 int opNum; 56 scanf("%d", &opNum); 57 58 stack<int> s; 59 BinaryIndexTree array(100000); 60 for (int i = 0; i < opNum; i++) 61 { 62 char c[10]; 63 scanf("%s", c); 64 string op(c); 65 if (op == "Pop") 66 { 67 if (s.empty()) 68 printf("Invalid\n"); 69 else 70 { 71 printf("%d\n", s.top()); 72 array.Update(s.top(), -1); 73 s.pop(); 74 } 75 } 76 else if (op == "PeekMedian") 77 { 78 if (s.empty()) 79 printf("Invalid\n"); 80 else 81 printf("%d\n", array.Find((s.size() + 1) / 2)); 82 } 83 else if (op == "Push") 84 { 85 int value; 86 scanf("%d", &value); 87 s.push(value); 88 array.Update(value, 1); 89 } 90 } 91 }