《二分答案》算法练习

目录

一、木材加工

二、EKO/砍树

三、跳石头


一、木材加工

P2440 木材加工 - 洛谷

答案如下:

cpp 复制代码
#include<iostream>
using namespace std;

typedef long long LL;

const int N = 1e5+10;
int a[N];
int n,k;

int cal(int x)
{
	int sum = 0;
	for(int i = 1; i <= n; i++)
	{
		sum += a[i]/x;
	}
	return sum;
}

int main()
{
	cin >> n >> k;
	int left = 0, right = 1e8;
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	while(left < right)
	{
		int mid = (left+right+1)/2;
		if(cal(mid) >= k)
		{
			left = mid;
		}
		else{
			right = mid-1;
		}
	}
	cout << left << endl;
	return 0;
 } 

二、EKO/砍树

P1873 COCI 2011/2012 #5 EKO / 砍树 - 洛谷

答案如下:

cpp 复制代码
#include<iostream>
using namespace std;

typedef long long LL;

const int N = 1e6+10;
LL a[N];
int n,m;

LL cal(LL x)
{
	LL ret = 0;
	for(int i = 1; i <= n; ++i)
	{
		if(x < a[i])
		{
			ret += a[i] - x;
		}
	}
	return ret;
}

int main()
{
	cin >> n >> m;
	LL max = 0;
	for(int i = 1; i <= n; ++i)
	{
		cin >> a[i];
		if(a[i] > max)
		{
			max = a[i];
		}
	}
	LL left = 0, right = max;
	while(left < right)
	{
		LL mid = (left + right + 1)/2;
		if(cal(mid) >= m)
		{
			left = mid;
		}
		else{
			right = mid - 1;
		}
	}
	cout << left << endl;
	return 0;
}

三、跳石头

P2678 NOIP 2015 提高组 跳石头 - 洛谷

答案如下:

cpp 复制代码
#include<iostream>
using namespace std;

const int N = 5e4 + 10;
int a[N];

int l,n,m;

int calc(int x)
{
	int ret = 0;
	for(int dst = 0, src = dst + 1; dst <= n; dst++)
	{
		while(src <= n && a[src] - a[dst] < x)
		{
			src++;
		}
		ret += src - dst - 1;
		dst = src - 1;
	 } 
	return ret; 
}

int main()
{
	cin >> l >> n >> m;
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	a[n+1] = l;
	n++; 
	int left = 0, right = l;
	while(left < right)
	{
		int mid = left + (right - left + 1)/2;
		if(calc(mid) > m)
		{
			right = mid - 1;
		}
		else{
			left = mid;
		}
	}
	cout << left << endl;
	return 0;
 } 
相关推荐
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
JieE2122 天前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack202 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树2 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2123 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2123 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术3 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦3 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4563 天前
C++进阶(1)——前景提要
c++