题解:AT_tenka1_2019_f Banned X

· · 题解

萌萌题但是我更萌。

首先经典结论,对于只有 0,1,2 的序列,若一个子区间和为 k,则对于所有 x\in[1,\lfloor\frac k2\rfloor],k-2x 都是可以凑出来的。

考虑拿出这个子区间,若有一端是 0,可以直接丢掉这个 0。

若有一端是 2,丢掉这个 2,就凑出来了 k-2。

否则两端都是 1,一起丢掉,也能凑出 k-2,故此得证。

设序列之和 s,分三类讨论:

  1. 否则可能合法也可能不合法。

发现第三类讨论是模糊不清的,从此入手。

首先我们可以直接枚举 0 的个数 x,因为 0 放在哪里都不影响答案,只需要最后将答案乘上 {n\choose x} 就行了,现在我们认为序列中只存在 1,2。

顺势枚举 1,2 的个数 y,z。

令 i,j 表示序列的最前面和最后面有多少个 2,正式开始讨论充要条件。

我们声称,s-2\min(i,j)-1<X 是不存在子区间和为 X 的充要条件。

理由:我们肯定是要找到所以一个和最大的子区间,使得其和 sum 与 X 奇偶性相同,显然 sum<X 是合法的充要条件,不难发现拿出这个子区间的方法是从序列的一端扣掉若干个 2 和一个 1。

所以若 s-2\min(i,j)-1<X,则我们无法找到一个子区间和为 X。

移项发现 \min(i,j)\ge\lfloor\frac{s-X-1}{2}\rfloor+1。

说明序列前后都至少有 \lfloor\frac{s-X-1}{2}\rfloor+1 个 2,剩下的 1,2 可以随便放,就做完了。

注意分讨 y=1 和 y=0 的情况,是容易的。

#include<bits/stdc++.h>

using namespace std;

const int N=6010;
const int mod=998244353;
struct modint {
    int val;
    static int norm(const int& x) { return x < 0 ? x + mod : x; }
    inline int Mod(int x){return x>=mod?x-mod:x;}
    modint inv() const {
        int a = val, b = mod, u = 1, v = 0, t;
        while (b > 0) t = a / b, swap(a -= t * b, b), swap(u -= t * v, v);
        return modint(u);
    }
    modint() : val(0) {}
    modint(const int& m) : val(norm(m)) {}
    modint(const long long& m) : val(norm(m % mod)) {}
    modint operator-() const { return modint(norm(-val)); }
    modint& operator+=(const modint& o) { return val = Mod(val + o.val), *this; }
    modint& operator-=(const modint& o) { return val = norm(1ll * val - o.val), *this; }
    modint& operator*=(const modint& o) { return val = static_cast<int>(1ll * val * o.val % mod), *this; }
    modint operator-(const modint& o) const { return modint(*this) -= o; }
    modint operator+(const modint& o) const { return modint(*this) += o; }
    modint operator*(const modint& o) const { return modint(*this) *= o; }
    friend std::ostream& operator<<(std::ostream& os, const modint& a) { return os << a.val; }
}c[N][N],ans,tot;

int n,X;
inline modint C(int n,int m){return (n<m||m<0)?0:c[n][m];}
inline modint C3(int x,int y,int z){return c[x+y+z][x]*c[y+z][y];}
inline void init(int n=3001){
    c[0][0]=1;
    for(int i=1;i<=n;++i){
        c[i][0]=c[i][i]=1;
        for(int j=1;j<i;++j) c[i][j]=c[i-1][j]+c[i-1][j-1];
    }
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    cin>>n>>X;init();
    for(int x=0;x<=n;++x){
        modint ws=0;
        for(int y=0;y<=n-x;++y){
            int z=n-x-y,sum=y+2*z,w=(sum-X-1)/2+1;
            if(sum<X){ans+=C3(x,y,z);continue;}
            if((sum&1)==(X&1)) continue;
            if(!y){ans+=C3(x,y,z);continue;}
            if(z<2*w) continue;
            if(y==1){ans+=C(x+y+z,x)*(z-2*w+1);continue;}
            ws+=C(y+z-2*w,y);
        }
        ans+=ws*c[n][x];
    }
    cout<<ans<<'\n';
    return 0;
}