数据结构OJ作业——栈

本文提供两道POJ题目解析:一是判断一个出栈序列是否合法,二是利用单调栈求解特定问题。通过示例代码详细介绍了如何使用C++实现这两种算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POJ 1363:http://poj.org/problem?id=1363
判断一个出栈序列是否合法

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 1005;

int main(int argc, char const *argv[])
{
    int n,cntout,cntin,top,cnt; 
    int stack[MAX]; 
    int in[MAX],out[MAX]; 
    while (scanf("%d",&n), n) {
        while (scanf("%d",&out[0]), out[0]) {
            int flag = 1; 
            memset(stack,0,sizeof(stack));
            top = cntout = cntin = cnt = 0;
            in[0] = 1;
            for (int i = 1; i < n; i ++) {
                scanf("%d",&out[i]);
                in[i] = i + 1;
            }
            stack[top ++] = in[cntin ++];
            while (top > 0) { 
                while (out[cntout] != stack[top - 1] && cntin < n) {
                    stack[top ++] = in[cntin ++];
                }
                if (cntin == n && stack[top - 1] != out[cntout]) {
                    flag = 0;
                    break;
                }
                top --;
                cntout ++;
                if (top == 0 && cntin < n) {
                    stack[top ++] = in[cntin ++];
                }
            }
            if (flag) {
                printf("Yes\n");
            } else {
                printf("No\n");
            }
        }
        printf("\n");
    }

    return 0;
}

POJ 3250:http://poj.org/problem?id=3250
单调栈

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;

int main()
{
    int n;
    while (~scanf("%d",&n)) {
        long long ans = 0;
        stack<int> s;
        int h;
        for (int i = 1; i <= n; i ++) {
            scanf("%d",&h);
            while (!s.empty() && s.top() <= h) {
                s.pop();
            }
            ans += s.size();
            s.push(h); 
        }
        printf("%lld\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值