题解:AT_abc478_f [ABC478F] Min-First Search

· · 题解

考虑对每个点求合法父亲的数量。

一个显然的条件是 f_i<i,但这样不一定合法。考虑一个 j<i,Q_j>Q_i,则 Q_i,Q_j 一定不能在一同在 S 中出现,否则会先取出 Q_i 而非 Q_j。因此,还需要满足 f_i\ge l_i,其中 l_i 为上述最大的 j,不存在则为 1。最后的答案就是 i-l_i 的积。l_i 用单调栈维护即可。

时间复杂度 O(n)。 :::success[code]

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e5+5,mod=998244353;
int n,q[N],ans=1;
stack<int>st;
signed main(){
    // freopen(".in","r",stdin);
    // freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++) cin>>q[i];
    for(int i=1;i<=n;i++){
        while(!st.empty()&&q[st.top()]<q[i]) st.pop();
        if(i>1) ans=1ll*ans*(i-(st.empty()?1:st.top()))%mod;
        st.push(i);
    }
    cout<<ans<<'\n';
    return 0;
}/*
*/

:::