【C++编程基础】AOJ (C++ Programming II)—2-A-stack

2-A-stack

题目

stack
Stack is a container of elements that are inserted and deleted according to LIFO (Last In First Out).For n stack Si (i=0,1,…,n−1), perform a sequence of the following operations.
push(t, x): Insert an integer x to St.
top(t): Report the value which should be deleted next from St. If St is empty, do nothing.
pop(t): Delete an element from St. If St is empty, do nothing.
In the initial state, all stacks are empty.
输入
The input is given in the following format. nq query1 query2 : queryq Each query queryi is given by 0 t x or 1 t or 2 t where the first digits 0, 1 and 2 represent push, top and pop operations respectively. 1≤n≤1,000 1≤q≤200,000 −1,000,000,000≤x≤1,000,000,000 Sample Input 1
输出
For each top operation, print an integer in a line.

样例输入

3 9
0 0 1
0 0 2
0 0 3
0 2 4
0 2 5
1 0
1 2
2 0
1 0

样例输出

3
5
2

题解(代码流程)

#include<bits/stdc++.h>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int n, q;
    cin >> n >> q;
    vector<stack<int>> Si(n);//嵌套栈数组
    while (q--) {
        int p;
        cin >> p;
        if (p == 0) {
            int t, x;
            cin >> t >> x;
            Si[t].push(x);把x放入Si[t]中
        } else if (p == 1) {
            int t;
            cin >> t;
            if (!Si[t].empty())
                cout << Si[t].top() << endl;//返回Si[t]栈顶元素
        } else if (p == 2) {
            int t;
            cin >> t;
            if (!Si[t].empty()) Si[t].pop();//移除Si[t]栈顶元素
        }
    }

    return 0;
}

小结

学会定义嵌套栈数组,对栈中的元素进行修改
remember
c++ STack 栈堆实现了一个先进后出(FILO)的数据结构
  • empty()
  • pop()
  • push()
  • size()
  • top()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值