【11.21】3.栈 --- hdu1062、洛谷 P2947

正文

先进后出,可以当作手枪或者步枪弹夹

1. STL stack

  1. stack<dataType> st — 定义栈
  2. st.push(e) — push,入栈操作,可以看作是子弹被压入弹夹
  3. st.top() — 返回栈顶元素,看看这颗子弹长什么样
  4. st.pop() — 弹栈操作,可以看作是子弹被打出
  5. st.size() — 查看栈当前元素数量
  6. st.empty() — 检查是否为空
hdu 1062

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

洛谷 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;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值