题解:P11731 [集训队互测 2015] 最大异或和

· · 题解

题意简述

给定一个长度为 n 的序列 \{a_n\},值域 [0,2^m)。有 q 次操作,每次是下面的一种:

  1. 给定 l,r,w。\forall i \in [l,r],使 a_i \gets a_i \oplus w。w 值域 [0,2^m)。
  2. 给定 l,r,w。\forall i \in [l,r],使 a_i \gets w。w 值域 [0,2^m)。
  3. 求 \max_{S \subseteq [1,n] \cap \mathbb{Z}} \oplus_{i \in S} a_i。

其中 \oplus 表示二进制按位异或,n,m,q \le 2000,a_i 和 w 使用二进制给出。

思路

看到操作 3,一眼线性基。

由于线性基每次是 O(\frac{m^2} w) 的,所以每次操作不可能修改 n 个位置。考虑 \{a_n\} 的差分数组 d_i = a_i \oplus a_{i-1},显然 \{d_n\} 的线性基也是 \{a_n\} 的线性基。

这样,前两个操作就变成了 O(q) 个单点修改和 q 次区间赋 0。根据均摊分析,从非 0 变为 0 次数是 O(n+q) 的,故修改的次数是 O(n+q) 的。

现在我们只需要一个可删除的线性基。简单离线维护出每个非 0 数 x 出现的时间区间 [l,r]。对于在 t 时刻的查询,只需要保留 l \le t \le r 的 x,l 可以按时间排序后双指针或使用 vector 等维护,r 可以使用前缀线性基做到保留 r \ge t 的部分。

这样做的时间复杂度是 O(\frac{(n+q) m^2} w),空间复杂度 O(\frac{(n+m+q)m} w),可以通过。

线段树分治或许也能过。

代码

#include<bits/stdc++.h>
using namespace std;
using bs = bitset<2000>;
int n,m,q;
struct Linear_Basis
{
    bs p[2000];
    int t[2000];
    Linear_Basis()
    {
        memset(t,-1,sizeof(t)); 
    }
    void insert(bs x,int ti)
    {
        for(int i=m-1;i>=0;i--)
        {
            if(!x[i])
                continue;
            if(t[i]==-1)
            {
                p[i] = x;
                t[i] = ti;
                return;
            }
            else if(t[i]<ti)
            {
                swap(x,p[i]);
                swap(ti,t[i]);
            }
            x ^= p[i];
        }
    }
    bs query(int mt)
    {
        bs ans;
        for(int i=m-1;i>=0;i--)
            if(!ans[i]&&t[i]>mt)
                ans ^= p[i];
        return ans;
    }
}b;
struct mdf
{
    bs v;
    int t;
    mdf(bs _v=0,int _t=0):v(_v),t(_t){}
};
vector<mdf> md[2007];
bs a[2007];
bs d[2007];
int lst[2007];
void update(int idx,bs val,int tim)
{
    if(val==d[idx])
        return;
    if(d[idx].any())
        md[lst[idx]].emplace_back(mdf(d[idx],tim));
    d[idx] = val;
    lst[idx] = tim;
}
bitset<2007> qr;
int op,l,r;
bs w;
signed main()
{
    cin.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);
    cin>>n>>m>>q;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        d[i] = a[i] ^ a[i-1];
    }
    for(int i=1;i<=q;i++)
    {
        cin>>op;
        if(op==3)
            qr[i] = true;
        else
        {
            cin>>l>>r>>w;
            if(op==1)
                for(int j=l;j<=r;j++)
                    a[j] ^= w;
            else if(op==2)
                for(int j=l;j<=r;j++)
                    a[j] = w;
            for(int j=l;j<=min(r+1,n);j++)
                update(j,a[j]^a[j-1],i);
        }
    }
    for(int i=1;i<=n;i++)
        if(d[i].any())
            md[lst[i]].emplace_back(mdf(d[i],q+1));
    for(auto& x:md[0])
        b.insert(x.v,x.t);
    for(int i=1;i<=q;i++)
    {
        for(auto& x:md[i])
            b.insert(x.v,x.t);
        if(qr[i])
            cout<<b.query(i).to_string().substr(2000-m)<<'\n';
    }
}