跳到正文

题解

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

Wangruofan约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年8月10日
更新
2026年8月10日
篇幅
约 2 分钟

版本

  1. v1当前

AT_abc470_c [ABC470C] Inc, Dec, Xor

题意

给定长度为 nn 的序列 a1,a2...ana_1,a_2...a_n,初始都为 00,qq 次操作:

1.1 x 令 ax←ax+1a_x\leftarrow a_x+1;

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

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

n,q≤5×105n,q\le 5 \times 10^5

思路

暴力显然是 O(nq)O(nq) 的。

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

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

时间复杂度 O(q)O(q)。

代码

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