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; }
相关文章推荐
- ZJU-PAT 1057. Stack (30)---17有3组超时 浙大2013年上机复试第三题
- ZJU-PAT 1079. Total Sales of Supply Chain (25) 浙大2014年上机复试第三题
- ZJU-PAT 1054. The Dominant Color (20) 浙大2013年上机复试第一题
- ZJU-PAT 1055. The World's Richest (25) 浙大2013年上机复试第二题
- ZJU-PAT 1080. Graduate Admission (30) 浙大2014年上机复试第四题
- pat 1057. Stack (30) 浙江大学复试上机最后一题
- ZJU-PAT 1078. Hashing (25) 浙大2014年上机复试第二题
- ZJU-PAT 1077. Kuchiguse (20) 浙大2014年上机复试第一题
- pat 1080. Graduate Admission (30) 浙大复试上机第四题
- 浙大2013复试:PAT 1057. Stack (30)
- 浙大2012上机 PAT1034. Head of a Gang (30)
- ZJU-PAT 1056. Mice and Rice (25) 浙大2013年上机复试第四题
- 浙大PAT考试1077~1080(2014上机复试题目)
- ZJU 09 复试上机 第三题
- 浙大PAT考试1077~1080(2014上机复试题目)
- PAT 1057. Stack (30)
- 北航研究生复试2014上机第三题:冒号对齐
- 2007浙大复试上机考试题目4--EXCEL排序
- 浙大2012上机 PAT 1033. To Fill or Not to Fill (25)
- 2009浙大上机复试解题报告