洛谷 P1873 砍树(二分答案)

一、题目描述

在这里插入图片描述

二、算法分析说明

求砍树的最高高度(最低为多少),符合“求最大(小)值的最小(大)值”,直接套二分答案的模板。
二分答案算法的证明我还想不到。
在这里插入图片描述

三、AC 代码

#include<cstdio>
#pragma warning(disable:4996)
unsigned long long h[1000000], m; unsigned n;
template<class _Ty> inline bool check(const _Ty& M) {
	unsigned long long s = 0;
	for (unsigned i = 0; i < n; ++i)if (h[i] > M)s += h[i] - M;
	return s < m;
}
template<class _Ty> inline _Ty dichotomize(_Ty L, _Ty R) {
	_Ty M;
	while (L <= R) {
		M = (L + R) / 2;
		if (check(M))R = M - 1;
		else L = M + 1;
	}
	return L - 1;
}
int main() {
	scanf("%u%llu", &n, &m);
	for (unsigned i = 0; i < n; ++i)scanf("%llu", &h[i]);
	printf("%llu\n", dichotomize(0ull, 1000000001ull));
	return 0;
}
发布了214 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/COFACTOR/article/details/104072903
今日推荐