PTA 甲级 1057 Stack (30 point(s))

1057 Stack (30 point(s))

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

思路:

本题的话,如果是暴力做的话,每次每次相加的话,105肯定会时间超限,所以就要用到树状数组了,可以极大程度减少遍历的次数,首先写出树状数组的模板,lowbit之类的,然后二分找中间值,因为getnum得出的值,是在这个数之前总共有多少个数,所以就可以写出二分的代码了,最后再写主函数。

#include <iostream>
#include <stack>
#include <string>
using namespace std;
const int maxn = 1e+5 + 1;
int c[maxn] = {0};
stack<int> s;
int lowbit(int i) {
	return (i & (-i));
}
void updata(int x, int v) {
	for (int i = x; i < maxn; i += lowbit(i)) c[i] += v; 
}
int getnum(int x) {
	int sum = 0;
	for (int i = x; i >= 1; i -= lowbit(i)) sum += c[i];
	return sum;
}
void PeekMedian() {
	int left = 1, right = maxn, k = (s.size() + 1) >> 1;
	while (right > left) {
		int mid = (left + right) >> 1;
		if (getnum(mid) >= k) right = mid;
		else left = mid + 1;
	}
	printf("%d\n", right);
}
int main() {
	int n, m;
	string str;
	scanf("%d", &n);
	while (n--) {
		cin >> str;
		if (str == "Pop") {
			if (s.empty()) printf("Invalid\n");
			else {
				updata(s.top(), -1);
				printf("%d\n", s.top());
				s.pop();
			}
		} else if (str == "Push") {
			scanf("%d", &m);
			s.push(m);
			updata(m, 1);
		} else {
			if (s.empty()) printf("Invalid\n");
			else PeekMedian();
		}
	}
	return 0;
}
全部评论

相关推荐

04-28 10:14
门头沟学院 Java
点赞 评论 收藏
分享
飞屋一号:实话实说就行,先争取一下能不能线上,不行就直接放弃,付出与回报不成正比
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务