题意
要求输出窗口大小为1~n,所有窗口中的最小值打最大值。
思路
先说总的思路。
对于每一位置的数,我们可以得到以他为最小值能够得到的最长区间的长度。
比如2 7 6 5 6 7 3,5这个位置的最长区间的长度就是5。
那么我们就可以得到每个区间长度对应的最大值。
因为如果有一个长度为6的窗口,里面的最小值的最大值是10,那么长度为5的窗口的最小值的最大值肯定不会小于10.
所以我们在计算完各个长度的答案后还要从后往前更新一遍值。
如何得到每个位置对应的最长区间?用单调栈分别从左往右和从右往左扫一遍即可。
注意一下初始化,r[i]要初始为n、l[i]要初始为-1(如果数组从0开始保存).因为用单调栈维护的时候得到的是最远的小于它的数,而且两边都是。所以长度是r[i]-l[i]-1。
代码
#include <stack>
#include <cstdio>
#include <list>
#include <cassert>
#include <set>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
//#pragma comment(linker, "/STACK:102400000,102400000")
#include <string>
#include <map>
#include <cmath>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define X first
#define Y second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define FOR(i, a, b) for (int i=(a); (i) < (b); (i)++)
#define FOOR(i, a, b) for (int i = (a); (i)<=(b); (i)++)
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int MAXN = 2e5+10;
const int MOD = 8e4+7;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
const int seed = 131;
int cases = 0;
typedef pair<int, int> pii;
int ans[MAXN], l[MAXN], r[MAXN], a[MAXN];
stack<int> stk;
int main()
{
//ROP;
int n;
scanf("%d", &n);
fill(r, r+n+1, n);
MS(l, -1);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int i = 0; i < n; i++)
{
while (!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
if (!stk.empty()) l[i] = stk.top();
stk.push(i);
}
while (!stk.empty()) stk.pop();
for (int i = n-1; i >= 0; i--)
{
while (!stk.empty() && a[stk.top()] >= a[i]) stk.pop();
if (!stk.empty()) r[i] = stk.top();
stk.push(i);
}
for (int i = 0; i < n; i++)
{
int len = r[i]-l[i]-1;
ans[len] = max(ans[len], a[i]);
}
for (int i = n; i > 0; i--) ans[i] = max(ans[i], ans[i+1]);
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
return 0;
}