题目1522:包含min函数的栈

http://ac.jobdu.com/problem.php?pid=1522

我想到了用multiset的方法

题目1522:包含min函数的栈
#include<iostream>

#include<set>

#include<stack>

#include<stdio.h>

#include<queue>

#include<algorithm>



using namespace std;



struct data{

    int v;

    friend bool operator <(data a,data b){

        return a.v<b.v;

    }

    data(int a){

        v=a;

    }



};



int main()

{

    int n;

    while(scanf("%d",&n)!=EOF){

        int i;

        multiset <data>set1;

        stack<int>sta;



        char s[9];

        int temp;

        for(i=1;i<=n;i++){

            scanf("%s",s);

            if(s[0]=='s'){

                scanf("%d",&temp);

                sta.push(temp);

                set1.insert(temp);

            }

            else{

                if(!set1.empty()){

                    multiset <data>::iterator po;

                    for(po=set1.begin();po!=set1.end();po++){

                        if(po->v==sta.top())break;

                    }



                    set1.erase(po);

                    sta.pop();

                }

            }



            if(set1.begin()!=set1.end())

                printf("%d\n",set1.begin()->v);//写成*set1.begin()编译可以过 但会RE

            else

                printf("NULL\n");

        }

    }



    return 0;

}
View Code

 但是对SET里面的数据处理时不能直接删除数字,而是要删除数字所在的位置

还有一种比较简单的方法,就是不管如何,把较小的数字入队列

题目1522:包含min函数的栈
#include<stdio.h>



int sta[1009999];



int min(int a,int b){

    if(a>b)return b;

    else return a;

}

int main()

{

    int n;

    sta[0]=999999999;

    while(scanf("%d",&n)!=EOF){

        int i,add=0;

        char s[9];

        int temp;

        for(i=1;i<=n;i++){

            scanf("%s",s);

            if(s[0]=='s'){

                add++;

                scanf("%d",&temp);

                sta[add]=min(sta[add-1],temp);

                printf("%d\n",sta[add]);

                

            }else{

                add--;

                if(sta[add]==999999999)

                    printf("NULL\n");

                else

                    printf("%d\n",sta[add]);

            }

        }

    }



    return 0;

}
View Code

 

你可能感兴趣的:(函数)