CF 106296 F题 05.31 周赛vp 【思维转化 -> 正反两次线性遍历,找峰谷】

· · 题解

原题链接:https://codeforces.com/gym/106296/problem/F

题目要求:

P_1 < P_2 > P_3 < P_4 > \cdots

且:

A_{P_i} \equiv i \pmod 2

因为 A_x\in\{0,1\},所以:

奇数位置只能放 A_x=1 的数;
偶数位置只能放 A_x=0 的数。

于是 A_x=1 的数是谷,A_x=0 的数是峰。 把不等式拆成两类:

P_1<P_2,\ P_3<P_4,\ldots

和:

P_2>P_3,\ P_4>P_5,\ldots

第一类从小到大扫。
遇到 1 表示一个可用的谷,cnt++;遇到 0 表示峰,它要选择一个之前更小的谷,方案数乘 cnt,然后 cnt--。

第二类从大到小扫。
反转数组即可。遇到 0 表示一个可用的峰,cnt++;遇到 1 表示谷,它要选择一个之前更大的峰,方案数乘 cnt,然后 cnt--。

若 n 为奇数,最后会多一个谷,它不需要右侧匹配,所以第二遍只扫 n-1 个。

复杂度分析:

时间复杂度:O(n)

空间复杂度:O(n)

代码:

/ AC代码附上

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define all(a) (a).begin(), (a).end()
#define all1(a) (a).begin()+1, (a).end()
const int MOD = 998244353;

template<class A> string to_string(const A& v) {
    string s = "{";
    for (const auto& x : v) s += ((s).size() > 1 ? ", " : "") + to_string(x);
    return s += "}";    
}

template<class A, class B> string to_string(const pair<A, B>& p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
void debug_out() { cerr << '\n'; }

template<class T, class... U>
void debug_out(const T& x, const U&... args) {
    cerr << ' ' << to_string(x);
    debug_out(args...);
}
// 91: red 93: yellow 96: blue
#define sc(x) cerr << "\033[" << x << "m" 
#define debug(...) sc(96), cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__), sc(39)

void work(){
    int n;
    cin >> n;
    vector<int> a(n);
    for(int i=0; i<n; ++i) cin >> a[i];

    ll ans = 1, cnt1 = 0, cnt2 = 0;
    for(int i=0; i<n; ++i){ // 数字从小到大,为每一个峰找左边比它小的谷的个数
        if(a[i] == 1) ++cnt1; // p数组中的 奇数位置,谷

        else{ // p数组中的 偶数位置,峰
            ans = ans * cnt1 % MOD;
            --cnt1; // 用掉了一个谷
        }
    }

    for(int i=n-1; i>0; --i){ // 数字从大到小,为每一个谷找右边比它大的峰的个数
        if(a[i] == 0) ++cnt2; // p数组中的 偶数位置,峰

        else{ // p数组中的 奇数位置,谷
            ans = ans * cnt2 % MOD;
            --cnt2; // 用掉了一个峰
        }
    }
    cout << ans << '\n';
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T = 1;
    // cin >> T;
    while(T--) work(); 
}
/*

*/