2018CCPC女生赛 C 二分+取整Log

题目链接


题意:
给定三个整数 a , b , K ,求使得 n a l o g 2 n b <= K n 的最大值。


思路:
因为函数单调,显然可以直接二分 n 去验证。

此题有两个需要注意的地方:
一是对于log以2为底的函数取整,不能直接使用log函数来求,会带来精度的误差。需要模拟计算过程对2重复做除法。
二是 k 的范围最大为 1 e 18 ,使用乘法的过程中可能会产生溢出,故需要自定义乘法函数,用来避免计算的溢出,具体实现可参考代码。

此题得解。


代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
typedef long long ll;
using namespace std;

ll a,b,K;

ll Mul(ll a,ll b){
    if(!a || !b) return 0;
    if(a>(K+5)/b) return K+5;
    a *= b;
    return a>(K+5)?K+5:a;
}

ll GetLog(ll x){
    ll y = x;
    while(y%2 == 0) y/=2;
    ll res = 0;
    while(x>1) x/=2,res++;
    if(y>1) res++;
    return res;
}

ll Pow(ll n,ll m){
    ll res = 1;
    while(m--){
        res = Mul(res,n);
    }
    return res;
}

bool check(ll n){
    if(Mul(Pow(n,a),Pow(GetLog(n),b)) <= K) return true;
    return false;
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%I64d%I64d%I64d",&a,&b,&K);
        ll l = 1,r = K,ans = 0;
        while(l<=r){
            ll mid = (l+r)>>1;
            if(check(mid)){
                ans = mid;
                l = mid + 1;
            }
            else r = mid - 1;
        }
        printf("%I64d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wubaizhe/article/details/80497193