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.

输入

Each input file contains one test case. For each case, the first line contains a positive integer N ( ≤ 1 0 5 ) (≤10^5) (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 1 0 5 10^5 105.

输出

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.

思路

先分析复杂度,N为 1 0 5 10^5 105因此简单分析最后只能O(n)或者O(nlogn)。但每次找中间的数字至少为O(n),普通方法会超时。
这里采用的是线段树,插入删除复杂度以及查询都是logn这样就够了。

代码

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<stack>
using namespace std;
#define MAXN1 1000000
#define MAXN 100000
int ans[4 * MAXN1 + 1000] = { 0 };
stack<int> s;
void update1(int L, int R, int idx, int res, int q)
{
	if (L == R)
	{
		ans[idx] += q;
		return;
	}
	int mid = (L + R) / 2;
	if (res <= mid)
	{
		update1(L, mid, idx * 2, res, q);
	}
	else
	{
		update1(mid+1, R, idx * 2 + 1 , res, q);
	}
	ans[idx] = ans[idx * 2] + ans[idx * 2 + 1];
}
int query(int L, int R, int idx, int pos)
{
	if (L == R)
	{
		return L;
	}
	int mid = (L + R) / 2;
	if (pos <= ans[idx * 2])
	{
		return query(L, mid, idx * 2, pos);
	}
	else
	{
		return query(mid+1, R, idx * 2 + 1, pos-ans[idx*2]);
	}
}
int main()
{
	int N;
	cin >> N;
	while (N--)
	{
		string str;
		cin >> str;
		if (str == "Pop")
		{
			if (s.empty())
			{
				printf("Invalid\n");
			}
			else
			{
				int t = s.top();
                cout<<t<<endl;
				s.pop();
				update1(1, 4 * MAXN, 1, t, -1);
			}
		}
		else if (str == "Push")
		{
			int t;
			cin >> t;
			s.push(t);
			update1(1, 4 * MAXN, 1, t, 1);
		}
		else
		{
			if (s.empty())
			{
				printf("Invalid\n");
			}
			else
			{
				int mid = s.size() / 2;
				if (s.size() % 2 != 0)
				{
					mid++;
				}
				cout << query(1, 4 * MAXN, 1, mid) << endl;
			}
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值