题目描述

有N条绳子,它们的长度分别为Li。如果从它们中切割出K条长度相同的绳子,这K条绳子每条最长能有多长?答案保留到小数点后2位(直接舍掉2位后的小数)。

输入输出格式

输入格式:

第一行两个整数N和K(0<N<=10000, 0<K<=10000),接下来N行,描述了每条绳子的长度Li(0<Li<=100000.00)。

输出格式:

切割后每条绳子的最大长度。

输入输出样例

输入样例#1: 

4 11

8.02

7.43

4.57

5.39

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class rope_cutting {
public:
inline static rope_cutting &get() {
static rope_cutting obj;
return obj;
}
void init(int n, int k) {
if ((false == check_limit(n)) || (false == check_limit(k))) {
return;
}
ropes_.resize(n);
for (int i = 0;i < n;i++) {
cout << i << " = ";
cin >> ropes_[i];
}
ropes_number_ = n;
cutting_ropes_number_ = k;
}
double get_res() {
double right = *max_element(begin(ropes_), end(ropes_));
double left = 0;
double mid = 0;
while (right - left > 1e-4) {
mid = (left + right) / 2;
if (get_number(mid) < cutting_ropes_number_) {
right = mid;
}
else {
left = mid;
}
}
return right;
}
private:
bool check_limit(int n) {
if (n <= 0 || n > limit) {
cerr << n << " is invalid...!" << endl;
return false;
}
return true;
}
int get_number(double len) {
int num = 0;
for (auto &rope : ropes_) {
num += static_cast<int>(rope / len);
}
return num;
}
private:
rope_cutting() = default;
~rope_cutting() = default;
private:
static const int limit = 10000;
private:
int ropes_number_;
int cutting_ropes_number_;
vector<double>ropes_;
};
int main() {
rope_cutting::get().init(4, 11);
cout << rope_cutting::get().get_res() << endl;

return 0;
}