HDU 1969 搜索 浮点数二分

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

一个对精度要求比较高的浮点数二分,大体题意就是分蛋糕,求每个人能分得的蛋糕最大是多少,而且每个人得到的蛋糕只能来自一块的一部分,不能将零碎的蛋糕拼起来给一个人。

比如说现在这个蛋糕大小是1.5,每个人要分1,那么剩下的0.5就要扔掉了。还要注意自己也要留一块,也就是人数要加一,还要注意输出的格式,保留四位小数。

浮点数二分的while里面有两种写法,一个是常规的l<r,另一种就是执行100次,这样可以保证精度足够。

这里可以二分蛋糕的体积,也可以二分半径的平方,都可以,两种方式我都交了一次,貌似没有出现精度问题都AC了。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

const double PI=acos(-1),eps=1e-6;
const int N=10010;

int n,t,f;
double a[N];

int main()
{
	cin>>t;
	
	while(t--)
	{
		double maxx=-1;
		scanf("%d%d",&n,&f);
		for(int i=1;i<=n;i++)
		{
			scanf("%lf",&a[i]);
			a[i]=a[i]*a[i];
			if(a[i]-maxx>eps) maxx=a[i];
		}
		
		double mid,l=0.0,r=maxx;
		
		while(r-l>eps)
		{
			mid=(l+r)/2;
			
			int cnt=0;
			for(int i=1;i<=n;i++)
				cnt=cnt+(int)(a[i]/mid);
			
//			cout<<mid<<' '<<cnt<<endl;
			
			if(cnt>=f+1) l=mid;
			else r=mid;
				
		}
		
		printf("%.4f\n",l*PI);
		
	}
	
	
	
	return 0;
}
发布了43 篇原创文章 · 获赞 1 · 访问量 1587

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/104149052