PAT-1057 Stack (树状数组 + 二分查找)
1057. Stack
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:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
Sample Output:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
题目大意:要求实现一个栈,除了基础的push和pop操作外,还要拥有查找中间数的操作
(PeekMedian),即n个栈中元素在排序后,该元素的大小排行为 (n+1)/2。因为可能存在大量的查找中间数的操作,所以必须找到快速的解决方法。
主要思想:解此题的过程可谓是一波三折。开始的想法很天真,在每次需要PeekMedian的时候,将栈中元素全部拷贝到一个辅助数组,然后对该数组进行排序,很容易找到中间值,时间复杂度为
O((n^2) lgn),很显然最后超时了。
由于题目说明数据范围为 1~100000,想到了用一个count[]数组来储存每一个数在栈中的个数,然后每一次通过遍历数组累积,当 S[i] = count[1] + count[2] + ... + count[i] >= (n+1)/2 的时候则找到中间值i,时间复杂度为 O(n^2)。
这样显然还会超时,在这个想法的基础上利用树状数组,这种数据结构可以很快的得出前 i 项和,从而可以利用二分查找来找到中间数。于是,push和pop操作时间复杂度为 O(lgn),PeekMedian的复杂度为 O(n (lgn)^2),问题解决。
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string.h>
#define MAXN 100005
using namespace std;
int stack[MAXN]; //array of stack
int c[MAXN]; //BIT
int n = 0;
/*
functions of Binary Index Tree (BIT)
*/
int lowbit(int x) {
return x & (-x);
}
int get_sum(int x) {
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i))
sum += c[i];
return sum;
}
void update(int x, int t) {
for (int i = x; i <= MAXN; i += lowbit(i))
c[i] += t;
} /*
operations of stack
*/
bool isEmpty() {
return n == 0;
}
void push(int key) {
stack[n++] = key;
update(key, 1);
}
int pop() {
int k = stack[--n];
update(k, -1);
return k;
}
int peek_median() {
int lo = 1, hi = MAXN;
int median = (n + 1) / 2; //use the binary search
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (median > get_sum(mid))
lo = mid + 1;
else // median <= get_sum(mid)
hi = mid - 1;
}
return lo;
} int main(void) {
int m;
char comment[11]; scanf("%d", &m);
getchar();
for (int i = 0; i < m; i++) {
gets(comment);
if (comment[1] == 'u') { //push
int key = atoi(comment+5);
push(key);
}
else if (comment[1] == 'o') { //pop
if(isEmpty()) {
printf("Invalid\n");
continue;
}
int t = pop();
printf("%d\n", t);
}
else { //peek median
if (isEmpty()) {
printf("Invalid\n");
continue;
}
int m = peek_median();
printf("%d\n", m);
}
} return 0;
}
PAT-1057 Stack (树状数组 + 二分查找)的更多相关文章
- 1057 Stack 树状数组
Stack is one of the most fundamental data structures, which is based on the principle of Last In Fir ...
- POJ 2182 Lost Cows (树状数组 && 二分查找)
题意:给出数n, 代表有多少头牛, 这些牛的编号为1~n, 再给出含有n-1个数的序列, 每个序列的数 ai 代表前面还有多少头比 ai 编号要小的牛, 叫你根据上述信息还原出原始的牛的编号序列 分析 ...
- toj 4353 Estimation(树状数组+二分查找)
Estimation 时间限制(普通/Java):5000MS/15000MS 运行内存限制:65536KByte总提交: 6 测试通过: 1 描述 “There are ...
- 树状数组+二分||线段树 HDOJ 5493 Queue
题目传送门 题意:已知每个人的独一无二的身高以及排在他前面或者后面比他高的人数,问身高字典序最小的排法 分析:首先对身高从矮到高排序,那么可以知道每个人有多少人的身高比他高,那么取较小值(k[i], ...
- poj2182Lost Cows——树状数组快速查找
题目:http://poj.org/problem?id=2182 从后往前确定,自己位置之前没有被确定的且比自己编号小的个数+1即为自己的编号: 利用树状数组快速查找,可另外开一个b数组,角标为编号 ...
- P2161 [SHOI2009]会场预约[线段树/树状数组+二分/STL]
题目描述 PP大厦有一间空的礼堂,可以为企业或者单位提供会议场地.这些会议中的大多数都需要连续几天的时间(个别的可能只需要一天),不过场地只有一个,所以不同的会议的时间申请不能够冲突.也就是说,前一个 ...
- 牛客多校第3场 J 思维+树状数组+二分
牛客多校第3场 J 思维+树状数组+二分 传送门:https://ac.nowcoder.com/acm/contest/883/J 题意: 给你q个询问,和一个队列容量f 询问有两种操作: 0.访问 ...
- POJ 2828 Buy Tickets (线段树 or 树状数组+二分)
题目链接:http://poj.org/problem?id=2828 题意就是给你n个人,然后每个人按顺序插队,问你最终的顺序是怎么样的. 反过来做就很容易了,从最后一个人开始推,最后一个人位置很容 ...
- TZOJ 4602 高桥和低桥(二分或树状数组+二分)
描述 有个脑筋急转弯是这样的:有距离很近的一高一低两座桥,两次洪水之后高桥被淹了两次,低桥却只被淹了一次,为什么?答案是:因为低桥太低了,第一次洪水退去之后水位依然在低桥之上,所以不算“淹了两次”.举 ...
随机推荐
- Linux / mac OS Shell常用命令
一.文件.目录操作命令 1.ls命令 功能:显示文件和目录的信息 ls 以默认方式显示当前目录文件列表 ls -a 显示所有文件包括隐藏文件 ls -l 显示文件属性,包括大小,日期,符号连接,是否可 ...
- nodejs中httpserver的安装和使用
首先来看一下官方的介绍: 大概意思是说:命令行HTTP服务器工具,用于提供本地文件,类似于python -mSimpleHTTPServe. 直白点的意思就是通过命令行启动的一个http服务器工具,它 ...
- Java的循环语句
一.while 循环 while(循环条件){ 循环操作语句 } * 循环3要素: 变量的初值.变量的判断.变量的更新 * 缺少循环变量的更新,循环将一直进行下去 public class Whlie ...
- 数学--数论--HDU1825(积性函数性质+和函数公式+快速模幂+非互质求逆元)
As we all know, the next Olympic Games will be held in Beijing in 2008. So the year 2008 seems a lit ...
- HDOJ 4699 Editor 对顶栈模拟
Editor Time Limit: 3000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Subm ...
- The 2019 Asia Nanchang First Round Online Programming Contest B Fire-Fighting Hero(阅读理解)
This is an era of team success, but also an era of heroes. Throughout the ages, there have been nume ...
- 解决虚拟机中linux系统无法使用本机无线wifi联网的问题
VMware Workstation 在嵌入式开发中经常会遇到,但是显示大多数人使用开发环境是Win10 + 无线网卡,针对这种情况,需要配置虚拟机的上网环境使用的是NAT模式,将配置过程进行描述: ...
- P2766 最长不下降子序列问题 网络流重温
P2766 最长不下降子序列问题 这个题目还是比较简单的,第一问就是LIS 第二问和第三问都是网络流. 第二问要怎么用网络流写呢,首先,每一个只能用一次,所以要拆点. 其次,我们求的是长度为s的不下降 ...
- php使用curl post josn数据
今天在工作中使用到要使用("Content-Type", "application/json;charset=UTF-8")格式传送和接受数据,再次做个记录 p ...
- dbcp数据源连接池
一.数据源连接池 我们之前利用jdbc连接数据库,每次都要创建连接对象,销毁连接对象,如果并发访问量比较大,这样肯定比较辣 浪费数据库的效率,我们可以像之前mybatis中缓存查询到的数据一样,可以把 ...