codeforce 768B Code For 1

题意:将n分解为n/2, n%2, n/2三部分,再将n/2分解。。得到一个序列只有0和1,给出[l, r]问l到r有几个1
#include <stdio.h>
#define ll __int64
ll query(ll L,ll R,ll l,ll r,ll n){
    if(l == r) return n;
    ll mid = (l+r)>>1, ans=0;
    if(L <= mid-1) ans += query(L, R, l, mid-1, n>>1);
    if(mid+1 <= R) ans += query(L, R, mid+1 ,r, n>>1);
    if(mid <= R && mid >= L) ans += n%2;
    return ans;
}
ll f(ll n){
    if(n == 1||n == 0) return 1;
    return 2*f(n>>1)+1;
}
int main()
{
    ll n, l, r;
    scanf("%I64d%I64d%I64d", &n, &l, &r);
    printf("%I64d\n", query(l, r, 1, f(n), n));
    return 0;
}

题解:可以画出一棵树,发现是左右对称,直接DFS会超时,用到二分思想,分为左右区间递归处理

posted on 2017-03-10 20:28  2855669158  阅读(181)  评论(0编辑  收藏  举报

导航