AtCoder Beginner Contest 234 G Divide a Sequence

在这里插入图片描述
上面是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();

}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值