http://pat.zju.edu.cn/contests/pat-a-practise/1057
本题直接使用STL的stack和set即可。但测试中存在2个测试点错误,于是改成自己模拟栈操作,任然存在超时。可得22分。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define SIZE 100000+5
using namespace std;
int stack[SIZE], a[SIZE];
int n, key, top, len;
char order[20];
void Init()
{
memset(stack, 0, sizeof(stack));
memset(a, 0, sizeof(a));
top = -1;
len = 0;
}
int search(int x)
{
int low = 0, high = len-1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid] == x)
{
return mid;
}
else if(a[mid] < x)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return low;
}
void erase(int x)
{
int pos = search(x);
pos++;
while(pos < len)
{
a[pos-1] = a[pos];
pos++;
}
len--;
// 仍然有序
}
void Insert(int x)
{
int pos = search(x);
int i;
for(i=len; i> pos; i--)
{
a[i] = a[i-1];
}
a[pos] = x;
len++;
}
void op_push()
{
scanf("%d", &key);
stack[++top] = key;
Insert(key);
}
void op_pop()
{
if(top == -1)
{
printf("Invalid\n");
return ;
}
key = stack[top--];
printf("%d\n", key);
erase(key);
return ;
}
void op_Median()
{
if(top == -1)
{
printf("Invalid\n");
return ;
}
//printf("Median\n");
printf("%d\n", a[(len-1)/2]);
return ;
}
void Operation()
{
while(n-->0)
{
getchar();
scanf("%s", order);
//printf("order:%s\n", order);
if(strcmp(order, "Push") == 0)
{
op_push();
}
else if(strcmp(order, "Pop") == 0)
{
op_pop();
}
else if(strcmp(order, "PeekMedian") == 0)
{
op_Median();
}
else
{
printf("Error\n");
}
}// read op and deal with it
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
//freopen("E:\\out.txt", "w", stdout);
#endif
Init();
scanf("%d", &n);
Operation();
return 0;
}