三校联考20181017T1 异或xor
题意:
题解:
子任务1:直接暴力即可。
子任务3:我们随便举一个l=0,r=3的例子(为节省篇幅,表只打了一半)。
i | j | i^j |
---|---|---|
00 | 00 | 00 |
00 | 01 | 01 |
00 | 10 | 10 |
00 | 11 | 11 |
01 | 00 | 01 |
01 | 01 | 00 |
01 | 10 | 11 |
01 | 11 | 10 |
…
可以发现,枚举每一个i时,i^j都会使[l,r]中的每一个数恰好出现一次,所以就有.
子任务2:我们接着可以发现答案是可以按位计算的,对于某一位,令为这一位上0的个数,为这一位上1的个数。那么这一位上的结果就是。最后答案求和即可。可以枚举间的每一个数,累加每一位上1的个数。
正解:我们接着发现,上每一位的1的个数可以用以下方法来求:令t为最高位,那么第t位上1的个数加上,后面每一位上1的个数加上,然后递归处理。然后上每一位1的个数就是。
代码:
#include<cstdio>
#include<cstring>
#define mod 1000000007
#define D 32
int t,l,r,sum,cnt[D];
void Getcnt(int x,int d)
{
if(x<=0) return;
int t;
for(t=0;(1<<t)<=x;t++); t--;
cnt[t]+=d*(x-(1<<t)+1);
for(int i=0;i<t;i++) cnt[i]+=d*(1<<(t-1));
Getcnt(x-(1<<t),d);
}
int main()
{
scanf("%d",&t);
while(t--)
{
sum=0;
scanf("%d%d",&l,&r);
memset(cnt,0,sizeof(cnt));
Getcnt(r,1); Getcnt(l-1,-1);
for(int i=0;i<D;i++) sum=(sum+2ll*(1<<i)%mod*cnt[i]%mod*(r-l+1-cnt[i])%mod)%mod;
printf("%d\n",sum);
}
}