Codeforces 703D Mishka and Interesting sum (树状数组求区间内不同的数的异或和)

本文介绍了一道关于区间内出现偶数次数值异或的算法题目,通过巧妙运用树状数组和前缀异或操作,实现了高效查询。文章对比了两种解法,并详细解释了如何利用树状数组来跟踪不同元素。

http://www.codeforces.com/contest/703/problem/D

Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, …, an of n elements!

Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can’t process large arrays. Right because of that she invited you to visit her and asked you to process m queries.

Each query is processed in the following way:

Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment.
Integers, presented in array segment [l,  r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down.
XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value , where  — operator of exclusive bitwise OR. 

Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Input

The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array.

The second line of the input contains n integers a1, a2, …, an (1 ≤ ai ≤ 109) — array elements.

The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries.

Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment.
Output

Print m non-negative integers — the answers for the queries in the order they appear in the input.

Examples
Input

3
3 7 8
1
1 3

Output

0

Input

7
1 2 1 3 3 2 3
5
4 7
4 5
1 3
1 7
1 5

Output

0
3
1
3
2


题意:求区间内出现偶数次的数的所有异或值。
解题思路:

区间内所有数的异或值 = 区间内出现奇数次的数的所有异或值

区间内出现偶数次的数的所有异或值 = 区间内所有数的异或值 ^ 区间内不同的数的异或值。

然而区间内所有数的异或值可以用前缀异或数组得到,问题转化成求区间内不同的数的异或值。一开始用莫队算法,O(n*sqrt(n)) TLE了。标答是 O(nlog(n))。

标答是O(nlog(n)): 维护一个last[]数组,记录的是当前i位置的数在它前面出现的位置。然后按照询问的r从小到大排序。枚举n,插入该位置的数,当这个数前面出现过,即last[i]不等于0,那么先将这个数删掉,然后再插入当前位置的的数。这样就保证了每个数在树状数组里面仅出现过一次。
这种做法要记住。可活用。


先贴一份TLE的莫队算法:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <math.h>
using namespace std;

typedef long long LL;
const int N = 1e6 + 100;
LL arr[N],XOR[N],ANS[N];
int size;
map<LL,int> Hash;
struct Node
{
        int l,r,id;
        friend bool operator < (const Node &a, const Node &b)
        {
                if(a.l/size == b.l/size) return a.r < b.r;
                else return a.l/size < b.l/size;
        }
}q[N];
void work(int k)
{
        LL now = 0;
        int curL = q[1].l, curR = q[1].r;
        for(int i=curL; i<=curR ;i++)
        {
               now ^=  (Hash[arr[i]] ? 0 : arr[i]);
               Hash[arr[i]]++;
        }
        ANS[q[1].id] =  now ^ (XOR[q[1].l-1] ^ XOR[q[1].r]);

        for(int i=2;i<=k;i++)
        {
                while(q[i].l > curL)
                {
                        if(Hash[arr[curL]]==1) now ^= arr[curL];
                        Hash[arr[curL]]--;
                        curL++;
                }
                while(q[i].l < curL)
                {
                       curL--;
                       if(Hash[arr[curL]]==0) now ^= arr[curL];
                       Hash[arr[curL]]++;
                }
                while(q[i].r < curR)
                {
                        if(Hash[arr[curR]]==1) now^= arr[curR];
                        Hash[arr[curR]]--;
                        curR--;
                }
                while(q[i].r > curR)
                {
                        curR++;
                        if(Hash[arr[curR]]==0) now^= arr[curR];
                        Hash[arr[curR]]++;
                }
                ANS[q[i].id] = now ^ XOR[q[i].l-1] ^ XOR[q[i].r];
        }
}
int main()
{
        int n;
        scanf("%d",&n);
        size = (int)sqrt(n);
        for(int i=1;i<=n;i++) scanf("%I64d",&arr[i]), XOR[i] = XOR[i-1]^arr[i];
        int k;
        scanf("%d",&k);
        for(int i=1;i<=k;i++)
        {
                scanf("%d%d",&q[i].l,&q[i].r);
                q[i].id = i;
        }
        sort(q+1,q+1+k);
        work(k);
        for(int i=1;i<=k;i++) printf("%I64d\n",ANS[i]);
        return 0;
}

再贴一份AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;

const int N = 1e6 + 100;
int arr[N],n,XOR[N],last[N],tr[N],ans[N];
struct Node
{
    int l,r,id;
    friend bool operator < (const Node &a,const Node &b)
    {
        return a.r < b.r;
    }
}Q[N];
map<int,int>Hash;
int lowbit(int x) { return x&(-x); }
void add(int i,int val)
{
    for(;i<=n;i+=lowbit(i)) 
        tr[i] ^= val;
}
int query(int i)
{
    int res = 0;
    for(;i>=1;i-=lowbit(i))
        res ^= tr[i];
    return res;
}
int main()
{
    scanf("%d",&n);
    Hash.clear();
    memset(last,0,sizeof(last));
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&arr[i]);
        XOR[i] = XOR[i-1]^arr[i];
        last[i] = Hash[arr[i]];
        Hash[arr[i]] = i;
    }
    int m;
    scanf("%d",&m);
    for(int i=1;i<=m;i++) scanf("%d%d",&Q[i].l,&Q[i].r),Q[i].id = i;
    sort(Q+1,Q+1+m);

    int px = 1;
    for(int i=1;i<=n;i++)
    {
            if(last[i]) add(last[i],arr[i]);
            add(i,arr[i]);
            while( px <=m && Q[px].r == i  )
            {
                ans[Q[px].id] = query(Q[px].r) ^ query(Q[px].l-1);
                ans[Q[px].id] ^= XOR[Q[px].r] ^ XOR[Q[px].l-1];
                px++;
            }
    }
    for(int i=1;i<=m;i++) printf("%d\n",ans[i]);
    return 0;
}
<think>我们正在讨论两种不同树状数组技术: 1.树状数组(差分树状数组):支持区间修改(加减)单点查询。 2.树状数组:支持区间修改(加减)区间查询()。 用户的问题是:这两种技术实现的区间查询(注意:单树状数组的差分实现通常不支持区间查询,但用户可能指的是单树状数组差分实现中“单点查询”与双树状数组区间查询”的区别)? 因此,我们需要明确: - 单树状数组(差分实现)只能进行单点查询(即查询一个位置的值),无法直接进行区间查询()。 - 双树状数组则可以直接进行区间查询。 所以,这个问题可能是在问:在单树状数组差分实现中,我们只能查询单点,而双树状数组可以查询区间,那么它们之间的区别是什么?以及为什么会有这样的区别? 回答重点: 1. 功能区别:单树状数组差分实现只能单点查询,而双树状数组可以实现区间。 2. 实现原理:单树状数组差分实现维护的是差分组,而双树状数组维护两个差分组(其中一个维护的是d[i],另一个维护的是i*d[i])来支持区间。 3. 复杂度:双树状数组区间查询区间修改都是O(log n),而单树状数组差分实现区间修改是O(log n)(修改两个点),单点查询是O(log n)前缀),但区间查询如果要用单树状数组差分实现,则需要查询每个单点再,这样区间查询就是O(n log n),效率低。 因此,我们总结:双树状数组是为了解决区间修改区间查询而设计的,而单树状数组差分实现只能高效地支持区间修改单点查询。 下面我们按照要进行回答。</think>### 单树状数组差分查询 vs 双树状数组区间查询 #### 本质区别对比 | **特性** | 单树状数组(差分实现) | 双树状数组区间查询) | |------------------|--------------------------------------|--------------------------------------| | **核心功能** | 单点值查询 | 区间查询 | | **学本质** | $a[i] = \sum_{k=1}^{i} d[k]$ | $\sum_{i=l}^{r} a[i] = f(r) - f(l-1)$ | | **查询复杂度** | $O(\log n)$ (单点) | $O(\log n)$ (任意区间) | | **修改复杂度** | $O(\log n)$ (两点修改) | $O(\log n)$ (两点修改) | | **据结构量** | 1个树状数组 | 2个互补树状数组 | #### 技术实现差异 **单树状数组差分查询**: ```python def query_point(i): # 查询单点a[i] s = 0 while i > 0: s += bit[i] # 累加差分值 i -= i & -i return s ``` **双树状数组区间查询**: ```python def query_range(l, r): # 查询区间 &sum;a[l..r] def _query(pos): s1 = s2 = 0; x = pos while x > 0: s1 += bit1[x] # &sum;d[i] s2 += bit2[x] # &sum;(i*d[i]) x -= x & -x return (pos+1)*s1 - s2 # 核心公式 return _query(r) - _query(l-1) ``` #### 操作代价对比 | **操作类型** | 单树状数组差分实现 | 双树状数组实现 | |--------------------|--------------------------|------------------------| | 区间[l,r]加k | 修改2点:$O(2\log n)$ | 修改2点:$O(2\log n)$ | | 查询单点i | $O(\log n)$ | $O(\log n)$ | | 查询区间[l,r] | $O(n\log n)$ (遍历单点) | $O(\log n)$ | | 内存占用 | $O(n)$ | $O(2n)$ | #### 典型应用场景 - **单树状数组适用**: ✔️ 实时日志系统(批量标记+单点检查) ✔️ 游戏状态更新(区域BUFF/DEBUFF生效检测) - **双树状数组适用**: ✔️ 金融实时K线(分钟级区间交易量计算) ✔️ 基因组分析(DNA片段突变频率统计) ✔️ 竞赛难题(如Codeforces 上需要 $O(m\log n)$ 解决10⁵级区间查询)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值