堆栈

我们所说的堆栈其实就是栈这种数据结构。只能在栈顶来进行添加和删除。

第一步:初始化
|_|
|_|
|_|
|_|
|_|
|_| top=0;

第二步:加入一个元素8
|_|
|_|
|_|
|_|
|8| top=1;
|_|

第三步:删除一个元素
|_|
|_|
|_|
|_|
|8|
|_| top=0;

 典型的堆栈的题目是:poj 3250 http://poj.org/problem?id=3250

代码如下:

(不用stl的代码,141ms)

View Code
include "iostream"
#include "string"
#include "algorithm"
using namespace std;
#define maxn 80005
int cow[maxn];
int main()
{
    int n, nn;
    long  long ans=0;
    scanf("%d", &n);
    int h=0, t=0;
    while(n--)
    {
        scanf("%d", &nn);
        while(h>t && cow[h]<=nn) h--;
        ans += h;
        cow[++h]=nn;
    }
    printf("%lld\n", ans);
}

(用了stl的代码,1016ms)

View Code
#include "iostream"
#include "string"
#include "algorithm"
#include "stack"
using namespace std;
int main()
{
    int n, nn;
    long long ans=0;
    cin>>n;
    stack<int> s;
    while(n--)
    {
        cin>>nn;
        while(!s.empty() && s.top()<=nn) s.pop();
        ans += s.size();
        s.push(nn);
    }
    cout<<ans<<endl;
}

 

转载于:https://www.cnblogs.com/o8le/archive/2012/08/14/2638333.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值