CodeForces 617E XOR and Favorite Number(莫队)

题意: 给你n个数,m次询问,询问给你(l,r),问你满足l ≤ i ≤ j ≤ r, ai^(ai+1)^...aj = k的区间数。


思路:因为又是区间又是没修改的询问,很容易想到莫队,但是怎么O(1)转移呢,可以利用异或的前缀和,具体思路可

以看官方题解:

We have array a.

Let's calculate array pref (pref[0] = 0).

Xor of subarray a[l...r] equals to .

So query (l, r) is counting number of pairs ij (l - 1 ≤ i < j ≤ r.

Let we know answer for query (l, r) and know for all v cnt[v] — count of v in a[l - 1...r]. We can update in O(1) answer and cnt if we move left or right border of query on 1. So we can solve problem offline in  with sqrt-decomposion (Mo's algorithm)


add和del操作时,要注意下num[x]改变和统计答案的先后顺序


代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e6+5;
int a[maxn], num[maxn], pre[maxn], unit, n, m, k;
ll tmp, ans[maxn];
struct node
{
    int l, r, id, blk;
    bool operator < (const node &a) const
    {
        if(blk == a.blk) return r < a.r;
        else return blk < a.blk;
    }
}op[maxn];

void add(int x)
{
    tmp += num[x^k];
    num[x]++;
}

void del(int x)
{
    num[x]--;
    tmp -= num[x^k];
}

void solve()
{
    int l = 1, r = 0;
    tmp = 0;
    memset(num, 0, sizeof(num));
    for(int i = 1; i <= m; i++)
    {
        while(r < op[i].r) add(pre[++r]);
        while(r > op[i].r) del(pre[r--]);
        while(l < op[i].l-1) del(pre[l++]);
        while(l > op[i].l-1) add(pre[--l]);
        ans[op[i].id] = tmp;
    }
    for(int i = 1; i <= m; i++)
        printf("%I64d\n", ans[i]);
}

int main(void)
{
    while(cin >> n >> m >> k)
    {
        unit = (int)sqrt(n);
        memset(pre, 0, sizeof(pre));
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]), pre[i] = pre[i-1]^a[i];
        for(int i = 1; i <= m; i++)
            scanf("%d%d", &op[i].l, &op[i].r), op[i].id = i, op[i].blk = op[i].l/unit;
        sort(op+1, op+1+m);
        solve();
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值