Pie(二分)

http://poj.org/problem?id=3122

题意:将n个圆柱体的不同口味的pie分给m个人,要求每个人分得的pie必须体积相同,且来自于一块pie(即:只分得一种口味的pie),求最多每个人可分得的体积。

思路:理解了题意就好做了,二分并注意精度。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <algorithm>
 4 #include <math.h>
 5 using namespace std;
 6 const double PI=acos(-1.0);
 7 const double eps=1e-8;//设置精度
 8 const int N=10008;
 9 int main()
10 {
11     int t;
12     scanf("%d",&t);
13     while(t--)
14     {
15         int n,num;
16         double pie[N],maxn = 0,r;
17         scanf("%d %d",&n,&num);
18         num++;
19         for (int i = 0; i < n; i++)
20         {
21             scanf("%lf",&r);
22             pie[i] = r*r;//每个pie代表的体积(暂时不乘π)
23             maxn = max(maxn,pie[i]);
24         }
25         double mid;
26         double low = 0;//下限
27         double high = maxn;//上限为按最大的那块分
28         while(high-low>eps)//二分
29         {
30             mid = (high+low)/2;//每次以体积mid尝试着分
31             int cnt = 0;
32             for (int i = 0; i < n; i++)
33             {
34                 cnt+=(int)pie[i]/mid;//统计可以分的人数
35             }
36             if (cnt < num)//如果可以分的人数比原人数少,说明以mid分的体积过大
37                 high = mid;//减少上限
38             else
39                 low = mid;//增加下限
40         }
41         printf("%.4f
",mid*PI);
42     }
43     return 0;
44 }
View Code
原文地址:https://www.cnblogs.com/lahblogs/p/3384901.html