切绳子

具体题目:
https://www.luogu.org/problemnew/show/P1577

大致意思就是给定几根绳子,切为等长度的几份。长度保留到0.01。

思路:
暴力的解法就是枚举每个可能的长度。但是由于精确到0.01,因此需要枚举的数量实在太多。

采用二分,先排序。二分起始点为0,终点为a[n-1] +1(为何这样设置我其实也有点接受不清)
注意当 mid = 0时,break.

由于是精确到0.01,可以将两位小数double类型的先乘以100保存,这样二分查找的时候,就可以±1了。
最后结果除以100即可。

输入的时候,%lf对应的是double类型,%f对应的是float类型。。

#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<cstdio>

using namespace std;
vector<int>a;
int n,m;

bool check(int k)
{
    int cnt = 0;
    for (int i=n-1;i>=0 && a[i]>=k;i--)
    {
        cnt += (a[i]/k);
    }
    return cnt>=m;
}

int main()
{

    scanf("%d%d",&n,&m);

    for (int i=0;i<n;i++)
    {
        double t;
        scanf("%lf",&t);
        a.push_back(t*100);
    }

    sort(a.begin(),a.end());

    int left = 0;
    int right = a[n-1] + 1 ;

    double ans;


    while(left<=right){
        int k = (left+right)/2;
        if (k==0)break;
        if (check(k))
        {
            left = k+1;
            ans = double(k/100.0);
        }

        else {
            right = k-1;
        }

    }

    printf ("%.2lf",ans);
    return 0;

}

参考:
https://www.cnblogs.com/Shy-key/p/7899199.html

https://www.nowcoder.com/discuss/164189?type=0&order=0&pos=10&page=0
https://blog.csdn.net/ms961516792/article/details/88596440
https://www.nowcoder.com/discuss/163780?type=0&order=0&pos=29&page=1
https://zhuanlan.zhihu.com/p/59446102?utm_source=wechat_session&utm_medium=social&utm_oi=42982413697024

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值