您的位置:首页 > 其它

ZJU-PAT 1057. Stack (30) 浙大2013年上机复试第三题

2013-04-18 15:15 603 查看
#pragma warning (disable:4786)
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;

int n,d;;
int A[10005],B[10005];

int select(int num)
{
for(int i=1;i<=d;i++) B[i]=A[i];
sort(B+1,B+d+1);
return B[num];
}

void process()
{
char operate[1000];
scanf("%s",operate);
string s=operate;

if(s=="Pop")
{
if(d==0)
printf("Invalid\n");
else
{
printf("%d\n",A[d]);
d--;
}
}
else if(s=="PeekMedian")
{
if(d==0)
printf("Invalid\n");
else
{
int num;
if(d%2==0) num=d/2;
else
num=(d+1)/2;
printf("%d\n",select(num));
}
}
else if(s=="Push")
{
int b;
scanf("%d",&b);
A[++d]=b;
}
}

int main()
{
//freopen("1.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
d=0;
for(int i=0;i<n;i++)
process();
}
return 0;
}




利用树状数组+二分查找进行定位

#pragma warning (disable:4786)
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;

const int N=100005;

int n,d;
int A
,C
;

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

void update(int x,int num)
{
while(x<=N)
{
C[x]+=num;
x+=lowbit(x);
}
}

int getsum(int x)
{
int sum=0;
while(x>0)
{
sum+=C[x];
x-=lowbit(x);
}
return sum;
}

int select(int num)
{
int L=0,R=N-1,M,ans;

while(L<R-1)
{
M=(L+R)/2;
ans=getsum(M);

if(ans<num) L=M;
else
R=M;
}
return R;
}

void process()
{
char operate[1000];
scanf("%s",operate);
string s=operate;

if(s=="Pop")
{
if(d==0)
printf("Invalid\n");
else
{
printf("%d\n",A[d]);
update(A[d],-1);
d--;
}
}
else if(s=="PeekMedian")
{
if(d==0)
printf("Invalid\n");
else
{
int num;
if(d%2==0) num=d/2;
else
num=(d+1)/2;
printf("%d\n",select(num));
}
}
else if(s=="Push")
{
int b;
scanf("%d",&b);
update(b,1);
A[++d]=b;
}
}

int main()
{
while(scanf("%d",&n)!=EOF)
{
d=0;
for(int i=0; i<10005; i++) C[i]=0;
for(int i=0; i<n; i++)
process();
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: