跳到正文

题解

题解:AT_abc246_h [ABC246Ex] 01? Queries

Your_Name约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年2月11日
收录
2026年2月4日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

题解

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


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

转移我们分三种情况。

  • 若 si=1s_i=1 则:
fi,0=fi−1,0f_{i,0} =f_{i-1,0} fi,1=fi−1,0+fi−1,1+1f_{i,1}=f_{i-1,0}+f_{i-1,1}+1
  • 若 si=0s_i=0 则:
fi,0=fi−1,0+fi−1,1+1f_{i,0} =f_{i-1,0}+f_{i-1,1}+1 fi,1=fi−1,1f_{i,1}=f_{i-1,1}
  • 若 si=s_i= 则:
fi,0=fi−1,0+fi−1,1+1f_{i,0} =f_{i-1,0}+f_{i-1,1}+1 fi,1=fi−1,0+fi−1,1+1f_{i,1}=f_{i-1,0}+f_{i-1,1}+1

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

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

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

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


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

直接转成:

fi,0=fi−1,0+[si≠1]×(fi−1,1+1)f_{i,0}=f_{i-1,0}+[s_i\ne1]\times (f_{i-1,1}+1) fi,1=fi−1,1+[si≠0]×(fi−1,0+1)f_{i,1}=f_{i-1,1}+[s_i\ne0]\times (f_{i-1,0}+1)

再写出矩阵:

[fi−1,0fi−1,11]×[1[si≠0]0[si≠1]10[si≠1][si≠0]1]=[fi,0fi,11]\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

C++
#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;
}

完结撒花。

原文