最佳植树距离

#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

int minSpace(vector<int>& holes, int target)

{

sort(holes.begin(), holes.end());

int left = 0;

int right = holes.back() - holes.front();

int answer = -1;

while (left <= right)

{

int mid = left + (right - left) / 2;

int count = 1;

int previous = holes[0];

for (int i = 1; i < holes.size(); i++)

{

if (holes[i] - previous >= mid)

{

count++;

previous = holes[i];

if (count >= target)

{

answer = mid;

left = mid + 1;

break;

}

}

}

if (count < target)

{

right = mid - 1;

}

}

return answer;

}

int main()

{

int n;

cin >> n;

vector<int> holes(n);

for (int i = 0; i < n; i++)

{

cin >> holes[i];

}

int target;

cin >> target;

int result = minSpace(holes, target);

cout << result << endl;

return 0;

}

相关推荐
淡海水4 分钟前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
西工程小巴37 分钟前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程1 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit1 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
青草地溪水旁1 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁2 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
百度Geek说2 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven2 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven2 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试
CoovallyAIHub2 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·计算机视觉