LightOJ 1352 Strange Summation(规律)

Description
给出一个区间[L,R],把这个区间所有数的二进制表示按最高位对其之后求异或和
Input
第一行一整数T表示用例组数,每组用例输入两整数L和R表示查询区间(1<=T<=1e4,0 < L < R < 2^63)
Output
输出一个整数表示区间[L,R]所有数的二进制表示按最高位对其之后求异或和
Sample Input
4
1 4
2 5
1 2147483647
7 12
Sample Output
Case 1: 2
Case 2: 3
Case 3: 1610612736
Case 4: 2
Solution
问题转化为求[1,N]中从左向右第i位为1的数的个数,第0位显然为N,因为每个数的最高位都是1,下面考虑第i位,首先一个数有第i位,那么其值最少是2^i,之后枚举第i位右边位数,找规律看每多一位第i位上会多多少个1,之后还有些剩的(即当前长度的数不全在区间内),假设第i位右边有x位,那么后面的数字每大2^x第i位才会进位,也即由0变1,假设剩下的数有cnt个,那么变1的有cnt/(2^x)/2次由0变1,对答案的贡献就是cnt/(2^x)/2*(2^x),如果cnt/(2^x)为奇数,说明余数部分也全部是1,对答案贡献就是cnt%(2^x)
Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 111
ll cnt[maxn];
void Solve(ll n,int sta)
{
    cnt[0]+=n*sta;
    for(int i=1;i<63;i++)
    {
        ll m=1ll<<i,len=1;
        if(m>n)break;
        while(m<=n/2)
        {
            cnt[i]+=m/2*sta;
            m<<=1ll,len<<=1ll;
        }
        m=n-m+1;
        cnt[i]+=(m/len/2*len)*sta;
        if((m/len)&1)cnt[i]+=(m%len)*sta;   
    }
}
int main()
{
    int T,Case=1;
    ll l,r;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&l,&r);
        memset(cnt,0,sizeof(cnt));
        Solve(r,1),Solve(l-1,-1);
        int res=0;
        while(r)res++,r>>=1;
        ll ans=0;
        for(int i=0;i<res;i++)
            if(cnt[i]&1)ans+=1ll<<(res-1-i);
        printf("Case %d: %lld\n",Case++,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值