結果

問題 No.2950 Max Min Product
ユーザー ooaiu
提出日時 2024-10-26 00:20:42
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 284 ms / 3,000 ms
コード長 2,049 bytes
コンパイル時間 3,508 ms
コンパイル使用メモリ 261,888 KB
実行使用メモリ 24,344 KB
最終ジャッジ日時 2024-10-26 00:20:55
合計ジャッジ時間 13,124 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
#include "algo/debug.h"
#else
#define debug(...) (void(0))
#endif

#include <atcoder/modint>
using mint = atcoder::modint998244353;
#include <atcoder/lazysegtree>
struct S {
    mint sum, sz;
};
S op(S a, S b) {
    return S{a.sum + b.sum, a.sz + b.sz};
}
S e() { return S{0, 0}; }
using F = long;
F id() { return -1; }
S mapping(F f, S x) {
    if(f == id()) return x;
    x.sum = f * x.sz;
    return x;
}
F composition(F f, F g) {
    if(f == id()) return g;
    return f;
}
void solve() {
    int N; cin >> N;
    vector<long> A(N);
    for(int i = 0; i < N; i++) cin >> A[i];
    atcoder::lazy_segtree<S, op, e, F, mapping, composition, id> Max(vector<S>(N, {0, 1})), Min(vector<S>(N, {0, 1}));
    mint ans = 0;
    vector<pair<long, long>> st1; // max
    vector<pair<long, long>> st2; // min
    mint sum = 0;
    for(int i = 0; i < N; i++) {
        {
            int w1 = 1;
            int cur = i;
            while(!st1.empty() && st1.back().first <= A[i]) {
                auto[h, w] = st1.back();

                sum += mint(A[i] - h) * Min.prod(cur - w, cur).sum;
                cur -= w;

                w1 += w;
                st1.pop_back();
            }
            st1.push_back({A[i], w1});
            Max.apply(i + 1 - w1, i + 1, A[i]);
        }
        {
            int w2 = 1;
            int cur = i;
            while(!st2.empty() && st2.back().first >= A[i]) {
                auto[h, w] = st2.back();

                sum -= mint(h - A[i]) * Max.prod(cur - w, cur).sum;
                cur -= w;

                w2 += w;
                st2.pop_back();
            }
            st2.push_back({A[i], w2});
            Min.apply(i + 1 - w2, i + 1, A[i]);
        }
        ans += sum;
        mint t = A[i] * A[i];
        ans += t;
        sum += t;
    }
    cout << ans.val() << endl;
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int tt = 1;
    // std::cin >> tt;
    while(tt--) {
        solve();
    }
}
0