题解:AT_abc470_c [ABC470C] Inc, Dec, Xor

· · 题解

AT_abc470_c [ABC470C] Inc, Dec, Xor

题意

给定长度为 n 的序列 a_1,a_2...a_n,初始都为 0,q 次操作:

1.1 x 令 a_x\leftarrow a_x+1;

2.2 对于所有 i=1...n,a_i\ge 1,令 a_i\leftarrow a_i-1。

求每次操作后整个序列的异或和。

n,q\le 5 \times 10^5

思路

暴力显然是 O(nq) 的。

注意到序列初始值为 0,且每次操作 1 只能使一个值加 1,所以全局上有效的操作 2 至多只有 q 次(因为总和最多是 q)。

因此,考虑使用 set 动态维护序列中非零值的位置。设 S 为整个序列的异或和,对于操作 1,令 S\leftarrow S\oplus a_x\oplus(a_x-1);对于操作 2,直接重新计算 S 即可。

时间复杂度 O(q)。

代码

#include<iostream>
#include<set>
using namespace std;
const int N=5e5+9;
int n,q,a[N],op,x,S;
set<int> s;
int main(){
    cin>>n>>q;
    for(int i=1;i<=q;++i){
        cin>>op;
        if(op==1){
            cin>>x;
            S^=a[x];
            ++a[x];
            S^=a[x];
            s.insert(x);
        }
        else{
            S=0;
            auto it=s.begin();
            while(it!=s.end()){
                int pos=*it;
                --a[pos];
                S^=a[pos];
                if(!a[pos]) it=s.erase(it);
                else ++it;
            }
        }
        cout<<S<<'\n';
    }
    return 0;
}