C++ #include<stack> 用法

版权声明:转载注明出处!!! https://blog.csdn.net/xhpaqh/article/details/83278463

C++ #include 用法

c++ stl栈stack的头文件为:

#include < stack >

stack< int > S;//声明一个对象

S.empty();//栈空返回true 否则false

int x=S.size();//返回栈中元素个数于x

S.pop();//移除栈顶元素

S.push(x);将x置于栈顶

x=S.top();返回栈顶元素
其中51nod中 1289 大鱼吃小鱼题目用stack函数直接调用栈直接调用会比较方便。
而这道题,规定一个方向压栈,然后与栈顶元素比较,如果大于栈顶元素则ans++,最后N-sum就是剩下的鱼。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int main(){
	stack<int> s;
	int n;
    scanf("%d",&n);
    int ans=0;
    for(int i=0;i<n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        if(y==1) s.push(x);//向右压栈 
        if(y==0)
        {
            while(!s.empty()&&s.top()<x)
            {
                s.pop();
                ans++;
            }
            if(!s.empty())ans++;
        }
    }
    printf("%d",n-ans);
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/xhpaqh/article/details/83278463