【例1】切绳子。
题目描述
有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
输出样例#1:
2.00
(1)编程思路。
先确定初始区间[left,right],显然left=0,right可取单段绳子的最大值,然后使用二分法得到mid,测试mid是大于要求的值还是小于要求的值。如果mid值可以切出k段绳子,则增大下界,使left=mid;如果mid值切不出k段绳子,则mid取大了,减小上界,使right=mid;.然后最终使left 与right无限逼近答案。注意:程序中可以使用 while ((right-left)>1e-4)作为循环控制条件。
(2)源程序。
#include <stdio.h>
#include <math.h>
#define MAX_N 10000
double a[MAX_N+1];
int n,k;
int judge(double x)
{
int num = 0,i;
for (i = 0; i < n; i++)
num += (int)(a[i] / x);
return num;
}
int main()
{
int i;
double left,right,mid,max=0;
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
{
scanf("%lf",&a[i]);
if (max<a[i]) max=a[i];
}
left=0, right=max;
while ((right-left)>1e-4)
{
mid=(left+right)/2;
if(judge(mid)>=k) left=mid;
else right=mid;
}
printf("%.2f\n",floor(right*100)/100);
return 0;
}
将此源程序提交给POJ 1064 “Cable master”,可以Accepted。
【例2】Pie (POJ 3122)。
Description
My birthday is coming up and traditionally I'm serving pie. Not just one pie, no, I have a number N of them, of various tastes and of various sizes. F of my friends are coming to my party and each of them gets a piece of pie. This should be one piece of one pie, not several small pieces since that looks messy. This piece can be one whole pie though.
My friends are very annoying and if one of them gets a bigger piece than the others, they start complaining. Therefore all of them should get equally sized (but not necessarily equally shaped) pieces, even if this leads to some pie getting spoiled (which is better than spoiling the party). Of course, I want a piece of pie for myself too, and that piece should also be of the same size.
What is the largest possible piece size all of us can get? All the pies are cylindrical in shape and they all have the same height 1, but the radii of the pies can be different.
Input
One line with a positive integer: the number of test cases. Then for each test case:
One line with two integers N and F with 1 ≤ N, F ≤ 10 000: the number of pies and the number of friends.
One line with N integers ri with 1 ≤ ri ≤ 10 000: the radii of the pies.
Output
For each test case, output one line with the largest possible volume V such that me and my friends can all get a pie piece of size V. The answer should be given as a floating point number with an absolute error of at most 10?3.
Sample Input
3