题解:AT_abc246_h [ABC246Ex] 01? Queries

· · 题解

题解

显然是一个 dp,那么我们先考虑不带修的情况。

设 f_{i,0/1} 表示前 i 位以 0/1 结尾的方案数。

转移我们分三种情况。

f_{i,0} =f_{i-1,0} f_{i,1}=f_{i-1,0}+f_{i-1,1}+1 f_{i,0} =f_{i-1,0}+f_{i-1,1}+1 f_{i,1}=f_{i-1,1} f_{i,0} =f_{i-1,0}+f_{i-1,1}+1 f_{i,1}=f_{i-1,0}+f_{i-1,1}+1

解释一下,这里只考虑选 s_i 作为子序列末尾的原因。

  1. 这样可以做到不重。因为每次都把前面不重的方案在最后加上了 s_i。

  2. 这样可以做到不漏。因为当 s_i 不选时,把所有之前结尾和 s_i 一样的换成 s_i 本质等价。也就是不选的情况对答案没有贡献。

而加一表示直接让其变成单独的新子序列。

接下来我们来考虑 ddp 的部分。

直接转成:

f_{i,0}=f_{i-1,0}+[s_i\ne1]\times (f_{i-1,1}+1) f_{i,1}=f_{i-1,1}+[s_i\ne0]\times (f_{i-1,0}+1)

再写出矩阵:

\begin{bmatrix} f_{i-1,0} & f_{i-1,1}&1 \end{bmatrix} \times \begin{bmatrix} 1 & [s_i\ne0] & 0\\ [s_i\ne1] & 1&0\\ [s_i\ne1]&[s_i\ne0]&1& \end{bmatrix} = \begin{bmatrix} f_{i,0} & f_{i,1}&1 \end{bmatrix}

线段树维护即可。

AC_Code

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10, mod = 998244353;
char s[N], c;
LL n, q, x;
struct node{
    LL a[4][4];
    node(){
        memset(a, 0, sizeof a);
    }
    node operator * (const node& b)const{
        node res;
        for(LL i = 0; i < 3; i ++){
            for(LL k = 0; k < 3; k ++){
                if(a[i][k] == 0)continue;
                for(LL j = 0; j < 3; j ++){
                    res.a[i][j] += a[i][k] * b.a[k][j] % mod;
                    res.a[i][j] %= mod;
                }
            }
        }
        return res;
    }
    void build(LL x){
        a[0][0] = a[1][1] = a[2][2] = 1;
        a[1][0] = a[2][0] = (s[x] != '1');
        a[0][1] = a[2][1] = (s[x] != '0'); 
    }
}base;
struct TR{
    LL l, r;
    node res;
}tr[N * 4];
void pushup(LL k){
    LL lc = k * 2, rc = k * 2 + 1;
    tr[k].res = tr[lc].res * tr[rc].res;
}
void build(LL k, LL l, LL r){
    tr[k].l = l, tr[k].r = r;
    if(l == r){
        tr[k].res.build(l);
        return;
    }
    LL mid = l + r >> 1, lc = k * 2, rc = k * 2 + 1;
    build(lc, l, mid);
    build(rc, mid + 1, r);
    pushup(k);
}
void update(LL k, LL pos){
    if(tr[k].l == tr[k].r){
        tr[k].res.build(pos);
        return;
    }
    LL mid = tr[k].l + tr[k].r >> 1, lc = k * 2, rc = k * 2 + 1;
    if(pos <= mid)update(lc, pos);
    else update(rc, pos);
    pushup(k);
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n >> q >> s + 1;
    base.a[0][2] = 1;
    build(1, 1, n);
    while(q --){
        cin >> x >> c;
        s[x] = c;
        update(1, x);
        node res = base * tr[1].res;
        cout << (res.a[0][0] + res.a[0][1]) % mod << '\n';
    }
    return 0;
}

完结撒花。