标签:
set的使用和它的迭代器的使用
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 keywhere 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 PopSample Output:
Invalid Invalid 3 2 2 1 2 4 4 5 3 Invalid
#include<iostream>
#include<vector>
#include<string>
#include<string.h>
#include<stdio.h>
#include<set>
#include<stack>
#pragma warning(disable:4996)
using namespace std;
multiset<int> minS, maxS;
stack<int> st;
int mid;
void adjust() {
multiset<int>::iterator it;
if (minS.size() < maxS.size()) {
it = maxS.begin();
minS.insert(*it);
maxS.erase(it);
}
else if (minS.size() > maxS.size() + 1) {
it = minS.end();
it--;
maxS.insert(*it);
minS.erase(it);
}
if (minS.size() != 0) {
it = minS.end();
it--;
mid = *it;
}
}
int main(void) {
multiset<int>::iterator it;
freopen("Text.txt", "r", stdin);
int n;int m;
cin >> n;
char s[15];
for (; n--; ) {
scanf("%s", s);
if (strcmp(s, "Push") == 0) {
scanf("%d", &m);
if (st.size() == 0)
{
minS.insert(m);
mid = m;
}
else if (m <= mid)
minS.insert(m);
else
maxS.insert(m);
st.push(m);
adjust();
}
else if (strcmp(s, "PeekMedian") == 0) {
if (st.size() == 0) {
printf("Invalid\n");
}
else {
//cout << mid << endl;
printf("%d\n", mid);
}
}
else if(strcmp(s, "Pop") == 0){
if (st.size() == 0) {
printf("Invalid\n");
}
else {
int m;
m = st.top();
// cout << m << endl;
printf("%d\n", m);
st.pop();
if (m > mid) {
it = maxS.find(m);
maxS.erase(it);
}
else {
it = minS.find(m);
minS.erase(it);
}
adjust();
}
}
else {
printf("Invalid\n");
continue;
}
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/zzandliz/p/5023186.html