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 3 3 4 3 3 1 24 5 10 5 1 4 2 3 4 5 6 5 4 2
Sample Output
25.1327 3.1416 50.2655
题意:给出n个蛋糕的半径,求m+1个人分,分得的最大面积是多少。
解析:涉及精度问题,所以不能提前乘π,最后结果的时候乘就可以了。
二分寻找答案。
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<vector>
#include<stack>
#include<cstring>
#include<string>
using namespace std;
#define maxn 100005
#define eps 1e-6
#define PI 3.14159265359
double a[maxn];
int n,m,t;
int fun(double x)
{
int cnt = 0;
for(int i = 0; i < n; i ++)
{
double temp = a[i];
while(temp>x+eps)
{
temp -= x;
cnt ++;
}
}
if(cnt>=m)
return 1;
return 0;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
m++;
memset(a,0,sizeof a);
double sum = 0;
for(int i = 0; i < n; i ++)
{
scanf("%lf",&a[i]);
a[i] = 1.0*a[i]*a[i];
sum += a[i];
}
double l = 0.0;
double r = 1.0*sum;
while(r-l>eps)
{
double mid = (l+r)/2.0;
if(fun(mid))
l = mid;
else
r = mid;
//printf("%f %f \n",l,r);
}
printf("%.4f\n",l*PI);
}
}
一开始我对于二分的理解就是二分搜索某个数,后来发现二分的范围真的很广。
就这个题来说吧,首先计算出所有饼的半径的和作为右端点,然后将0作为左端点。
mid = (sum + 0)/ 2,那么mid就是sum/2
将这个值传到判断函数里,看看当半径为这个值的时候能分得多少块饼。
如果分得饼的数量不够一个人一块,那么将这个值设为左端点,否则将其设为右端点。
左右循环,直到l>r,找到的那个值就是最合适的。