跳到正文

题解

「SMOI-R1」Game

_H17_约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年2月26日
更新
2026年2月26日
篇幅
约 4 分钟
题目
P10407

版本

  1. v1当前

题目分析

首先这种最值贡献可以直接尝试枚举数,找区间。区间一般一个带等号另一个不带。

这里有两种数:结束的端点和中间点。

中间的点的右边界就是自己。所有点的左边界是左边第一个更大的数,这个数一定是结束的端点,可以单调栈。

考虑中间点的右边界怎么求,也是反着做单调栈。注意一个细节:这个右边界不一定恰好是结束的端点。

预处理逆元之后,时间复杂度 O(n)O(n)。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
constexpr int N=1e6+1,p=998244353,inv2=499122177,inv3=332748118;
int n,a[N],l[N],r[N],sum[N],ans;
stack<pair<int,int> >st;
int calc(int a,int b,int x,int y){
    int ret=(a-1)*(((x+y)*(y-x+1)%p)*inv2%p)%p,cnt;
    a=b-a+1;
    cnt=((a+1)*a%p)*inv2%p;
    (ret+=(cnt*(x+2*y)%p)*inv3)%=p;
    return ret;
}
string program(){
    cin.tie(nullptr)->ios::sync_with_stdio(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        (sum[i]=sum[i-1]+a[i])%=p;
    }//l>=,r>
    for(int i=1,cur;i<=n;i++){
        cur=0;
        while(!st.empty()&&st.top().second<=a[i]-1){
            auto[pos,val]=st.top();
            st.pop();//i 的 cur+1~val 的 l 贡献
            if(cur+1>val)
                continue;
            int x=((sum[i]-a[i]+(cur+1))-pos)%p,y=((sum[i]-a[i]+val)-pos)%p;
            (ans+=calc(x,y,cur+1,val))%=p;
            cur=val;
        }
        if(!st.empty()){
            auto[pos,val]=st.top();
            //cur+1~a[i]-1 的 l 贡献
            if(cur+1<=a[i]-1){
                int x=((sum[i]-a[i]+(cur+1))-pos)%p,y=((sum[i]-1)-pos)%p;
                (ans+=calc(x,y,cur+1,a[i]-1))%=p;
            }
            l[i]=st.top().first+1;
        }
        else{
            if(cur+1<=a[i]-1){
                int x=(sum[i]-a[i]+(cur+1))%p,y=(sum[i]-1)%p;
                (ans+=calc(x,y,cur+1,a[i]-1))%=p;
            }
            l[i]=1;
        }
        st.push({sum[i],a[i]});
    }
    while(!st.empty())
        st.pop();
    for(int i=n;i>=1;i--){
        while(!st.empty()&&st.top().second<=a[i])
            st.pop();
        r[i]=(st.empty()?sum[n]:(st.top().first-(st.top().second-a[i])));
        st.push({sum[i],a[i]});
    }
    for(int i=1;i<=n;i++)
        (ans+=((sum[i]-l[i]+1)*(r[i]-sum[i]+1)%p)*a[i])%=p;
    print("{}",(ans%p+p)%p);
    return"H17";
}
string H17=program();
signed main(){
    return 0;
}
原文