codeforces 617 E 莫队算法(求区间异或为k的数量)

莫队算法这么牛逼的一个算法,我决定把他学会,虽然目前我还对核心操作add(),sub()不太理解,但是我一定要把它肯出来,因为莫队对处理区间信息问题,真的是又快又牛批

题目链接:XOR and Favorite Number

AC代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
//莫队求区间异或和为k的种类
#define ll long long
const ll maxn=1e5+5;
struct node
{
    ll l,r,k;
} q[maxn];

ll pos[maxn],Xor[maxn];
ll ans[maxn];
ll c[2000000];
ll n,m,k,res;
bool cmp(node a,node b)
{
    if(pos[a.l]==pos[b.l])
        return a.r<b.r;
    return pos[a.l]<pos[b.l];
}

void add(ll i)
{

   res+=c[Xor[i]^k];
    c[Xor[i]]++; 
    //printf("%d\n",res);
    //printf("%d\n",k);


}
void sub(ll i)
{


    c[Xor[i]]--;
    res-=c[Xor[i]^k];
    //printf("%d\n",res);

}
int main()
{
    scanf("%lld %lld %lld",&n,&m,&k);
    ll dis=sqrt(n);
    memset(c,0,sizeof(c));
    Xor[0]=0;
    c[0]=1;
    for(ll i=1; i<=n; i++)
    {
        scanf("%lld",&Xor[i]);
        Xor[i]=Xor[i]^Xor[i-1];
        pos[i]=i/dis;
    }
    for(ll i=0; i<m; i++)
    {
        scanf("%lld %lld",&q[i].l,&q[i].r);
        q[i].k=i;
    }
    sort(q,q+m,cmp);
    ll L=1,R=0;
    //res=0;

    for(ll i=0; i<m; i++)
    {
        while(L<q[i].l)
        {
            sub(L-1),L++;
        }
        while(R>q[i].r)
        {
            sub(R),R--;
        }
        while(L>q[i].l)
        {
            L--,add(L-1);
        }
        while(R<q[i].r)
        {
            R++,add(R);
        }
        ans[q[i].k]=res;
    }
    for(ll i=0; i<m; i++)
    {
        printf("%lld\n",ans[i]);
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值