PAT Advanced Level 1057

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1057

解题感悟:主要解决超时问题。参考网络大神解题报告,使用到了树形数组,膜拜

代码如下:

#include<stdio.h>
#include<cstring>
#include<iostream>
#include<string>
using namespace std;

const int N=100005;
int c[N];

int lowbit(int i){
	return i&(-i);
}

void add(int pos,int value){
	while(pos<N){
		c[pos]+=value;
		pos+=lowbit(pos);
	}
}

int sum(int pos){
	int res=0;
	while(pos>0){
		res+=c[pos];
		pos-=lowbit(pos);
	}
	return res;
}

int find(int value){
	int l=0,r=N-1,median,res;
	while(l<r-1){
		if((l+r)%2==0)
			median=(l+r)/2;
		else
			median=(l+r-1)/2;
		res=sum(median);
		if(res<value)
			l=median;
		else
			r=median;

	}
	return l+1;
}

int main(){
	char ss[20];
	int stack[N],top=0,n,pos;
	memset(c,0,sizeof(c));
	scanf("%d",&n);
	while(n--){
		scanf("%s",ss);
		if(ss[1]=='u'){
			scanf("%d",&pos);
			stack[++top]=pos;
			add(pos,1);
		}else if(ss[1]=='o'){
			if(top==0){
				printf("Invalid\n");
				continue;
			}
			int out=stack[top];
			add(out,-1);
			printf("%d\n",stack[top--]);
		}else if(ss[1]=='e'){
			if(top==0){
				printf("Invalid\n");
				continue;
			}
			int res;
			if(top%2==0)
				res=find(top/2);
			else
				res=find((top+1)/2);
			printf("%d\n",res);

		}else{
			printf("Invalid\n");
		}
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值