搜素算法——二分搜索-1003

来源:互联网 发布:h5排行榜页面源码 编辑:程序博客网 时间:2024/05/17 16:46

题意:来了f个人,有n个披萨饼,这些披萨饼有着相同的厚度和各自的半径,每个人吃的都是一样的数量,而且不能大家都不想去吃用剩下的边角料留下的披萨,所以就问每个人吃披萨饼的最大量。

用二分搜素,注意精度,误差限,一定要注意1e-

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


const double PI = acos(-1.0);
const double eps = 1e-5;


int n, f;
double r, v[10005];
double maxa = 0;


bool test(double x)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += int(v[i] / x);
    return sum >= (f + 1);
}


double Bsearch(double l, double r)
{
    while (r - l > eps)
    {
        double mid = (r + l) * 0.5;
        if (test(mid))
            l = mid;
        else r = mid;
    }
    return l;
}


void solve()
{
    scanf("%d%d", &n, &f);
    maxa = 0;
    for (int i = 0; i < n; i++)
    {
        scanf("%lf", &r);
        v[i] = r * r * PI;
        maxa = max(maxa, v[i]);
    }
    double ans = Bsearch(0.0, maxa);
    printf("%.4lf\n", ans);
}


int main()
{
    int t; scanf("%d", &t);
    while (t--)
        solve();
    return 0;
}

0 0
原创粉丝点击