題目:
堆棧是一種經典的後進先出的線性結構,相關的操作主要有“入棧”(在堆棧頂插入一個元素)和“出棧”(將棧頂元素返回並從堆棧中刪除)。本題要求你實現另一個附加的操作:“取中值”——即返回所有堆棧中元素鍵值的中值。給定 N 個元素,如果 N 是偶數,則中值定義爲第 N/2 小元;若是奇數,則爲第 (N+1)/2 小元。
輸入格式:
輸入的第一行是正整數 N(≤105)。隨後 N 行,每行給出一句指令,爲以下 3 種之一:
Push key
Pop
PeekMedian
其中 key
是不超過 105 的正整數;Push
表示“入棧”;Pop
表示“出棧”;PeekMedian
表示“取中值”。
輸出格式:
對每個 Push
操作,將 key
插入堆棧,無需輸出;對每個 Pop
或 PeekMedian
操作,在一行中輸出相應的返回值。若操作非法,則對應輸出 Invalid
。
輸入樣例:
17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
輸出樣例:12
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
思路:
用數組模擬一下棧,但要注意的是在進行PeekMedian操作時,
需要返回的是堆棧中元素鍵值的中值
第一次自己理解成了返回棧中中間位置的數值!!
這時候就需要建立一個vector容器,在進行pop和push操作時
需要注意刪除和插入的位置;
代碼:
#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<string>
#include<algorithm>
#define ll long long
#define N 1008611
#define inf 0x3f3f3f3f
using namespace std;
vector<int> vec;
vector<int>::iterator it;//定義迭代器變量
int a[100861];
int main()
{
int n;
scanf("%d",&n);
int top=0;
for(int i=0;i<n;i++)
{
char s[100];
scanf("%s",s);
if(strcmp(s,"Pop")==0)
{
if(top==0)
printf("Invalid\n");
else
{
it=std::lower_bound(vec.begin(),vec.end(),a[top-1]);
//返回棧頂元素在vector容器中的位置
vec.erase(it);//刪除元素
top--;
printf("%d\n",a[top]);
}
}
if(strcmp(s,"PeekMedian")==0)
{
if(top==0)
{
printf("Invalid\n");
continue;
}
if(top%2)
printf("%d\n",vec[(top+1)/2-1]);
else
printf("%d\n",vec[top/2-1]);
}
if(strcmp(s,"Push")==0)
{
int c;
scanf("%d",&c);
a[top++]=c;
it=std::lower_bound(vec.begin(),vec.end(),c);
//利用二分法求得插入元素所插入的位置
vec.insert(it,c);//插入
}
}
return 0;
}