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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lngxling/article/details/82992477

题意:

把一个数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;
}

猜你喜欢

转载自blog.csdn.net/Lngxling/article/details/82992477
今日推荐