T3
非常好的一道题。
我们发现如果枚举每一个子段,时间复杂度是 的,且很难优化。于是换一个角度,考虑算每个 对答案的贡献(经典的转化了)。
对于一个 ,我们先想想它在哪些长度的子段中会产生贡献,即什么情况下它是一个子段的最小值。我们可以用单调栈求出 能成为最小值的最大子段长度 ,这样 就会在 时作为某个子段的最小值出现。但我们貌似还是不好算总贡献。
接下来是最精彩的地方:发现 一定大于 ,具有单调性。于是我们先让 ,然后让 ,这样就将所有的贡献都统计上了。
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, a[N], L[N], R[N], ans[N];
stack<int> stk1, stk2;
int main() {
cin.tie(0) -> sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
R[i] = n + 1;
}
for (int i = 1; i <= n; i++) {
while (!stk1.empty() && a[stk1.top()] > a[i]) {
R[stk1.top()] = i;
stk1.pop();
}
stk1.push(i);
}
for (int i = n; i >= 1; i--) {
while (!stk2.empty() && a[stk2.top()] > a[i]) {
L[stk2.top()] = i;
stk2.pop();
}
stk2.push(i);
}
for (int i = 1; i <= n; i++) {
int len = (R[i] - 1) - (L[i] + 1) + 1;
ans[len] = max(ans[len], a[i]);
}
for (int i = n; i >= 1; i--)
ans[i] = max(ans[i], ans[i + 1]);
for (int i = 1; i <= n; i++)
cout << ans[i] << ' ';
return 0;
}T4
简单线段树,如果乘积超过 就设为 即可。
代码
#include <bits/stdc++.h>
#define ls(x) (x << 1)
#define rs(x) (x << 1 | 1)
#define int long long
using namespace std;
const int N = 1e5 + 5;
int q, pos, tr[N << 2];
int get(int x, int y) {
if (!x || !y)
return 0;
else if (x == -1 || y == -1 || x >= (1ll << 32) / y)
return -1;
else return x * y;
}
void pushup(int cur) {
tr[cur] = get(tr[ls(cur)], tr[rs(cur)]);
}
void modify(int cur, int l, int r, int x, int val) {
if (r < x || l > x) return ;
if (l == r) {
tr[cur] = val;
return ;
}
int mid = l + r >> 1;
modify(ls(cur), l, mid, x, val);
modify(rs(cur), mid + 1, r, x, val);
pushup(cur);
}
int query(int cur, int l, int r, int x, int y) {
if (l > y || r < x) return 1;
if (x <= l && r <= y) return tr[cur];
int mid = l + r >> 1;
return get(query(ls(cur), l, mid, x, y), query(rs(cur), mid + 1, r, x, y));
}
signed main() {
cin.tie(0) -> sync_with_stdio(0);
cin >> q;
while (q --) {
int opt, x; cin >> opt;
if (opt == 1) {
cin >> x;
pos ++;
modify(1, 1, 1e5, pos, x);
}
else if (opt == 2 && pos) pos --;
else if (opt == 3) {
cin >> x;
if (pos < x) {
cout << "ERROR\n";
continue;
}
int ans = query(1, 1, 1e5, pos - x + 1, pos);
if (ans < 0) cout << "OVERFLOW\n";
else cout << ans << '\n';
}
}
return 0;
}