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()