原题:
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. Input
Output
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块蛋糕,F+1个人,每人只能分一块(不能拿几块小的拼成大的),求每人最多拿多少体积(高相等,体积即面积)
分析:
非常水的二分题,千万要注意,输入的是朋友的数量f,分pie是分给所有人,包括自己在内共f+1人
下界low=0,即每人都分不到pie
上界high=maxsize,每人都得到整个pie,而且那个pie为所有pie中最大的 (上界就是 n个人n个pie,每个pie还等大)
对当前上下界折中为mid,计算"如果按照mid的尺寸分pie,能分给多少人"
求某个pie(尺寸为size)按照mid的尺寸,能够分给的人数,就直接size / mid,舍弃小数就可以
由于每个pie都是圆的,为了保证精度和减少运算,我的程序在计算过程中把 π 先忽略,仅仅用半径R²去计算,最后的结果再乘π
没难度的二分题,若果WA要多多留意是不是精度问题,因为算法思路是很明确的,精度才是最头疼的
代码:
#include <iostream> #include <cstdio> #include<cmath> using namespace std; double pi = acos(-1.0); // 圆周率的表示 int T, n, f; double b[10003]; int juge(double x) { int total = 0; for (int i = 1; i <= n; i++) { total += int(b[i] / x); } if (total>f) return 1; else return 0; } int main() { double l, r, mid, rad; cin >> T; while (T--) { cin >> n >> f; double sum = 0; for (int i = 1; i <= n; i++) { cin >> rad; b[i] = rad*rad*pi; sum += b[i]; } l = 0; double r = sum / (f + 1); while (r - l>0.0001) // 此题精度小数点后四位 { mid = (l + r) / 2; if (juge(mid)) l = mid; else r = mid; } printf("%.4lf\n", mid); } return 0; }
原文:http://www.cnblogs.com/shawn-ji/p/4711780.html