CodeForces - 768B Code For 1 —— 递归分治

题意:

把一个数n拆分,奇数拆成n/2,1,n/2,偶数拆成n/2,0,n/2,1和0不可拆,问拆分后从l位置到r位置1的个数

思路:

分治递归拆分即可...想的太多...

n最大是2^50,最多递归调用也才是高为50的二叉树

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
#define ll long long
#define max_ 200100
#define mod 1000000007
#define inf 0x3f3f3f3f
#define eps 1e-9
ll n;
ll l,r;
ll length(ll n)
{
    if(n<=1)
    return 1;
    return 2*length(n/2)+1;
}
ll cal(ll n,ll l,ll r)
{
    if(l>r||l<=0||r<=0||n==0)
    return 0;
    if(n==1)
    return 1;
    ll len=length(n);
    ll mid=len/2+1;
    if(r<mid)
        return cal(n/2,l,r);
    else if(l>mid)
        return cal(n/2,l-mid,r-mid);
    else
        return cal(n/2,l,mid-1)+cal(n/2,1,r-mid)+(n&1);
}
int main(int argc, char const *argv[]) {
    scanf("%lld%lld%lld",&n,&l,&r);
    printf("%lld\n",cal(n,l,r));
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值