1. 程式人生 > >HDU pie (二分查詢)

HDU pie (二分查詢)

Problem DescriptionMy 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.
InputOne 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.
OutputFor 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 Input3 3 3 4 3 3 1 24 5 10 5 1 4 2 3 4 5 6 5 4 2
Sample Output25.1327 3.1416 50.2655題目大意是要辦生日Party,有n個餡餅,有f個朋友,接下來是n個餡餅的半徑。然後是分餡餅了,
注意咯自己也要,大家都要一樣大,形狀沒什麼要求,但都要是一整塊的那種,也就是說不能從兩個餅中
各割一小塊來湊一塊,像面積為10的和6的兩塊餅(餅的厚度是1,所以面積和體積相等),
如果每人分到面積為5,則10分兩塊,6切成5,夠分3個人,如果每人6,則只能分兩個了!
題目要求我們分到的餅儘可能的大!


只要注意精度問題就可以了,一般WA 都是精度問題
運用2分搜尋:
首先用總餅的體積除以總人數,得到每個人最大可以得到的V,但是每個人手中不能有兩片或多片拼成的一塊餅,
最多隻能有一片分割過得餅。用2分搜尋時,把0設為left,把V 設為right。mid=(left+right)/2;
搜尋條件是:以mid為標誌,如果每塊餅都可以分割出一個mid,那麼返回true,說明每個人可以得到的餅的體積可以
大於等於mid;如果不能分出這麼多的mid,那麼返回false,說明每個人可以得到餅的體積小於等於mid。
(1)精度為:0.000001
(2)   pi 用反餘弦求出,精度更高。 
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n,m;
double pi= acos(-1.0);
double v[20000];
bool judge(double num)
{
	int sum=0;
	for(int i=1;i<=n;i++){
		sum+=int(v[i]/num);
	}
	if(sum>=m) return true;
	return false;
}

int main()
{
	int t,i;
	double left,right,mid;
	double sum;
	while(scanf("%d",&t)!=EOF){
		while(t--){
			scanf("%d%d",&n,&m);
			for(i=1;i<=n;i++){
				scanf("%lf",&v[i]);
				v[i]=pi*v[i]*v[i];
				sum+=v[i];
			}
			m++;
			left=0;right=sum/m;
			while(right-left>=1e-7){
				mid=(left+right)/2;
				if(judge(mid)) left=mid;
				else right=mid;
			}
			printf("%.4lf\n",mid);
		}
	}
	return 0;
}