C++二分法思想相关题目及题解

题目来源某公司真题,我觉得非常好

珂珂喜欢吃香蕉。这里有 N 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 H 小时后回来。珂珂可以决定她吃香蕉的速度 K (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K 根。如果这堆香蕉少于 K 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。 珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。返回她可以在 H 小时内吃掉所有香蕉的最小速度 K(K 为整数)。

解题思路:利用二分法去逼近正确答案,左边界一定不满足条件,右边满足条件时候一定是最小速度K。代码如下。

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class Solution{
  public:
      int banana(vector<int> arr,int h)
      {
          int len=arr.size();
          int mid;
          sort(arr.begin(),arr.end());
          int l=0,r=arr[len-1];
          mid=l+(r-l)/2;
          while(l!=r)
          {
              int count=0;
              for(int i=0;i<arr.size();i++)
              {
                  if(arr[i]/mid==0)
                  {
                      count++;
                  }
                  else{
                      if(arr[i]%mid==0)
                      {
                          count+=arr[i]/mid;
                      }
                      else{
                          count+=arr[i]/mid+1;
                      }
                  }
              }
              if(count>h)
              {
                  l=mid+1;
                  mid=l+(r-l)/2;
              }
              else
              {
                  r=mid;
                  mid=l+(r-l)/2;
              }
          }
          return r;
      }
};


int main()
{
     string str;
    vector<int> nums;
    while(cin >> str)
    {
        int sum = 0;
        int target;
        for(int i = 1; i < str.size(); i++)
        {
            if(str[i] != ',' && str[i] != ']' && str[i] != ';')
            {
                int num = str[i] - '0';
                 sum = sum * 10 + num;
            }
            else if(str[i] == ',' || str[i] == ']')
            {
                nums.push_back(sum);
                sum = 0;
            }
            else if(str[i] == ';')
            {
                int j = i + 1;
                int a = 0;
                while(j < str.size())
                {
                    int b = str[j] - '0';
                    a = a * 10 + b;
                    j++;
                }
                target = a;
                break;
            }
        }
    

    Solution s;
    auto str=s.banana(nums,target);
    cout<<str;
   
}
 return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值