pat1057. Stack (30)
发布日期:2025-05-01 23:09:28 浏览次数:2 分类:技术文章

本文共 2557 字,大约阅读时间需要 8 分钟。

1057. Stack (30)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian -- return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<= 105). Then N lines follow, each contains a command in one of the following 3 formats:

Push 
key
Pop
PeekMedian

where key is a positive integer no more than 105.

Output Specification:

For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print "Invalid" instead.

Sample Input:
17PopPeekMedianPush 3PeekMedianPush 2PeekMedianPush 1PeekMedianPopPopPush 5Push 4PeekMedianPopPopPopPop
Sample Output:
InvalidInvalid322124453Invalid

 

注意点:

1.树状数组的常见操作

学习:

 

1 int lowbit(int val){ 2     return val&(-val); 3 } 4 int sum(int val){ 5     int res=0; 6     while(val>0){ 7         res+=line[val]; 8         val-=lowbit(val); 9     }10     return res;11 }12 void add(int val,int x){13     while(val

这里要注意二分查找的书写。对于区间[a,b),不断二分,最后返回l。

 

2.string的操作一般要比char的操作时间长。这里用的string会超时。

 

1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 using namespace std; 9 #define maxnum 10000510 int line[maxnum];11 int lowbit(int val){12 return val&(-val);13 }14 int sum(int val){15 int res=0;16 while(val>0){17 res+=line[val];18 val-=lowbit(val);19 }20 return res;21 }22 void add(int val,int x){23 while(val
s;48 scanf("%d",&n);49 while(n--){50 scanf("%s",op);//cin>>op;51 if(op[1]=='u'){52 scanf("%d",&num);53 s.push(num);54 add(num,1);55 }56 else{57 if(op[1]=='o'){58 if(s.empty()){59 printf("Invalid\n");60 }61 else{62 num=s.top();63 s.pop();64 printf("%d\n",num);65 add(num,-1);66 }67 }68 else{69 if(s.size()==0){70 printf("Invalid\n");71 continue;72 }73 if(s.size()%2==0){74 num=find(s.size()/2);75 }76 else{77 num=find((s.size()+1)/2);78 }79 printf("%d\n",num);80 }81 }82 }83 return 0;84 }

 

转载于:https://www.cnblogs.com/Deribs4/p/4790435.html

上一篇:PAT1093 Count PAT's (25)(逻辑题)
下一篇:pat1011. World Cup Betting (20)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月06日 00时19分32秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章