洛谷P3760 - [TJOI2017]异或和

Portal

Description

给出一个\(n(n\leq10^5)\)的序列\(\{a_n\}(\Sigma a_i\leq10^6)\),求该数列所有连续和的异或和。

Solution

线段树/树状数组。
首先做出前缀和\(p\),然后按位考虑答案上的值。考虑\(2^k\)这一位,有多少个连续和\([i,j]\)\(2^k\)位为\(1\)。我们发现,\(x\)\(2^k\)位上为\(1⇔x \bmod 2^{k+1}\in[2^k,2^{k+1}-1]\)。那么对于每一个\(j\),求出有多少个\(i<j\)满足\((p_j-p_i) \bmod 2^{k+1}\in[2^k,2^{k+1}-1]\),即\(p_i\in[p_j-2^{k+1}+1,p_j-2^k] \pmod {2^{k+1}}\)。那么我们只要用线段树来做就好啦。注意这个区间有可能由于取模而被分成两半,要分别来求。

时间复杂度\(O(nlog^2(\Sigma a_i))\)

Code

//[TJOI2017]异或和
#include <cstdio>
#include <cstring>
typedef long long lint;
inline char gc()
{
    static char now[1<<16],*s,*t;
    if(s==t) {t=(s=now)+fread(now,1,1<<16,stdin); if(s==t) return EOF;}
    return *s++;
}
inline int read()
{
    int x=0; char ch=gc();
    while(ch<'0'||'9'<ch) ch=gc();
    while('0'<=ch&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x;
}
const int N=1e5+10;
int n; lint pre[N];
const int N1=4e6;
int cnt,rt,ch[N1][2]; int sum[N1];
inline void update(int p) {sum[p]=sum[ch[p][0]]+sum[ch[p][1]];}
void ins(int &p,int L0,int R0,int x)
{
    if(!p) p=++cnt;
    if(L0==R0) {sum[p]++; return;}
    int mid=L0+R0>>1;
    if(x<=mid) ins(ch[p][0],L0,mid,x);
    else ins(ch[p][1],mid+1,R0,x);
    update(p);
}
int optL,optR;
int query(int p,int L0,int R0)
{
    if(!p) return 0;
    if(optL<=L0&&R0<=optR) return sum[p];
    int mid=L0+R0>>1; int res=0;
    if(optL<=mid) res+=query(ch[p][0],L0,mid);
    if(mid<optR) res+=query(ch[p][1],mid+1,R0);
    return res;
}
int check(lint m)
{
    cnt=0; rt=++cnt;
    memset(ch,0,sizeof ch);
    memset(sum,0,sizeof sum);
    lint m1=m<<1,res=0;
    for(int i=0;i<=n;i++)
    {
        lint x=pre[i]%m1,y=x-m;
        if(y<0) optL=x+1,optR=y+m1,res+=query(rt,0,m1-1);
        else
        {
            optL=0,optR=y; res+=query(rt,0,m1-1);
            optL=x+1,optR=m1-1; if(optL<=optR) res+=query(rt,0,m1-1);
        }
        ins(rt,0,m1-1,x);
    }
    return res&1;
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++) pre[i]=pre[i-1]+read();
    lint ans=0;
    for(lint i=1;i<=pre[n];i<<=1) if(check(i)) ans|=i;
    printf("%lld\n",ans);
    return 0;
}

P.S.

星际了看错题以为\(a_i\leq10^6\),也就是\(\Sigma a_i\leq10^{11}\)所以用了动态开点线段树...实际上用树状数组就可以解决,常数还要小很多。

转载于:https://www.cnblogs.com/VisJiao/p/LgP3760.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值