题干
有N条绳子,它们的长度分别为L
i
,i=1,⋯,N。如果从它们中切割出K条长度相同的绳子,这K条绳子每条最长能有多长?
输入格式:
第一行两个整数n和k(1<n<10000;1<k<10000)。
接下来n行,描述了每条绳子的长度L
i
,L
i
也是整数。
输出格式:
切割后每条绳子的最大长度。
输入样例:
4 11
802
743
457
539
输出样例:
200
解答过程
c
#include <stdio.h>
int canCut(int ropes[], int n, int k, int length) {
int count = 0;
for (int i = 0; i < n; ++i) {
count += ropes[i] / length;
}
return count >= k;
}
int maxCutLength(int ropes[], int n, int k) {
int left = 1, right = 0;
for (int i = 0; i < n; ++i) {
if (ropes[i] > right) {
right = ropes[i];
}
}
while (left <= right) {
int mid = left + (right - left) / 2;
if (canCut(ropes, n, k, mid)) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right;
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
int ropes[n];
for (int i = 0; i < n; ++i) {
scanf("%d", &ropes[i]);
}
int maxLength = maxCutLength(ropes, n, k);
printf("%d\n", maxLength);
return 0;
}