3210. Maximum Element

单点时限: 2.0 sec

内存限制: 256 MB

You have an empty sequence, and you will be given queries. Each query is one of these three types:

1 x -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.
输入格式
The first line of input contains an integer, . The next lines each contain an above mentioned query. (It is guaranteed that each query is valid.)
1<=N<=10^5
1<=x<=10^9
1<=type<=3

输出格式
For each type 3 query, print the maximum element in the stack on a new line.

样例
input
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
output
26
91

/*
思路一:用一个优先队列保存最大值,用visit[]保存是否出栈。
*/
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
struct node {
	int index;
	int data;
	friend bool operator < (node a,node b) {
		return a.data<b.data;
	}
};
int main() {
	stack<node>s;
	priority_queue<node>q;
	int n;
	cin>>n;
	int i =0;
	bool visit[n+1]= {false};
	while(n--) {
		int p;
		cin>>p;
		if(p==1) {
			int x;
			cin>>x;
			node g= {i,x};
			s.push(g);
			q.push(g);
			i++;
		} else if(p==2) {
			node g=s.top();
			s.pop();
			visit[g.index]=true;
		} else {
			while(visit[q.top().index]!=false) {
				q.pop();
			}
			cout<<q.top().data<<endl;
		}
	}
	return 0;
}
/*
思路二:双栈模拟。其中一个栈保存最大值。
*/
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
int main() {
	stack<int>s1,s2;
	int n;
	cin>>n;
	while(n--) {
		int q;
		cin>>q;
		if(q==1) {
			int x;
			cin>>x;
			s1.push(x);
			if(s2.empty()||x>=s2.top())
				s2.push(x);
		} else if(q==2) {
			int x=s1.top();
			s1.pop();
			if(x==s2.top())
				s2.pop();
		} else {
			cout<<s2.top()<<endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40394960/article/details/106032187
今日推荐