题解:P11325 【MX-S7-T3】「SMOI-R2」Monotonic Queue
考虑特殊性质 A,令
这个过程启发我们关注队列中只有一个元素的时刻,令队列有且仅有
显然最终答案为
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
constexpr int maxn = 500000 + 10;
i64 c[maxn], a[maxn], g[maxn];
i64 f[maxn];
int s[maxn], p[maxn];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i=1;i<=n;++i) cin >> c[i];
for (int i=1;i<=n;++i) cin >> a[i];
memset(f, 0xcf, sizeof(f));
f[1] = 0;
i64 ans = 0;
for (int i=n,top=0;i>=1;--i)
{
while (top && a[s[top]] < a[i]) --top;
if (top) p[i] = s[top];
s[++top] = i;
}
for (int i=1;i<=n;++i) g[i] = c[i] + g[i - 1];
for (int i=1;i<=n;++i)
{
ans = max(ans, f[i]);
f[i + 1] = max(f[i + 1], f[i] + (a[i + 1] > a[i] ? c[i] : 0));
if (p[i]) f[p[i]] = max(f[p[i]], f[i] + g[p[i] - 1] - g[i - 1]);
}
cout << ans << '\n';
return 0;
}