P1750 出栈序列(贪心)

手玩数据模拟即可。

注意一点,之前无脑认为0x3f3f3f3f是INF,实际只有1e9那么大,而int类型2e9多,所以mn初始值不能赋值成0x3f3f3f3f

也要注意一些细节:如栈为空时的处理; 还有min(n, p + re - 1)。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, c, a[N];
stack<int> st;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> n >> c;
	for (int i = 1; i <= n; i ++) cin >> a[i];
	int re = c, p = 1;//指针
	while (p != n + 1) {
		int mn = 2e9, r;//注意数据范围,mn赋值成0x3f3f3f3f不对(约是1e9) 
		for (int i = p; i <= min(n, p + re - 1); i ++)//min
			if (a[i] < mn) mn = a[i], r = i;
		while (!st.empty() && st.top() <= mn) {//注意判断空 
			cout << st.top() << " ";
			st.pop(); 
			re ++;
			if (p + re - 1 <= n && a[p + re - 1] < mn) 
				mn = a[p + re - 1], r = p + re - 1;
		}
		if (st.empty() || st.top() > mn) {
			for (int i = p; i < r; i ++) 
				st.push(a[i]);
			cout << mn << " ";
			re -= r - p;
			p = r + 1;
		}
	}
	while (!st.empty()) {
		cout << st.top() << " ";
		st.pop();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值