1057. Stack

http://pat.zju.edu.cn/contests/pat-a-practise/1057


本题直接使用STL的stack和set即可。但测试中存在2个测试点错误,于是改成自己模拟栈操作,任然存在超时。可得22分。


#include <stdio.h>
#include <string.h>
#include <algorithm>

#define SIZE 100000+5

using namespace std;

int stack[SIZE], a[SIZE];
int n, key, top, len;
char order[20];

void Init()
{
	memset(stack, 0, sizeof(stack));
	memset(a, 0, sizeof(a));
	top = -1;
	len = 0;
}

int search(int x)
{
	int low = 0, high = len-1;
	while(low<=high)
	{
		int mid = (low+high)/2;
		if(a[mid] == x)
		{
			return mid;
		}
		else if(a[mid] < x)
		{
			low = mid + 1;
		}
		else
		{
			high = mid - 1;
		}
	}
	return low;
}

void erase(int x)
{
	int pos = search(x);
	pos++;
	while(pos < len)
	{
		a[pos-1] = a[pos];
		pos++;
	}
	len--;
	// 仍然有序
}

void Insert(int x)
{
	int pos = search(x);
	int i;
	for(i=len; i> pos; i--)
	{
		a[i] = a[i-1];
	}
	a[pos] = x;
	len++;
}

void op_push()
{
	scanf("%d", &key);
	stack[++top] = key;
	Insert(key);
}

void op_pop()
{
	if(top == -1)
	{
		printf("Invalid\n");
		return ;
	}
	key = stack[top--];
	printf("%d\n", key);
	erase(key);
	return ;
}

void op_Median()
{
	if(top == -1)
	{
		printf("Invalid\n");
		return ;
	}

	//printf("Median\n");
	printf("%d\n", a[(len-1)/2]);
	return ;
}

void Operation()
{
	while(n-->0)
	{
		getchar();
		scanf("%s", order);
		//printf("order:%s\n", order);

		if(strcmp(order, "Push") == 0)
		{
			op_push();
		}
		else if(strcmp(order, "Pop") == 0)
		{
			op_pop();
		}
		else if(strcmp(order, "PeekMedian") == 0)
		{
			op_Median();
		}
		else
		{
			printf("Error\n");
		}
	}// read op and deal with it

}

int main()
{
#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
	//freopen("E:\\out.txt", "w", stdout);
#endif

	Init();

	scanf("%d", &n);
	Operation();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值