Codeforces 985 D - Sand Fortress

本文介绍了一种使用二分法解决D-SandFortress问题的方法,通过两种不同的构造方式来找到最优解,并给出了具体的实现代码。

D - Sand Fortress

思路:

二分

有以下两种构造,

分别二分取个最小。

代码:

#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pi acos(-1.0) 
#define LL long long 
//#define mp make_pair
#define pb push_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pii pair<int, int> 
#define mem(a, b) memset(a, b, sizeof(a))
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout);
//head
ULL n, h;
bool check(ULL t) {
    ULL res;
    if(t >= h) res = (1+t)*t/2 + t*(t-1)/2 - h*(h-1)/2;
    else res = (1+t)*t/2;
    if(res >= n) return true;
    else return false;
} 
bool Check(ULL t) {
    ULL res;
    if(t >= h) res = (1+t)*t - h*(h-1)/2;
    else res = (1+t)*t/2;
    if(res >= n) return true;
    else return false;
}
int main() {
    scanf("%llu%llu", &n, &h);
    ULL l = 0, r = 2e9, m = (l+r) >> 1;
    while(l < r) {
        if(check(m)) r = m;
        else l = m+1;
        m = (l+r) >> 1;
    }
    ULL ans;
    if(m >= h) ans = 2*m - h;
    else ans = m;
    l = 0, r = 2e9, m = (l+r) >> 1;
    while(l < r) {
        if(Check(m)) r = m;
        else l = m+1;
        m = (l+r) >> 1;
    }
    if(m >= h) ans = min(ans, 2*m - h + 1);
    else ans = min(ans, m);
    printf("%llu\n", ans); 
    return 0;
}

 

转载于:https://www.cnblogs.com/widsom/p/9074529.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值