最佳植树距离

#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;

}

相关推荐
TTTrees几秒前
C++学习笔记(32):智能指针(weak_ptr)
c++
qq_417695052 分钟前
基于C++的区块链实现
开发语言·c++·算法
We་ct4 分钟前
LeetCode 74. 搜索二维矩阵:两种高效解题思路
前端·算法·leetcode·矩阵·typescript·二分查找
2401_894241925 分钟前
基于C++的反射机制探索
开发语言·c++·算法
cui_ruicheng8 分钟前
C++ 数据结构进阶:unordered_map 与 unordered_set源码分析与实现
数据结构·c++·算法·哈希算法
天赐学c语言10 分钟前
Linux - 网络应用层协议HTTP
linux·c++·网络服务
C蔡博士13 分钟前
最小生成树(MST)详解:定义、算法与核心性质
算法·贪心算法·图论·时间复杂度
wWYy.13 分钟前
STL:map与unordered_map
开发语言·c++·stl
sxtyjty15 分钟前
AtCoder Beginner Contest 450 G题题解
数学·算法·期望
code_whiter16 分钟前
C++4(类与对象下篇)
c++