Description
To buy network cables, the Judging Committee has contacted a local network solutions provider with a request to sell for them a specified number of cables with equal lengths. The Judging Committee wants the cables to be as long as possible to sit contestants as far from each other as possible.
The Cable Master of the company was assigned to the task. He knows the length of each cable in the stock up to a centimeter, and he can cut them with a centimeter precision being told the length of the pieces he must cut. However, this time, the length is not known and the Cable Master is completely puzzled.
You are to help the Cable Master, by writing a program that will determine the maximal possible length of a cable piece that can be cut from the cables in the stock, to get the specified number of pieces.
Input
The input is ended by line containing two 0's.
Output
If it is not possible to cut the requested number of pieces each one being at least one centimeter long, then the output must contain the single number "0.00" (without quotes).
Sample Input
4 11 8.02 7.43 4.57 5.39 0 0
Sample Output
2.00
题目分析
有n条绳子,分成11段相等的,问最长的长度为多少
解题思路
虽然放在搜索里,利用二分可以做出来,而且时间减短。
源代码
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
int n,k;
double a[10005],sum;
int judge(double s)
{
int cnt = 0;
for(int i = 0; i<n; i++)
{
cnt+=(int)(a[i]/s);
}
if(cnt>=k) return 1;
return 0;
}
int main()
{
int i;
while(~scanf("%d%d",&n,&k),n+k)
{
sum = 0;
for(i = 0; i<n; i++)
{
scanf("%lf",&a[i]);
sum+=a[i];
}
sum = sum/k;
double l = 0,r = sum;
while(fabs(l-r)>0.00000001)
{
double mid = (l+r)/2;
if(judge(mid))
l = mid;
else
r = mid;
}
printf("%.2f\n",l);
}
return 0;
}