您的位置:首页 > 其它

PAT 1057. Stack (30)

2015-08-25 12:36 381 查看

1057. Stack (30)

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

采用树状数组以及scanf和printf


#include <cstdio>
#include <stack>
#include <string>
#include <cstring>

using namespace std;

#define MAXSIZE 100001
class BinaryIndexTree
{
private:
int numbers[MAXSIZE];
int size;
int lowbit(int x){ return x&(-x); }
public:
BinaryIndexTree(int size){ memset(numbers, 0, (size + 1)*sizeof(int)); this->size = size; }
void Update(int x, int num);
int GetSum(int x);
int Find(int value, int left, int right);
};

void BinaryIndexTree::Update(int x, int num)
{
while (x <= size)
{
numbers[x] += num;
x += lowbit(x);
}
}

int BinaryIndexTree::GetSum(int x)
{
int sum = 0;
while (x > 0)
{
sum += numbers[x];
x -= lowbit(x);
}
return sum;
}

int BinaryIndexTree::Find(int value, int left=0, int right = MAXSIZE-1)
{
if (left == right)
return left;
int mid = (left + right) / 2;
if (GetSum(mid) < value)
return Find(value, mid + 1, right);
else
return Find(value, left, mid);
}

int main()
{
int opNum;
scanf("%d", &opNum);

stack<int> s;
BinaryIndexTree array(100000);
for (int i = 0; i < opNum; i++)
{
char c[10];
scanf("%s", c);
string op(c);
if (op == "Pop")
{
if (s.empty())
printf("Invalid\n");
else
{
printf("%d\n", s.top());
array.Update(s.top(), -1);
s.pop();
}
}
else if (op == "PeekMedian")
{
if (s.empty())
printf("Invalid\n");
else
printf("%d\n", array.Find((s.size() + 1) / 2));
}
else if (op == "Push")
{
int value;
scanf("%d", &value);
s.push(value);
array.Update(value, 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: