PAT 甲级:1057. Stack

这道题的难点在于在线查询(在查询过程中元素回会发生改变)

下面是模仿内存分块存储的思想,分块记录数据。

#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<string.h>
#include<stack>
using namespace std;
//用类似内存读取的分块思想,来加快存储数据的读取
const int maxn=100010;
const int blocks=316;//每块又316个数,有317块
int cnt[maxn];//记录每个数字有多少个,应该初始化为0
int block[blocks];//记录每个块里面有多少数字
stack<int> st;

int main(){
	int n;
	scanf("%d",&n);
	getchar();
	memset(cnt,0,sizeof(cnt));
	memset(block,0,sizeof(block));
	for(int i=0;i<n;i++){
		char command[15];
		//检测有无空格
		scanf("%s",command);
		//插入,删除同时更新堆栈和区块数组,查找通过区块数组
		if(strcmp(command,"Pop")==0){//弹出有两种清空,栈为空,栈非空
			if(st.size()==0) printf("Invalid\n");
			else{//---------------------------------------------删除-----------------------
				int da=st.top();
				st.pop();
				printf("%d\n",da);//从堆栈中删除数据
				//同时更新区块的记录
				cnt[da]--;
				block[da/blocks]--;
			}
		}
		else if(strcmp(command,"PeekMedian")==0){
			if(st.size()==0) printf("Invalid\n");
			else{//----------------------------------------------查找------------------------
				int mid=st.size();
				if(mid%2==0) mid=mid/2;
				else mid =(mid+1)/2;
				int b=0,total=0;
				while(total+block[b]<mid){
					total+=block[b++];
				}
				//表示要查找的mid存在与第b块中
				int i=b*blocks;
				while(total+cnt[i]<mid){
					total+=cnt[i++];
				}
				printf("%d\n",i);
			}
		}
		else{//--------------------------------------------------插入----------------------------
			int num;
			scanf("%d",&num);
			st.push(num);
			cnt[num]++;
			block[num/blocks]++;
		}
	}
	return 0;
}

之前我一直中间三个点一直通不过,因为中间三个点都是大数据。而我的读取方法都是,先gets整行内容,再用scanf提取出命令何和整数。

char in[15];
    gets(in);
    char command[15];
    //检测有无空格
    int j;
    for(j=0;j<strlen(in);j++){
      if(command[j]==' ') break;
    }
    //其中没有空格
    int num;
    if(j!=strlen(command)){
      sscanf(in,"%s%d",command,&num);
    }
    else{
      strcpy(command,in);
    }


当读取整数很大时,需要把in数组设置成很大,才能把大整数一起读入,而我把in数组设置太小了。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值