Light OJ 1105 Fi Binary Number(二分+数位DP)

解析:

二分x, 用数位dp查询1到x有多少个符合要求的数。

[code]:

#include
#include
#include
#include
#include

using namespace std;
typedef long long LL;
const int maxn = 1005;
const LL MOD = 1e9+7;
const LL INF = 1e18;

int n,bit[100],top;
LL dp[100][2];

LL dfs(int i,int s,bool e){
    if(i == -1) return 1;
    if(!e&&dp[i][s]!=-1) return dp[i][s];
    LL res = 0;
    int d,u = e?bit[i]:1;
    for(d = 0;d <= u;d++){
        if(d==0) res += dfs(i-1,d,e&&(d==u));
        else if(!s) res += dfs(i-1,d,e&&(d==u));
    }
    return e?res:dp[i][s]=res;
}

LL solve(LL n){
    top = 0;
    for(;n;n>>=1) bit[top++] = n&1;
    return dfs(top-1,0,1);
}
int main(){
    int i,j,cas,T;
    scanf("%d",&cas);
    memset(dp,-1,sizeof(dp));
    for(T = 1;T <= cas;T++){
        scanf("%d",&n);
        n++;
        printf("Case %d: ",T);
        LL mid,l = 0,r = INF;
        while(r-l>1){
            mid = (l+r)>>1;
            if(solve(mid)>=n) r = mid;
            else l = mid;
        }
        top = 0;
        for(;r;r>>=1) bit[top++] = r&1;
        for(i = top-1;i>=0;i--) printf("%d",bit[i]);
        putchar('\n');
    }

    return 0;
}


你可能感兴趣的:(DP,Mark)