正文
栈
先进后出,可以当作手枪或者步枪弹夹
1. STL stack
stack<dataType> st
— 定义栈st.push(e)
— push,入栈操作,可以看作是子弹被压入弹夹st.top()
— 返回栈顶元素,看看这颗子弹长什么样st.pop()
— 弹栈操作,可以看作是子弹被打出st.size()
— 查看栈当前元素数量st.empty()
— 检查是否为空
hdu 1062
题目分析
反转字符串,注意分割条件
思路分析
使用栈,挨个读取,当到达分割条件时,从栈顶输出
AC代码
#include <bits/stdc++.h>
using namespace std;
// #define ONLINE_JUDGE
const int N = 100010;
const int INF = 0x7fffffff;
inline void solve() {
stack<char> st;
char ch;
while (true) {
ch = getchar();
if (ch == '\n' || ch == ' ' || ch == EOF) {
while (!st.empty()) {
printf("%c", st.top());
st.pop();
}
if (ch == '\n' || ch == EOF) {
return;
}
printf(" ");
} else {
st.push(ch);
}
}
}
inline void problem() {
int t; scanf("%d", &t);
getchar();
while (t--) {
solve();
printf("\n");
}
}
int main()
{
// ios::sync_with_stdio(0);
// cin.tie(0), cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
problem();
return 0;
}
2. 手写栈
使用数组实现即可
struct mystack{
int top;
int data[N];
mystack():top(-1){}
} st;
// 入栈
st.data[++ st.top] = e;
// 出栈
-- st.top;
// 访问栈顶
data[top];
// 判空
if (top < 0)
3. 单调栈
栈内元素单调递增或单调递减,元素入栈的时候进行比较,符合单调性就入栈,不符合就弹栈,直到符合时将元素入栈
洛谷 P2947
直接看代码吧
#include <bits/stdc++.h>
using namespace std;
// #define ONLINE_JUDGE
const int N = 1e6 + 10;
int n;
int a[N];
int h[N];
inline void solve() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%d", &h[i]);
stack<int> st;
for (int i = n; i >= 1; --i) {
while (!st.empty() && h[st.top()] <= h[i]) st.pop();
if (st.empty()) a[i] = 0;
else a[i] = st.top();
st.push(i);
}
for (int i = 1; i <= n; ++i) printf("%d\n", a[i]);
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0);
// cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t = 1;
// scanf("%d", &t);
while (t--) {
solve();
}
return 0;
}