题目1522:包含min函数的栈

题目1522:包含min函数的栈

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:2248

解决:725

题目描述:

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(1<=n<=1000000), n代表将要输入的操作的步骤数。
接下来有n行,每行开始有一个字母Ci。
Ci=’s’时,接下有一个数字k,代表将k压入栈。
Ci=’o’时,弹出栈顶元素。

输出:

对应每个测试案例中的每个操作,
若栈不为空,输出相应的栈中最小元素。否则,输出NULL。

样例输入:
7
s 3
s 4
s 2
s 1
o
o
s 0
样例输出:
3
3
2
1
2
3
0
用set直接存和删除,找最小值。。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cmath>
#include<stack>
#include<map>
#include<set>
using namespace std;
int main()
{
    int n,num;
    string s1;
    while( cin >> n )
    {
        stack<int> s;
        set<int> s3;
        while( n -- )
        {
            cin >> s1;
            if( s1 == "s" )
            {
                cin >> num;
                s.push(num);
                s3.insert(num);
                cout << *s3.begin() << endl;
            }
            else
            {
                int num = s.top();
                s.pop();
                if( s3.size() != 0 ) 
s3.erase(num);
if( s3.size() != 0 )
cout << *s3.begin() << endl; else cout << "NULL" << endl; } } } return 0; }
彼时当年少,莫负好时光。
原文地址:https://www.cnblogs.com/l609929321/p/6591211.html