手玩数据模拟即可。
注意一点,之前无脑认为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;
}