HDU

从D+1开始,对于一个数x,区间[x,x+lowbit(x))内的数字的二进制位上1的数量整体来说是单调不减的,因此可快速得出1在这个区间的取值范围。

每次判断一下有没有和[s1,s2]有没有交集,一旦发现解就贪心最小的一个。

复杂度是O(T*log(ans-D))

#include<bits/stdc++.h>
using namespace std;

inline int read()
{
    char c; while(c=getchar(),c<'0'||c>'9');
    int re = c-'0';
    while(c=getchar(),c>='0'&&c<='9') re = re*10+c-'0';
    return re;
}

#define lowbit(x) (x&-x)
int bc(long long x)
{
    int re = 0;
    while(x){
        re += x&1;
        x>>=1;
    }
    return re;
}

//bitset<64> bs;

#define cer(x) bs = x; cout<<bs<<endl;

//#define LOCAL
int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
#endif
    int T = read();
    for(int ks = 1; ks <= T; ks++){
        int D = read(), s1 = read(), s2 = read();
        long long cur = D+1LL,lb = lowbit(cur);
        int ct = bc(cur);
        while(ct < s1 || ct > s2){
            int ex = bc(lb-1);
            if(s1 > ct+ex || s2 < ct) {
                cur += lb;
                lb = lowbit(cur);
                ct = bc(cur);
            }else {
                int ad = max(ct,s1)-ct;
                cur += (1<<ad)-1;
                break;
            }
        }
        printf("Case #%d: %I64d
",ks,cur);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jerryRey/p/4842501.html