上面是n2的dp式子,每一层都比上层有2个不同点:
1.多了个f[i - 1] * a[i],这个直接加上就可以
2.除了上面这个,每个之前的f[i] * max(…)中的max都多了个a[i]
我们需要考虑对2这个变动进行优化。maxx[i]代表以a[i]作为最大值*f[x](x< i)的答案,若当前a[i]比在栈里的a[st[top]]更大,那么说明之前那个maxx[st[top]]不应当再以a[st[top]]作为最大值,而变成了以a[i]为最大值,那么把之前贡献的加到现在的,再把之前的贡献清0,即把ansmax中的之前的属于maxx[st[top]]的贡献清掉。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define endl '\n'
#define int long long
const int maxn = 3e5 + 5;
const int mod = 998244353;
int stmax[maxn],stmin[maxn],minn[maxn],maxx[maxn],dp[maxn];
int top1,top2,n;
int a[maxn];
void solve(){
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
dp[0] = 1;
int maxans = 0,minans = 0;
for (int i = 1; i <= n; ++i) {
while (top1 && a[i] > a[stmax[top1]]){
maxx[i] = (maxx[i] + maxx[stmax[top1]]) % mod;//以a[i]为最大值的maxx[i]要加上之前以a[stmax[top1]]的
maxans = ((maxans - maxx[stmax[top1]] * a[stmax[top1]] % mod) % mod + mod) % mod;//之前以a[stmax[top1]]为最大值的,由于a[i]更大,所以需要减去之前的贡献,之后再加以a[i]的共享
maxx[stmax[top1]] = 0;//clear贡献,但是可加可不加,因为每个i只会入栈一次出栈一次,这里下一步会马上出栈,即使不清除,下次也不会再遍历到了
top1 --;
}
stmax[++top1] = i;
maxx[i] = (maxx[i] + dp[i - 1]) % mod;
maxans = (maxans + maxx[i] * a[i]) % mod;
while (top2 && a[i] < a[stmin[top2]]){
minn[i] = (minn[i] + minn[stmin[top2]]) % mod;
minans = ((minans - minn[stmin[top2]] * a[stmin[top2]] % mod) % mod + mod) % mod;
minn[stmin[top2]] = 0;
top2 --;
}
stmin[++top2] = i;
minn[i] = (minn[i] + dp[i - 1]);
minans = (minans + minn[i] * a[i]) % mod;
dp[i] = ((maxans - minans) % mod + mod) % mod;
}
cout << dp[n];
}
signed main(){
std::ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t = 1;
// cin >> t;
while (t--) solve();
}