1057 Stack(30 分) (cj)

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

思路 做着的时候发现很简单的题感觉应该是 15 分的分值 但是一看 30 分 很懵,果然提交后 超时,上网搜了一下 原来需要树状数组和半分查找的技巧。真的是简单题不简单。

code

#pragma warning(disable:4996)
#include <iostream>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
#define maxn 100005
int lowbit(int x);
void add(int pos,int val);
int binaryfind(int x);
int getsum(int p);
int tree[100005];
class mystack {
public:
	int arr[maxn];
	int top = 0;
	int size = 0;
	void push(int key) {
		arr[(++top) % maxn] = key;
		++size;
		add(key,1);
	}
	int pop() {
		if (size == 0) return -1;
		--size;
		add(arr[top], -1);
		return arr[top--];
	}
	int peekmedian() {
		if (size == 0) return -1;
		if (size % 2 == 0) {
			return binaryfind(size/2);
		}
		else {
			return binaryfind((size + 1) / 2);
		}
	}
};
int main(){
	int n;
	mystack a;
	cin >> n;
	while (n--) {
		string command;
		cin >> command;
		if (command == "Pop") {
			int val = a.pop();
			if (val == -1) cout << "Invalid" << endl;
			else cout << val << endl;
		}
		else if (command == "PeekMedian") {
			int val = a.peekmedian();
			if (val == -1) cout << "Invalid" << endl;
			else cout << val << endl;
		}
		else {
			int val;
			cin >> val;
			a.push(val);
		}
	}
	system("pause");
	return 0;
}
int binaryfind(int x) {
	int  l = 0, r = maxn;
	while (l + 1 < r) {
		int mid = (l + r)>>1;
		if (getsum(mid) >= x) r = mid;
		else l = mid;
	}
	return r;
}
int lowbit(int x) {
	return x & (-x);
}
void add(int pos,int val) {
	while (pos < maxn) {
		tree[pos] += val;
		pos += lowbit(pos);
	}
}
int getsum(int pos) {
	int sum = 0;
	while (pos > 0) {
		sum += tree[pos];
		pos -= lowbit(pos);
	}
	return sum;
}

猜你喜欢

转载自blog.csdn.net/Cute_jinx/article/details/82080930